Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 10 additions & 0 deletions sentry-android-core/api/sentry-android-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -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 <init> (Lio/sentry/SentryOptions;)V
public fun <init> (Lio/sentry/SentryOptions;Ljava/io/File;)V
public fun add (Lio/sentry/android/core/anr/AnrStackTrace;)V
Expand Down Expand Up @@ -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 <init> (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 <init> ()V
public fun onActivityCreated (Landroid/app/Activity;Landroid/os/Bundle;)V
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<AnrStackTrace> queue;

Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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<AnrStackTrace> 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());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Sample timestamps use wall clock

Low Severity

Each sample stamps itself with a fresh epochClock.now() reading. Those timestamps are later sorted and turned into profile sample times, so they are related instants. A wall-clock jump during the hang can reorder stacks or stretch the profile. AnchoredClock is the type for this: one epoch read, then monotonic ticks for the rest.

Fix in Cursor Fix in Web

Triggered by learned rule: AnchoredClock for related instants, not EpochClock math

Reviewed by Cursor Bugbot for commit a19a7c8. Configure here.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Failed flush skips buffered samples

Medium Severity

onDisk is set before startDiskRecording finishes, so an IOException from clear or a later add still marks the hang as flushed. Later ticks then append only the new sample. If clear failed, that appends onto the previous hang; if clear succeeded, the in-memory buffer never reaches the file. The fatal ANR path can then load mixed or truncated stacks.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit a19a7c8. Configure here.

} 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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 {
Expand Down
Loading
Loading