From a19a7c8f6b131c7cce1d9f2b5ceaab1a4faaed66 Mon Sep 17 00:00:00 2001 From: Markus Hintersteiner Date: Fri, 20 Nov 2026 09:56:23 +0100 Subject: [PATCH 1/6] feat(anr): Add ThreadSampleCollector --- .../api/sentry-android-core.api | 10 + .../android/core/anr/AnrProfileManager.java | 11 +- .../core/hang/ThreadSampleCollector.java | 131 +++++++++++ .../android/core/hang/HangRecorderTest.kt | 38 ++- .../core/hang/ThreadSampleCollectorTest.kt | 221 ++++++++++++++++++ 5 files changed, 398 insertions(+), 13 deletions(-) create mode 100644 sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java create mode 100644 sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 5db38fadc3a..8e39c9f533d 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -746,6 +746,7 @@ public final class io/sentry/android/core/anr/AnrProfile { } public final class io/sentry/android/core/anr/AnrProfileManager : java/lang/AutoCloseable { + public static final field MAX_NUM_STACKTRACES I public fun (Lio/sentry/SentryOptions;)V public fun (Lio/sentry/SentryOptions;Ljava/io/File;)V public fun add (Lio/sentry/android/core/anr/AnrStackTrace;)V @@ -904,6 +905,15 @@ public abstract interface class io/sentry/android/core/hang/ThreadPoster { public abstract fun remove (Ljava/lang/Runnable;)V } +public final class io/sentry/android/core/hang/ThreadSampleCollector : io/sentry/android/core/hang/HangDataCollector { + public fun (Lio/sentry/SentryOptions;Lio/sentry/time/EpochClock;Lio/sentry/time/MonotonicTicker;Ljava/lang/Thread;)V + public fun close ()V + public fun onRecordingCanceled ()V + public fun onRecordingStarted (Lio/sentry/android/core/hang/HangInterval;)V + public fun onRecordingStopped (Lio/sentry/android/core/hang/HangInterval;Lio/sentry/android/core/hang/HangRecord$Builder;)V + public fun onSample (Lio/sentry/android/core/hang/HangInterval;)V +} + public abstract class io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter : android/app/Application$ActivityLifecycleCallbacks { public fun ()V public fun onActivityCreated (Landroid/app/Activity;Landroid/os/Bundle;)V diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java index dd3cffc3ffc..ffa5749fc43 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java @@ -1,11 +1,10 @@ package io.sentry.android.core.anr; import static io.sentry.SentryLevel.ERROR; -import static io.sentry.android.core.anr.AnrProfilingIntegration.POLLING_INTERVAL_MS; -import static io.sentry.android.core.anr.AnrProfilingIntegration.THRESHOLD_ANR_MS; import io.sentry.ILogger; import io.sentry.SentryOptions; +import io.sentry.android.core.hang.HangRecorder; import io.sentry.cache.tape.ObjectQueue; import io.sentry.cache.tape.QueueFile; import io.sentry.util.Objects; @@ -22,8 +21,12 @@ @ApiStatus.Internal public final class AnrProfileManager implements AutoCloseable { - private static final int MAX_NUM_STACKTRACES = - (int) ((THRESHOLD_ANR_MS / POLLING_INTERVAL_MS) * 2); + /** + * One sample per {@link HangRecorder#DEFAULT_POLLING_INTERVAL_MS} tick for {@link + * HangRecorder#DEFAULT_MAX_RECORDING_TIME_MS}. The ThreadSampleCollector stops at this size, + * because a full file drops its oldest entry. + */ + public static final int MAX_NUM_STACKTRACES = 120; @NotNull private final ObjectQueue queue; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java new file mode 100644 index 00000000000..75ef4a7cf69 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java @@ -0,0 +1,131 @@ +package io.sentry.android.core.hang; + +import static java.util.concurrent.TimeUnit.NANOSECONDS; + +import io.sentry.SentryLevel; +import io.sentry.SentryOptions; +import io.sentry.android.core.anr.AnrProfileManager; +import io.sentry.android.core.anr.AnrProfileRotationHelper; +import io.sentry.android.core.anr.AnrStackTrace; +import io.sentry.time.EpochClock; +import io.sentry.time.MonotonicTicker; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Samples the stack of a thread on each tick of a hang interval. The samples stay in memory until + * the interval is {@link #DISK_THRESHOLD_MS} old, then they are written to the ANR profile file, so + * the fatal ANR path can still read them if the process is killed. + * + *

Not thread-safe, {@link HangRecorder} calls it only on its recorder thread. + */ +@ApiStatus.Internal +public final class ThreadSampleCollector implements HangDataCollector { + + static final long DISK_THRESHOLD_MS = 700; + + private final @NotNull SentryOptions options; + private final @NotNull EpochClock epochClock; + private final @NotNull MonotonicTicker ticker; + private final @NotNull Thread thread; + private final @NotNull List samples = new ArrayList<>(); + private @Nullable AnrProfileManager profileManager; + private boolean onDisk; + + public ThreadSampleCollector( + final @NotNull SentryOptions options, + final @NotNull EpochClock epochClock, + final @NotNull MonotonicTicker ticker, + final @NotNull Thread thread) { + this.options = options; + this.epochClock = epochClock; + this.ticker = ticker; + this.thread = thread; + } + + @Override + public void onRecordingStarted(final @NotNull HangInterval interval) { + reset(); + if (profileManager == null) { + final @Nullable String cacheDirPath = options.getCacheDirPath(); + if (cacheDirPath != null) { + final @NotNull File file = + AnrProfileRotationHelper.getFileForRecording(new File(cacheDirPath)); + profileManager = new AnrProfileManager(options, file); + } + } + } + + @Override + public void onSample(final @NotNull HangInterval interval) { + if (samples.size() >= AnrProfileManager.MAX_NUM_STACKTRACES) { + return; + } + + final long epochMs = NANOSECONDS.toMillis(epochClock.now().epochNanos()); + final @NotNull AnrStackTrace sample = + new AnrStackTrace(epochMs, thread.getStackTrace(), thread.getState()); + samples.add(sample); + + final long nowMs = NANOSECONDS.toMillis(ticker.tickNanos()); + // Most hangs end before this, so they cause no disk IO. + if (nowMs - interval.getStartTimeMs() < DISK_THRESHOLD_MS) { + return; + } + + final @Nullable AnrProfileManager manager = profileManager; + if (manager == null) { + return; + } + + try { + if (!onDisk) { + onDisk = true; + startDiskRecording(manager); + } else { + manager.add(sample); + } + } catch (IOException e) { + options.getLogger().log(SentryLevel.WARNING, "Failed to write the thread samples", e); + } + } + + private void startDiskRecording(final @NotNull AnrProfileManager manager) throws IOException { + manager.clear(); + for (final @NotNull AnrStackTrace buffered : samples) { + manager.add(buffered); + } + } + + @Override + public void onRecordingStopped( + final @NotNull HangInterval interval, final @NotNull HangRecord.Builder out) { + out.setSamples(new ArrayList<>(samples)); + } + + /** Discards the samples in memory only, the fatal path keeps the file. */ + @Override + public void onRecordingCanceled() { + reset(); + } + + @Override + public void close() throws IOException { + reset(); + final @Nullable AnrProfileManager manager = profileManager; + profileManager = null; + if (manager != null) { + manager.close(); + } + } + + private void reset() { + samples.clear(); + onDisk = false; + } +} diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt index c43f3094083..12835000b2f 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt @@ -10,6 +10,7 @@ import io.sentry.android.core.anr.AnrStackTrace import io.sentry.android.core.hang.HangRecorder.DEFAULT_MAX_RECORDING_TIME_MS import io.sentry.android.core.hang.HangRecorder.DEFAULT_POLLING_INTERVAL_MS import io.sentry.test.DeferredExecutorService +import io.sentry.test.ImmediateExecutorService import io.sentry.test.NonOverridableNoOpSentryExecutorService import io.sentry.time.EpochClock import io.sentry.time.JavaMonotonicTicker @@ -19,6 +20,7 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.HOURS import java.util.concurrent.TimeUnit.MILLISECONDS +import java.util.concurrent.locks.LockSupport import kotlin.test.BeforeTest import kotlin.test.Test import org.mockito.kotlin.any @@ -668,20 +670,31 @@ class HangRecorderTest { } @Test - fun `recorder on the default executor posts the probe of a thread signal`() { - val posted = CountDownLatch(1) + fun `recorder on the default executor records the stack of the watched thread`() { + val parked = Thread { while (!Thread.currentThread().isInterrupted) LockSupport.park() } + parked.isDaemon = true + parked.start() + var posts = 0 val poster = object : ThreadPoster { - override fun post(runnable: Runnable) = posted.countDown() + // The probe runs only at the 10th tick, so the thread looks blocked for about 600 ms. + override fun post(runnable: Runnable) { + if (++posts == 10) { + runnable.run() + } + } override fun remove(runnable: Runnable) = Unit } + val ticker = JavaMonotonicTicker.getInstance() + val recorded = CountDownLatch(1) + var record: HangRecord? = null appStateProvider.foreground() val created = HangRecorder( - options, + SentryOptions().apply { executorService = ImmediateExecutorService() }, appStateProvider, - JavaMonotonicTicker.getInstance(), + ticker, epochClock, DEFAULT_POLLING_INTERVAL_MS, DEFAULT_MAX_RECORDING_TIME_MS, @@ -690,23 +703,30 @@ class HangRecorderTest { listOf( ThreadHangSignal( metronome, - JavaMonotonicTicker.getInstance(), + ticker, { false }, poster, HangRecorder.DEFAULT_SUSPICIOUS_THRESHOLD_MS, ), ) }, - emptyList(), + listOf(ThreadSampleCollector(SentryOptions(), epochClock, ticker, parked)), ) - created.subscribe(listener) + created.subscribe { + record = it + recorded.countDown() + } try { - assertThat(posted.await(10, TimeUnit.SECONDS)).isTrue() + assertThat(recorded.await(10, TimeUnit.SECONDS)).isTrue() } finally { created.close() + parked.interrupt() + parked.join() } + assertThat(record!!.samples).isNotEmpty() + assertThat(record!!.samples.first().stack.map { it.methodName }).contains("park") } private class FakeAppStateProvider : AppStateProvider { diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt new file mode 100644 index 00000000000..859747d024d --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt @@ -0,0 +1,221 @@ +package io.sentry.android.core.hang + +import com.google.common.truth.Truth.assertThat +import io.sentry.SentryOptions +import io.sentry.android.core.anr.AnrProfileManager +import io.sentry.android.core.anr.AnrProfileRotationHelper +import io.sentry.android.core.anr.AnrStackTrace +import io.sentry.time.EpochClock +import io.sentry.time.TestMonotonicTicker +import io.sentry.time.Timestamp +import java.io.File +import java.nio.file.Files +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeUnit.HOURS +import java.util.concurrent.TimeUnit.MILLISECONDS +import java.util.concurrent.locks.LockSupport +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test + +class ThreadSampleCollectorTest { + + private lateinit var cacheDir: File + private lateinit var ticker: TestMonotonicTicker + private var unixTimeMs = 1_700_000_000_000L + private lateinit var epochClock: EpochClock + private lateinit var options: SentryOptions + private lateinit var collector: ThreadSampleCollector + private lateinit var interval: HangInterval + + @BeforeTest + fun setUp() { + cacheDir = Files.createTempDirectory("thread-sample-collector").toFile() + // Rotation moves an existing file once per process, do it before any file is seeded. + AnrProfileRotationHelper.getFileForRecording(cacheDir) + ticker = TestMonotonicTicker(HOURS.toNanos(30)) + epochClock = EpochClock { Timestamp.ofEpochNanos(MILLISECONDS.toNanos(unixTimeMs)) } + options = SentryOptions() + options.cacheDirPath = cacheDir.absolutePath + collector = ThreadSampleCollector(options, epochClock, ticker, Thread.currentThread()) + } + + @AfterTest + fun tearDown() { + collector.close() + cacheDir.deleteRecursively() + } + + private fun nowMs(): Long = TimeUnit.NANOSECONDS.toMillis(ticker.tickNanos()) + + private fun startInterval() { + interval = HangInterval(nowMs()) + collector.onRecordingStarted(interval) + } + + private fun advance(ms: Long) { + ticker.advance(ms, MILLISECONDS) + unixTimeMs += ms + } + + private fun sampleEvery66Ms(count: Int) { + repeat(count) { + collector.onSample(interval) + advance(66) + } + } + + private fun file() = File(cacheDir, "anr_profile") + + private fun readFile(): List { + // The collector keeps the queue open, so release it before reading from a second manager. + collector.close() + AnrProfileManager(options, file()).use { + return it.load().stacks + } + } + + private fun seedFile(timestampMs: Long) { + AnrProfileManager(options, file()).use { it.add(AnrStackTrace(timestampMs, emptyArray())) } + } + + @Test + fun `samples stay in memory before 700ms`() { + startInterval() + sampleEvery66Ms(10) // 0..594 ms + + val builder = HangRecord.Builder(660, unixTimeMs) + collector.onRecordingStopped(interval, builder) + assertThat(builder.build().samples).hasSize(10) + assertThat(readFile()).isEmpty() + } + + @Test + fun `onRecordingStarted opens the profile file before the first sample`() { + startInterval() + + assertThat(file().exists()).isTrue() + } + + @Test + fun `at 700ms file is cleared then buffer and new samples are written`() { + seedFile(1) + startInterval() + sampleEvery66Ms(11) // 0..660 ms + assertThat(AnrProfileManager(options, file()).use { it.load().stacks }.map { it.timestampMs }) + .containsExactly(1L) + + collector.onSample(interval) // 726 ms: first one past the threshold + advance(66) + collector.onSample(interval) // 792 ms + + val timestamps = readFile().map { it.timestampMs } + assertThat(timestamps).hasSize(13) + assertThat(timestamps).doesNotContain(1L) + assertThat(timestamps).isInOrder() + assertThat(timestamps.first()).isEqualTo(1_700_000_000_000L) + } + + @Test + fun `stops sampling when the file is full but keeps samples`() { + startInterval() + sampleEvery66Ms(150) + + val builder = HangRecord.Builder(0, unixTimeMs) + collector.onRecordingStopped(interval, builder) + assertThat(builder.build().samples).hasSize(120) + val timestamps = readFile().map { it.timestampMs } + assertThat(timestamps).hasSize(120) + assertThat(timestamps.first()).isEqualTo(1_700_000_000_000L) + } + + @Test + fun `onRecordingStopped puts samples and thread state into record`() { + val parked = Thread { while (!Thread.currentThread().isInterrupted) LockSupport.park() } + parked.isDaemon = true + parked.start() + try { + val deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (parked.state != Thread.State.WAITING && System.nanoTime() < deadlineNanos) { + Thread.yield() + } + assertThat(parked.state).isEqualTo(Thread.State.WAITING) + collector = ThreadSampleCollector(options, epochClock, ticker, parked) + startInterval() + collector.onSample(interval) + + val builder = HangRecord.Builder(66, unixTimeMs) + collector.onRecordingStopped(interval, builder) + val sample = builder.build().samples.single() + assertThat(sample.state).isEqualTo(Thread.State.WAITING) + assertThat(sample.timestampMs).isEqualTo(unixTimeMs) + assertThat(sample.stack).isNotEmpty() + } finally { + parked.interrupt() + parked.join() + } + } + + @Test + fun `onRecordingCanceled drops the samples in memory but keeps the file`() { + startInterval() + sampleEvery66Ms(12) + + collector.onRecordingCanceled() + + val builder = HangRecord.Builder(0, unixTimeMs) + collector.onRecordingStopped(interval, builder) + assertThat(builder.build().samples).isEmpty() + assertThat(readFile()).hasSize(12) + } + + @Test + fun `interval after onRecordingCanceled clears the file once`() { + startInterval() + sampleEvery66Ms(12) + collector.onRecordingCanceled() + startInterval() + sampleEvery66Ms(12) + + val timestamps = readFile().map { it.timestampMs } + assertThat(timestamps).hasSize(12) + assertThat(timestamps.first()).isAtLeast(1_700_000_000_000L + 12 * 66) + } + + @Test + fun `second interval clears the file once`() { + startInterval() + sampleEvery66Ms(12) + startInterval() + sampleEvery66Ms(12) + + val timestamps = readFile().map { it.timestampMs } + assertThat(timestamps).hasSize(12) + assertThat(timestamps.first()).isAtLeast(1_700_000_000_000L + 12 * 66) + } + + @Test + fun `close drops the samples in memory`() { + startInterval() + sampleEvery66Ms(5) + + collector.close() + + val builder = HangRecord.Builder(0, unixTimeMs) + collector.onRecordingStopped(interval, builder) + assertThat(builder.build().samples).isEmpty() + } + + @Test + fun `keeps samples in memory when cacheDirPath is null at onRecordingStarted`() { + options.cacheDirPath = null + startInterval() + options.cacheDirPath = cacheDir.absolutePath + sampleEvery66Ms(15) + + val builder = HangRecord.Builder(0, unixTimeMs) + collector.onRecordingStopped(interval, builder) + assertThat(builder.build().samples).hasSize(15) + assertThat(file().exists()).isFalse() + } +} From 79a512a816edece4a094e15aadf1a6030356eed1 Mon Sep 17 00:00:00 2001 From: Markus Hintersteiner Date: Mon, 23 Nov 2026 09:00:18 +0100 Subject: [PATCH 2/6] ref(anr): Make ThreadSampleCollector a pure reader --- .../api/sentry-android-core.api | 9 +- .../android/core/anr/AnrProfileManager.java | 2 +- .../core/hang/ThreadSampleCollector.java | 107 +--------- .../android/core/hang/HangRecorderTest.kt | 16 +- .../core/hang/ThreadSampleCollectorTest.kt | 197 ++---------------- 5 files changed, 43 insertions(+), 288 deletions(-) diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 9ab9502e375..03ff6dcd7e4 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -927,12 +927,11 @@ public abstract interface class io/sentry/android/core/hang/ThreadPoster { } public final class io/sentry/android/core/hang/ThreadSampleCollector : io/sentry/android/core/hang/HangDataCollector { - public fun (Lio/sentry/SentryOptions;Lio/sentry/time/EpochClock;Lio/sentry/time/MonotonicTicker;Ljava/lang/Thread;)V + public fun (Lio/sentry/time/EpochClock;Ljava/lang/Thread;)V public fun close ()V - public fun onRecordingCanceled ()V - public fun onRecordingStarted (Lio/sentry/android/core/hang/HangInterval;)V - public fun onRecordingStopped (Lio/sentry/android/core/hang/HangInterval;Lio/sentry/android/core/hang/HangRecord$Builder;)V - public fun onSample (Lio/sentry/android/core/hang/HangInterval;)V + public fun onRecordingStopped (Ljava/util/List;Lio/sentry/android/core/hang/HangRecord$Builder;)V + public fun onSample (Lio/sentry/android/core/hang/HangInterval;)Lio/sentry/android/core/anr/AnrStackTrace; + public synthetic fun onSample (Lio/sentry/android/core/hang/HangInterval;)Ljava/lang/Object; } public abstract class io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter : android/app/Application$ActivityLifecycleCallbacks { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java index ffa5749fc43..498e0b8a84b 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java @@ -23,7 +23,7 @@ public final class AnrProfileManager implements AutoCloseable { /** * One sample per {@link HangRecorder#DEFAULT_POLLING_INTERVAL_MS} tick for {@link - * HangRecorder#DEFAULT_MAX_RECORDING_TIME_MS}. The ThreadSampleCollector stops at this size, + * HangRecorder#DEFAULT_MAX_RECORDING_TIME_MS}. The hang recorder stops sampling at this size, * because a full file drops its oldest entry. */ public static final int MAX_NUM_STACKTRACES = 120; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java index 75ef4a7cf69..408521b223a 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java @@ -2,130 +2,37 @@ import static java.util.concurrent.TimeUnit.NANOSECONDS; -import io.sentry.SentryLevel; -import io.sentry.SentryOptions; -import io.sentry.android.core.anr.AnrProfileManager; -import io.sentry.android.core.anr.AnrProfileRotationHelper; import io.sentry.android.core.anr.AnrStackTrace; import io.sentry.time.EpochClock; -import io.sentry.time.MonotonicTicker; -import java.io.File; -import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -/** - * Samples the stack of a thread on each tick of a hang interval. The samples stay in memory until - * the interval is {@link #DISK_THRESHOLD_MS} old, then they are written to the ANR profile file, so - * the fatal ANR path can still read them if the process is killed. - * - *

Not thread-safe, {@link HangRecorder} calls it only on its recorder thread. - */ +/** Samples the stack and the state of a thread on each tick of a hang interval. */ @ApiStatus.Internal -public final class ThreadSampleCollector implements HangDataCollector { +public final class ThreadSampleCollector implements HangDataCollector { - static final long DISK_THRESHOLD_MS = 700; - - private final @NotNull SentryOptions options; private final @NotNull EpochClock epochClock; - private final @NotNull MonotonicTicker ticker; private final @NotNull Thread thread; - private final @NotNull List samples = new ArrayList<>(); - private @Nullable AnrProfileManager profileManager; - private boolean onDisk; - public ThreadSampleCollector( - final @NotNull SentryOptions options, - final @NotNull EpochClock epochClock, - final @NotNull MonotonicTicker ticker, - final @NotNull Thread thread) { - this.options = options; + public ThreadSampleCollector(final @NotNull EpochClock epochClock, final @NotNull Thread thread) { this.epochClock = epochClock; - this.ticker = ticker; this.thread = thread; } @Override - public void onRecordingStarted(final @NotNull HangInterval interval) { - reset(); - if (profileManager == null) { - final @Nullable String cacheDirPath = options.getCacheDirPath(); - if (cacheDirPath != null) { - final @NotNull File file = - AnrProfileRotationHelper.getFileForRecording(new File(cacheDirPath)); - profileManager = new AnrProfileManager(options, file); - } - } - } - - @Override - public void onSample(final @NotNull HangInterval interval) { - if (samples.size() >= AnrProfileManager.MAX_NUM_STACKTRACES) { - return; - } - + public @NotNull AnrStackTrace onSample(final @NotNull HangInterval interval) { final long epochMs = NANOSECONDS.toMillis(epochClock.now().epochNanos()); - final @NotNull AnrStackTrace sample = - new AnrStackTrace(epochMs, thread.getStackTrace(), thread.getState()); - samples.add(sample); - - final long nowMs = NANOSECONDS.toMillis(ticker.tickNanos()); - // Most hangs end before this, so they cause no disk IO. - if (nowMs - interval.getStartTimeMs() < DISK_THRESHOLD_MS) { - return; - } - - final @Nullable AnrProfileManager manager = profileManager; - if (manager == null) { - return; - } - - try { - if (!onDisk) { - onDisk = true; - startDiskRecording(manager); - } else { - manager.add(sample); - } - } catch (IOException e) { - options.getLogger().log(SentryLevel.WARNING, "Failed to write the thread samples", e); - } - } - - private void startDiskRecording(final @NotNull AnrProfileManager manager) throws IOException { - manager.clear(); - for (final @NotNull AnrStackTrace buffered : samples) { - manager.add(buffered); - } + return new AnrStackTrace(epochMs, thread.getStackTrace(), thread.getState()); } @Override public void onRecordingStopped( - final @NotNull HangInterval interval, final @NotNull HangRecord.Builder out) { + final @NotNull List samples, final @NotNull HangRecord.Builder out) { out.setSamples(new ArrayList<>(samples)); } - /** Discards the samples in memory only, the fatal path keeps the file. */ - @Override - public void onRecordingCanceled() { - reset(); - } - @Override - public void close() throws IOException { - reset(); - final @Nullable AnrProfileManager manager = profileManager; - profileManager = null; - if (manager != null) { - manager.close(); - } - } - - private void reset() { - samples.clear(); - onDisk = false; - } + public void close() {} } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt index 5c5d16d2285..ac79a6cf8b7 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt @@ -1032,13 +1032,19 @@ class HangRecorderTest { ), ) }, - listOf(ThreadSampleCollector(SentryOptions(), epochClock, ticker, parked)), + listOf(CollectorSetup(ThreadSampleCollector(epochClock, parked), null)), ) - created.subscribe { - record = it - recorded.countDown() - } + created.subscribe( + object : HangRecorderListener { + override fun onHangStarted(interval: HangInterval) = HangRecordingRequest.DEFAULT + + override fun onHangRecorded(hangRecord: HangRecord) { + record = hangRecord + recorded.countDown() + } + }, + ) try { assertThat(recorded.await(10, TimeUnit.SECONDS)).isTrue() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt index 859747d024d..c8ddabe13d1 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt @@ -1,136 +1,22 @@ package io.sentry.android.core.hang import com.google.common.truth.Truth.assertThat -import io.sentry.SentryOptions -import io.sentry.android.core.anr.AnrProfileManager -import io.sentry.android.core.anr.AnrProfileRotationHelper import io.sentry.android.core.anr.AnrStackTrace import io.sentry.time.EpochClock -import io.sentry.time.TestMonotonicTicker import io.sentry.time.Timestamp -import java.io.File -import java.nio.file.Files import java.util.concurrent.TimeUnit -import java.util.concurrent.TimeUnit.HOURS import java.util.concurrent.TimeUnit.MILLISECONDS import java.util.concurrent.locks.LockSupport -import kotlin.test.AfterTest -import kotlin.test.BeforeTest import kotlin.test.Test class ThreadSampleCollectorTest { - private lateinit var cacheDir: File - private lateinit var ticker: TestMonotonicTicker private var unixTimeMs = 1_700_000_000_000L - private lateinit var epochClock: EpochClock - private lateinit var options: SentryOptions - private lateinit var collector: ThreadSampleCollector - private lateinit var interval: HangInterval - - @BeforeTest - fun setUp() { - cacheDir = Files.createTempDirectory("thread-sample-collector").toFile() - // Rotation moves an existing file once per process, do it before any file is seeded. - AnrProfileRotationHelper.getFileForRecording(cacheDir) - ticker = TestMonotonicTicker(HOURS.toNanos(30)) - epochClock = EpochClock { Timestamp.ofEpochNanos(MILLISECONDS.toNanos(unixTimeMs)) } - options = SentryOptions() - options.cacheDirPath = cacheDir.absolutePath - collector = ThreadSampleCollector(options, epochClock, ticker, Thread.currentThread()) - } - - @AfterTest - fun tearDown() { - collector.close() - cacheDir.deleteRecursively() - } - - private fun nowMs(): Long = TimeUnit.NANOSECONDS.toMillis(ticker.tickNanos()) - - private fun startInterval() { - interval = HangInterval(nowMs()) - collector.onRecordingStarted(interval) - } - - private fun advance(ms: Long) { - ticker.advance(ms, MILLISECONDS) - unixTimeMs += ms - } - - private fun sampleEvery66Ms(count: Int) { - repeat(count) { - collector.onSample(interval) - advance(66) - } - } - - private fun file() = File(cacheDir, "anr_profile") - - private fun readFile(): List { - // The collector keeps the queue open, so release it before reading from a second manager. - collector.close() - AnrProfileManager(options, file()).use { - return it.load().stacks - } - } - - private fun seedFile(timestampMs: Long) { - AnrProfileManager(options, file()).use { it.add(AnrStackTrace(timestampMs, emptyArray())) } - } - - @Test - fun `samples stay in memory before 700ms`() { - startInterval() - sampleEvery66Ms(10) // 0..594 ms - - val builder = HangRecord.Builder(660, unixTimeMs) - collector.onRecordingStopped(interval, builder) - assertThat(builder.build().samples).hasSize(10) - assertThat(readFile()).isEmpty() - } - - @Test - fun `onRecordingStarted opens the profile file before the first sample`() { - startInterval() - - assertThat(file().exists()).isTrue() - } - - @Test - fun `at 700ms file is cleared then buffer and new samples are written`() { - seedFile(1) - startInterval() - sampleEvery66Ms(11) // 0..660 ms - assertThat(AnrProfileManager(options, file()).use { it.load().stacks }.map { it.timestampMs }) - .containsExactly(1L) - - collector.onSample(interval) // 726 ms: first one past the threshold - advance(66) - collector.onSample(interval) // 792 ms - - val timestamps = readFile().map { it.timestampMs } - assertThat(timestamps).hasSize(13) - assertThat(timestamps).doesNotContain(1L) - assertThat(timestamps).isInOrder() - assertThat(timestamps.first()).isEqualTo(1_700_000_000_000L) - } - - @Test - fun `stops sampling when the file is full but keeps samples`() { - startInterval() - sampleEvery66Ms(150) - - val builder = HangRecord.Builder(0, unixTimeMs) - collector.onRecordingStopped(interval, builder) - assertThat(builder.build().samples).hasSize(120) - val timestamps = readFile().map { it.timestampMs } - assertThat(timestamps).hasSize(120) - assertThat(timestamps.first()).isEqualTo(1_700_000_000_000L) - } + private val epochClock = EpochClock { Timestamp.ofEpochNanos(MILLISECONDS.toNanos(unixTimeMs)) } + private val interval = HangInterval(0) @Test - fun `onRecordingStopped puts samples and thread state into record`() { + fun `onSample returns the stack, the state and the time of the thread`() { val parked = Thread { while (!Thread.currentThread().isInterrupted) LockSupport.park() } parked.isDaemon = true parked.start() @@ -140,16 +26,13 @@ class ThreadSampleCollectorTest { Thread.yield() } assertThat(parked.state).isEqualTo(Thread.State.WAITING) - collector = ThreadSampleCollector(options, epochClock, ticker, parked) - startInterval() - collector.onSample(interval) + val collector = ThreadSampleCollector(epochClock, parked) + + val sample = collector.onSample(interval) - val builder = HangRecord.Builder(66, unixTimeMs) - collector.onRecordingStopped(interval, builder) - val sample = builder.build().samples.single() assertThat(sample.state).isEqualTo(Thread.State.WAITING) assertThat(sample.timestampMs).isEqualTo(unixTimeMs) - assertThat(sample.stack).isNotEmpty() + assertThat(sample.stack.map { it.methodName }).contains("park") } finally { parked.interrupt() parked.join() @@ -157,65 +40,25 @@ class ThreadSampleCollectorTest { } @Test - fun `onRecordingCanceled drops the samples in memory but keeps the file`() { - startInterval() - sampleEvery66Ms(12) + fun `each onSample reads the clock again`() { + val collector = ThreadSampleCollector(epochClock, Thread.currentThread()) - collector.onRecordingCanceled() + val first = collector.onSample(interval) + unixTimeMs += 66 + val second = collector.onSample(interval) - val builder = HangRecord.Builder(0, unixTimeMs) - collector.onRecordingStopped(interval, builder) - assertThat(builder.build().samples).isEmpty() - assertThat(readFile()).hasSize(12) + assertThat(second.timestampMs - first.timestampMs).isEqualTo(66) } @Test - fun `interval after onRecordingCanceled clears the file once`() { - startInterval() - sampleEvery66Ms(12) - collector.onRecordingCanceled() - startInterval() - sampleEvery66Ms(12) + fun `onRecordingStopped puts a copy of the samples into the record`() { + val collector = ThreadSampleCollector(epochClock, Thread.currentThread()) + val samples = mutableListOf(AnrStackTrace(1, emptyArray()), AnrStackTrace(2, emptyArray())) + val builder = HangRecord.Builder(66, unixTimeMs) - val timestamps = readFile().map { it.timestampMs } - assertThat(timestamps).hasSize(12) - assertThat(timestamps.first()).isAtLeast(1_700_000_000_000L + 12 * 66) - } - - @Test - fun `second interval clears the file once`() { - startInterval() - sampleEvery66Ms(12) - startInterval() - sampleEvery66Ms(12) - - val timestamps = readFile().map { it.timestampMs } - assertThat(timestamps).hasSize(12) - assertThat(timestamps.first()).isAtLeast(1_700_000_000_000L + 12 * 66) - } - - @Test - fun `close drops the samples in memory`() { - startInterval() - sampleEvery66Ms(5) - - collector.close() - - val builder = HangRecord.Builder(0, unixTimeMs) - collector.onRecordingStopped(interval, builder) - assertThat(builder.build().samples).isEmpty() - } - - @Test - fun `keeps samples in memory when cacheDirPath is null at onRecordingStarted`() { - options.cacheDirPath = null - startInterval() - options.cacheDirPath = cacheDir.absolutePath - sampleEvery66Ms(15) + collector.onRecordingStopped(samples, builder) + samples.clear() - val builder = HangRecord.Builder(0, unixTimeMs) - collector.onRecordingStopped(interval, builder) - assertThat(builder.build().samples).hasSize(15) - assertThat(file().exists()).isFalse() + assertThat(builder.build().samples.map { it.timestampMs }).containsExactly(1L, 2L).inOrder() } } From f729109be08ee65e3e24b2bc84141921fca92419 Mon Sep 17 00:00:00 2001 From: Markus Hintersteiner Date: Mon, 23 Nov 2026 12:38:37 +0100 Subject: [PATCH 3/6] ref(anr): Rename ThreadSampleCollector.onSample to sample --- .../api/sentry-android-core.api | 5 ++-- .../core/hang/ThreadSampleCollector.java | 10 +------- .../android/core/hang/HangRecorderTest.kt | 12 +++++++--- .../core/hang/ThreadSampleCollectorTest.kt | 23 ++++--------------- 4 files changed, 17 insertions(+), 33 deletions(-) diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index f1c4401688d..7106803bfb8 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -934,9 +934,8 @@ public abstract interface class io/sentry/android/core/hang/ThreadPoster { public final class io/sentry/android/core/hang/ThreadSampleCollector : io/sentry/android/core/hang/HangDataCollector { public fun (Lio/sentry/time/EpochClock;Ljava/lang/Thread;)V public fun close ()V - public fun onRecordingStopped (Ljava/util/List;Lio/sentry/android/core/hang/HangRecord$Builder;)V - public fun onSample (Lio/sentry/android/core/hang/HangInterval;)Lio/sentry/android/core/anr/AnrStackTrace; - public synthetic fun onSample (Lio/sentry/android/core/hang/HangInterval;)Ljava/lang/Object; + public fun sample (Lio/sentry/android/core/hang/HangInterval;)Lio/sentry/android/core/anr/AnrStackTrace; + public synthetic fun sample (Lio/sentry/android/core/hang/HangInterval;)Ljava/lang/Object; } public abstract class io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter : android/app/Application$ActivityLifecycleCallbacks { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java index 408521b223a..0d069eb45e3 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java @@ -4,8 +4,6 @@ import io.sentry.android.core.anr.AnrStackTrace; import io.sentry.time.EpochClock; -import java.util.ArrayList; -import java.util.List; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -22,17 +20,11 @@ public ThreadSampleCollector(final @NotNull EpochClock epochClock, final @NotNul } @Override - public @NotNull AnrStackTrace onSample(final @NotNull HangInterval interval) { + public @NotNull AnrStackTrace sample(final @NotNull HangInterval interval) { final long epochMs = NANOSECONDS.toMillis(epochClock.now().epochNanos()); return new AnrStackTrace(epochMs, thread.getStackTrace(), thread.getState()); } - @Override - public void onRecordingStopped( - final @NotNull List samples, final @NotNull HangRecord.Builder out) { - out.setSamples(new ArrayList<>(samples)); - } - @Override public void close() {} } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt index f32f881f84a..db5fa9092fc 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt @@ -1189,7 +1189,13 @@ class HangRecorderTest { ), ) }, - listOf(CollectorSetup(ThreadSampleCollector(epochClock, parked), null)), + listOf( + CollectorSetup( + ThreadSampleCollector(epochClock, parked), + { stackTrace, builder -> builder.addStackTrace(stackTrace) }, + null, + ), + ), ) created.subscribe( @@ -1210,8 +1216,8 @@ class HangRecorderTest { parked.interrupt() parked.join() } - assertThat(record!!.samples).isNotEmpty() - assertThat(record!!.samples.first().stack.map { it.methodName }).contains("park") + assertThat(record!!.stackTraces).isNotEmpty() + assertThat(record!!.stackTraces.first().stack.map { it.methodName }).contains("park") } private class FakeAppStateProvider : AppStateProvider { diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt index c8ddabe13d1..c6a39ad76b3 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt @@ -1,7 +1,6 @@ package io.sentry.android.core.hang import com.google.common.truth.Truth.assertThat -import io.sentry.android.core.anr.AnrStackTrace import io.sentry.time.EpochClock import io.sentry.time.Timestamp import java.util.concurrent.TimeUnit @@ -16,7 +15,7 @@ class ThreadSampleCollectorTest { private val interval = HangInterval(0) @Test - fun `onSample returns the stack, the state and the time of the thread`() { + fun `sample returns the stack, the state and the time of the thread`() { val parked = Thread { while (!Thread.currentThread().isInterrupted) LockSupport.park() } parked.isDaemon = true parked.start() @@ -28,7 +27,7 @@ class ThreadSampleCollectorTest { assertThat(parked.state).isEqualTo(Thread.State.WAITING) val collector = ThreadSampleCollector(epochClock, parked) - val sample = collector.onSample(interval) + val sample = collector.sample(interval) assertThat(sample.state).isEqualTo(Thread.State.WAITING) assertThat(sample.timestampMs).isEqualTo(unixTimeMs) @@ -40,25 +39,13 @@ class ThreadSampleCollectorTest { } @Test - fun `each onSample reads the clock again`() { + fun `each sample reads the clock again`() { val collector = ThreadSampleCollector(epochClock, Thread.currentThread()) - val first = collector.onSample(interval) + val first = collector.sample(interval) unixTimeMs += 66 - val second = collector.onSample(interval) + val second = collector.sample(interval) assertThat(second.timestampMs - first.timestampMs).isEqualTo(66) } - - @Test - fun `onRecordingStopped puts a copy of the samples into the record`() { - val collector = ThreadSampleCollector(epochClock, Thread.currentThread()) - val samples = mutableListOf(AnrStackTrace(1, emptyArray()), AnrStackTrace(2, emptyArray())) - val builder = HangRecord.Builder(66, unixTimeMs) - - collector.onRecordingStopped(samples, builder) - samples.clear() - - assertThat(builder.build().samples.map { it.timestampMs }).containsExactly(1L, 2L).inOrder() - } } From 01e6e97f0fb68ad22e6f754849674e99d8b6e6a3 Mon Sep 17 00:00:00 2001 From: Markus Hintersteiner Date: Mon, 23 Nov 2026 14:58:21 +0100 Subject: [PATCH 4/6] ref(anr): Drop the interval from ThreadSampleCollector --- sentry-android-core/api/sentry-android-core.api | 5 ++--- .../io/sentry/android/core/hang/ThreadSampleCollector.java | 7 ++----- .../java/io/sentry/android/core/hang/HangRecorderTest.kt | 2 +- .../sentry/android/core/hang/ThreadSampleCollectorTest.kt | 7 +++---- 4 files changed, 8 insertions(+), 13 deletions(-) diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index ddef61ae200..082e439c885 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -927,9 +927,8 @@ public abstract interface class io/sentry/android/core/hang/ThreadPoster { public final class io/sentry/android/core/hang/ThreadSampleCollector : io/sentry/android/core/hang/HangDataCollector { public fun (Lio/sentry/time/EpochClock;Ljava/lang/Thread;)V - public fun close ()V - public fun sample (Lio/sentry/android/core/hang/HangInterval;)Lio/sentry/android/core/anr/AnrStackTrace; - public synthetic fun sample (Lio/sentry/android/core/hang/HangInterval;)Ljava/lang/Object; + public fun sample ()Lio/sentry/android/core/anr/AnrStackTrace; + public synthetic fun sample ()Ljava/lang/Object; } public abstract class io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter : android/app/Application$ActivityLifecycleCallbacks { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java index 0d069eb45e3..0be30433c34 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java @@ -7,7 +7,7 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; -/** Samples the stack and the state of a thread on each tick of a hang interval. */ +/** Samples the stack and the state of a thread on each sampling tick of a recorded hang. */ @ApiStatus.Internal public final class ThreadSampleCollector implements HangDataCollector { @@ -20,11 +20,8 @@ public ThreadSampleCollector(final @NotNull EpochClock epochClock, final @NotNul } @Override - public @NotNull AnrStackTrace sample(final @NotNull HangInterval interval) { + public @NotNull AnrStackTrace sample() { final long epochMs = NANOSECONDS.toMillis(epochClock.now().epochNanos()); return new AnrStackTrace(epochMs, thread.getStackTrace(), thread.getState()); } - - @Override - public void close() {} } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt index 304fb07ccfb..bfbfa2d14a4 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt @@ -1195,7 +1195,7 @@ class HangRecorderTest { created.subscribe( object : HangRecorderListener { - override fun onHangStarted(interval: HangInterval) = HangRecordingRequest.DEFAULT + override fun onHangStarted() = HangRecordingRequest(true, false) override fun onHangRecorded(hangRecord: HangRecord) { record = hangRecord diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt index c6a39ad76b3..7a3c3872d6f 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt @@ -12,7 +12,6 @@ class ThreadSampleCollectorTest { private var unixTimeMs = 1_700_000_000_000L private val epochClock = EpochClock { Timestamp.ofEpochNanos(MILLISECONDS.toNanos(unixTimeMs)) } - private val interval = HangInterval(0) @Test fun `sample returns the stack, the state and the time of the thread`() { @@ -27,7 +26,7 @@ class ThreadSampleCollectorTest { assertThat(parked.state).isEqualTo(Thread.State.WAITING) val collector = ThreadSampleCollector(epochClock, parked) - val sample = collector.sample(interval) + val sample = collector.sample() assertThat(sample.state).isEqualTo(Thread.State.WAITING) assertThat(sample.timestampMs).isEqualTo(unixTimeMs) @@ -42,9 +41,9 @@ class ThreadSampleCollectorTest { fun `each sample reads the clock again`() { val collector = ThreadSampleCollector(epochClock, Thread.currentThread()) - val first = collector.sample(interval) + val first = collector.sample() unixTimeMs += 66 - val second = collector.sample(interval) + val second = collector.sample() assertThat(second.timestampMs - first.timestampMs).isEqualTo(66) } From 0edebe2aea9d01e13743f08cbfaf6d996779f4d2 Mon Sep 17 00:00:00 2001 From: Markus Hintersteiner Date: Tue, 24 Nov 2026 08:40:45 +0100 Subject: [PATCH 5/6] ref(anr): Adapt to the renamed hang types --- .../io/sentry/android/core/anr/AnrProfileManager.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java index 498e0b8a84b..541465a26e6 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java @@ -4,7 +4,7 @@ import io.sentry.ILogger; import io.sentry.SentryOptions; -import io.sentry.android.core.hang.HangRecorder; +import io.sentry.android.core.hang.HangManager; import io.sentry.cache.tape.ObjectQueue; import io.sentry.cache.tape.QueueFile; import io.sentry.util.Objects; @@ -22,9 +22,9 @@ public final class AnrProfileManager implements AutoCloseable { /** - * One sample per {@link HangRecorder#DEFAULT_POLLING_INTERVAL_MS} tick for {@link - * HangRecorder#DEFAULT_MAX_RECORDING_TIME_MS}. The hang recorder stops sampling at this size, - * because a full file drops its oldest entry. + * One sample per {@link HangManager#DEFAULT_POLLING_INTERVAL_MS} tick for {@link + * HangManager#DEFAULT_MAX_RECORDING_TIME_MS}. The hang manager stops sampling a hang at this + * size, because a full file drops its oldest entry. */ public static final int MAX_NUM_STACKTRACES = 120; From 813a121381b87dff541e891913fcb1816c474a2d Mon Sep 17 00:00:00 2001 From: Markus Hintersteiner Date: Fri, 27 Nov 2026 13:37:35 +0100 Subject: [PATCH 6/6] ref(anr): Take the sample time of ThreadSampleCollector from the hang --- .../api/sentry-android-core.api | 6 ++--- .../core/hang/ThreadSampleCollector.java | 12 +++++----- .../android/core/hang/HangManagerTest.kt | 2 +- .../core/hang/ThreadSampleCollectorTest.kt | 22 +++++-------------- 4 files changed, 14 insertions(+), 28 deletions(-) diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index b0442fac993..7c8dcbb151e 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -918,9 +918,9 @@ public abstract interface class io/sentry/android/core/hang/ThreadPoster { } public final class io/sentry/android/core/hang/ThreadSampleCollector : io/sentry/android/core/hang/HangDataCollector { - public fun (Lio/sentry/time/EpochClock;Ljava/lang/Thread;)V - public fun sample ()Lio/sentry/android/core/anr/AnrStackTrace; - public synthetic fun sample ()Ljava/lang/Object; + public fun (Ljava/lang/Thread;)V + public fun sample (Lio/sentry/time/Timestamp;)Lio/sentry/android/core/anr/AnrStackTrace; + public synthetic fun sample (Lio/sentry/time/Timestamp;)Ljava/lang/Object; } public abstract class io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter : android/app/Application$ActivityLifecycleCallbacks { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java index 0be30433c34..4d274ea4e3c 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadSampleCollector.java @@ -3,7 +3,7 @@ import static java.util.concurrent.TimeUnit.NANOSECONDS; import io.sentry.android.core.anr.AnrStackTrace; -import io.sentry.time.EpochClock; +import io.sentry.time.Timestamp; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -11,17 +11,15 @@ @ApiStatus.Internal public final class ThreadSampleCollector implements HangDataCollector { - private final @NotNull EpochClock epochClock; private final @NotNull Thread thread; - public ThreadSampleCollector(final @NotNull EpochClock epochClock, final @NotNull Thread thread) { - this.epochClock = epochClock; + public ThreadSampleCollector(final @NotNull Thread thread) { this.thread = thread; } @Override - public @NotNull AnrStackTrace sample() { - final long epochMs = NANOSECONDS.toMillis(epochClock.now().epochNanos()); - return new AnrStackTrace(epochMs, thread.getStackTrace(), thread.getState()); + public @NotNull AnrStackTrace sample(final @NotNull Timestamp timestamp) { + return new AnrStackTrace( + NANOSECONDS.toMillis(timestamp.epochNanos()), thread.getStackTrace(), thread.getState()); } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangManagerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangManagerTest.kt index ae8c9c386cd..19959ca3f3a 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangManagerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangManagerTest.kt @@ -1165,7 +1165,7 @@ class HangManagerTest { }, listOf( HangCollectorSetup( - ThreadSampleCollector(epochClock, parked), + ThreadSampleCollector(parked), { stackTrace, builder -> builder.addStackTrace(stackTrace) }, null, ), diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt index 7a3c3872d6f..2f3d01ea5c4 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/ThreadSampleCollectorTest.kt @@ -1,7 +1,6 @@ package io.sentry.android.core.hang import com.google.common.truth.Truth.assertThat -import io.sentry.time.EpochClock import io.sentry.time.Timestamp import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS @@ -10,11 +9,11 @@ import kotlin.test.Test class ThreadSampleCollectorTest { - private var unixTimeMs = 1_700_000_000_000L - private val epochClock = EpochClock { Timestamp.ofEpochNanos(MILLISECONDS.toNanos(unixTimeMs)) } + private val unixTimeMs = 1_700_000_000_000L + private val timestamp = Timestamp.ofEpochNanos(MILLISECONDS.toNanos(unixTimeMs)) @Test - fun `sample returns the stack, the state and the time of the thread`() { + fun `sample returns the stack and the state of the thread at the given time`() { val parked = Thread { while (!Thread.currentThread().isInterrupted) LockSupport.park() } parked.isDaemon = true parked.start() @@ -24,9 +23,9 @@ class ThreadSampleCollectorTest { Thread.yield() } assertThat(parked.state).isEqualTo(Thread.State.WAITING) - val collector = ThreadSampleCollector(epochClock, parked) + val collector = ThreadSampleCollector(parked) - val sample = collector.sample() + val sample = collector.sample(timestamp) assertThat(sample.state).isEqualTo(Thread.State.WAITING) assertThat(sample.timestampMs).isEqualTo(unixTimeMs) @@ -36,15 +35,4 @@ class ThreadSampleCollectorTest { parked.join() } } - - @Test - fun `each sample reads the clock again`() { - val collector = ThreadSampleCollector(epochClock, Thread.currentThread()) - - val first = collector.sample() - unixTimeMs += 66 - val second = collector.sample() - - assertThat(second.timestampMs - first.timestampMs).isEqualTo(66) - } }