Skip to content

Commit 3d1f55e

Browse files
runningcodeclaude
andauthored
ref(android): Measure ANR thresholds on the monotonic clock (JAVA-579) (#6041)
* test(time): Publish the TestMonotonicTicker tick to other threads The ANR tests advance the ticker from the test thread while the watchdog thread reads it, which without volatile is a data race that can leave the watchdog looking at a stale tick forever. * ref(android): Measure ANR thresholds on the monotonic clock (JAVA-579) The watchdog took its readings from an ICurrentDateProvider lambda over SystemClock.uptimeMillis(). The type named no clock, so a call site could not tell what it was measuring, and the arithmetic -- now minus the last tick, compared against a threshold -- was spelled out inline. MonotonicClock and Deadline replace both: the clock is a named type, and the watchdog asks the question it actually cares about, which is whether the main thread has missed its window. The clock counts deep sleep, which uptimeMillis() did not, so a suspend between posting the ticker and checking it now looks like a missed window. It cannot fabricate an ANR: the watchdog reports only once ActivityManager confirms the process is NOT_RESPONDING, and on resume the main thread runs the ticker that is already queued. * ref(android): Measure ANR profiling on the monotonic clock (JAVA-579) Same reasoning as the watchdog: the suspicion and ANR thresholds are now read from a named clock rather than SystemClock, and injecting it lets the tests drive it directly instead of going through Robolectric's shadow clock. Deep sleep cannot inflate the measurement here either, because the polling thread parks itself while the app is backgrounded and resets the baseline when it wakes. * changelog * ref(time): Supply the ANR ticker through MonotonicTickerProvider (JAVA-579) Both ANR detectors resolved AndroidMonotonicTicker.getInstance() themselves, so each call site named the concrete Android ticker and neither could be pointed at another one. SentryAndroidOptions already knows which ticker the platform wants, but it is final, so a test cannot override the getter. Add a one-method MonotonicTickerProvider that SentryOptions implements. ANRWatchDog gains a static factory that reads its timeout, debug behavior, logger and ticker off options, replacing the telescoping convenience constructor. AnrProfilingIntegration installs the ticker in register(), which drops the two constructors it had grown and leaves the public no-arg constructor and sentry-android-core.api unchanged. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ref(android): Require an installed ticker for ANR profiling (JAVA-579) Drop the JavaMonotonicTicker fallback. On Android nanoTime() stops while the device is suspended, so a default that is never meant to be used would measure main-thread stalls against the wrong clock if it ever were. Start the test ticker at a non-zero origin. A fake that starts at zero makes a reading taken against a different origin indistinguishable from a correct one, which is the mistake this whole change exists to prevent. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ref(android): Pass the ANR profiling ticker directly (JAVA-579) MonotonicTickerProvider only existed so a test could hand AnrProfilingIntegration a fake ticker. A package-private method taking the ticker does the same without a new core interface or a change to the SentryOptions supertype. Also rename the ANRWatchDog test that claimed to cover a device suspend: the Android ticker counts suspend, so the test only shows the threshold is measured on the injected ticker rather than wall time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ref(android): Read the ANR profiling ticker from options (JAVA-579) Tests spy SentryAndroidOptions to supply a TestMonotonicTicker, so the package-private installTicker seam is no longer needed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ref(android): Drop the UnnecessaryLambda suppression in ANR profiling (JAVA-579) Error Prone does not run on sentry-android-core, so the suppression had no effect. The lambda field stays: removeCallbacks matches the posted Runnable by identity. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 2ac3550 commit 3d1f55e

7 files changed

Lines changed: 150 additions & 74 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@
6868
- [changelog](https://github.com/getsentry/sentry-native/blob/master/CHANGELOG.md#0176)
6969
- [diff](https://github.com/getsentry/sentry-native/compare/0.17.4...0.17.6)
7070

71+
### Internal
72+
73+
- Measure ANR detection and ANR profiling durations on the internal `MonotonicTicker` ([#6041](https://github.com/getsentry/sentry-java/pull/6041))
74+
7175
## 8.62.0
7276

7377
### Improvements

‎sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java‎

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -29,33 +29,37 @@
2929

3030
import android.app.ActivityManager;
3131
import android.content.Context;
32-
import android.os.SystemClock;
3332
import io.sentry.IDebugManager;
3433
import io.sentry.ILogger;
3534
import io.sentry.SentryLevel;
36-
import io.sentry.transport.ICurrentDateProvider;
35+
import io.sentry.time.Deadline;
36+
import io.sentry.time.MonotonicTicker;
3737
import java.util.List;
38+
import java.util.concurrent.TimeUnit;
3839
import java.util.concurrent.atomic.AtomicBoolean;
3940
import org.jetbrains.annotations.NotNull;
4041
import org.jetbrains.annotations.Nullable;
41-
import org.jetbrains.annotations.TestOnly;
4242

4343
/** A watchdog timer thread that detects when the UI thread has frozen. */
4444
@SuppressWarnings("UnusedReturnValue")
4545
final class ANRWatchDog extends Thread {
4646

47+
private static final long DEFAULT_POLLING_INTERVAL_MS = 500;
48+
4749
private final boolean reportInDebug;
4850
private final ANRListener anrListener;
4951
private final MainLooperHandler uiHandler;
50-
private final ICurrentDateProvider timeProvider;
52+
private final MonotonicTicker monotonicTicker;
5153

5254
/** the interval in which we check if there's an ANR, in ms */
5355
private long pollingIntervalMs;
5456

5557
private final long timeoutIntervalMillis;
5658
private final @NotNull ILogger logger;
5759

58-
private volatile long lastKnownActiveUiTimestampMs = 0;
60+
/** How long the main thread has left to run the ticker before we call it an ANR. */
61+
private volatile @NotNull Deadline uiResponsiveUntil;
62+
5963
private final AtomicBoolean reported = new AtomicBoolean(false);
6064

6165
private final @NotNull Context context;
@@ -64,30 +68,24 @@ final class ANRWatchDog extends Thread {
6468
@SuppressWarnings("UnnecessaryLambda")
6569
private final Runnable ticker;
6670

67-
ANRWatchDog(
68-
long timeoutIntervalMillis,
69-
boolean reportInDebug,
70-
@NotNull ANRListener listener,
71-
@NotNull ILogger logger,
72-
final @NotNull Context context,
73-
final @Nullable IDebugManager debugManager) {
74-
// avoid method refs on Android due to some issues with older AGP setups
75-
// noinspection Convert2MethodRef
76-
this(
77-
() -> SystemClock.uptimeMillis(),
78-
timeoutIntervalMillis,
79-
500,
80-
reportInDebug,
71+
static @NotNull ANRWatchDog create(
72+
final @NotNull SentryAndroidOptions options,
73+
final @NotNull ANRListener listener,
74+
final @NotNull Context context) {
75+
return new ANRWatchDog(
76+
options.getMonotonicTicker(),
77+
options.getAnrTimeoutIntervalMillis(),
78+
DEFAULT_POLLING_INTERVAL_MS,
79+
options.isAnrReportInDebug(),
8180
listener,
82-
logger,
81+
options.getLogger(),
8382
new MainLooperHandler(),
8483
context,
85-
debugManager);
84+
options.getDebugManager());
8685
}
8786

88-
@TestOnly
8987
ANRWatchDog(
90-
@NotNull final ICurrentDateProvider timeProvider,
88+
@NotNull final MonotonicTicker monotonicTicker,
9189
long timeoutIntervalMillis,
9290
long pollingIntervalMillis,
9391
boolean reportInDebug,
@@ -99,7 +97,7 @@ final class ANRWatchDog extends Thread {
9997

10098
super("|ANR-WatchDog|");
10199

102-
this.timeProvider = timeProvider;
100+
this.monotonicTicker = monotonicTicker;
103101
this.timeoutIntervalMillis = timeoutIntervalMillis;
104102
this.pollingIntervalMs = pollingIntervalMillis;
105103
this.reportInDebug = reportInDebug;
@@ -108,9 +106,12 @@ final class ANRWatchDog extends Thread {
108106
this.uiHandler = uiHandler;
109107
this.context = context;
110108
this.debugManager = debugManager;
109+
this.uiResponsiveUntil =
110+
Deadline.after(monotonicTicker, timeoutIntervalMillis, TimeUnit.MILLISECONDS);
111111
this.ticker =
112112
() -> {
113-
lastKnownActiveUiTimestampMs = timeProvider.getCurrentTimeMillis();
113+
uiResponsiveUntil =
114+
Deadline.after(monotonicTicker, timeoutIntervalMillis, TimeUnit.MILLISECONDS);
114115
reported.set(false);
115116
};
116117

@@ -146,11 +147,8 @@ public void run() {
146147
return;
147148
}
148149

149-
final long unresponsiveDurationMs =
150-
timeProvider.getCurrentTimeMillis() - lastKnownActiveUiTimestampMs;
151-
152150
// If the main thread has not handled ticker, it is blocked. ANR.
153-
if (unresponsiveDurationMs > timeoutIntervalMillis) {
151+
if (uiResponsiveUntil.hasPassed()) {
154152
if (!reportInDebug && debugManager != null && debugManager.isDebuggerConnected()) {
155153
logger.log(
156154
SentryLevel.DEBUG,

‎sentry-android-core/src/main/java/io/sentry/android/core/AnrIntegration.java‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -95,13 +95,7 @@ private void startAnrWatchdog(
9595
options.getAnrTimeoutIntervalMillis());
9696

9797
anrWatchDog =
98-
new ANRWatchDog(
99-
options.getAnrTimeoutIntervalMillis(),
100-
options.isAnrReportInDebug(),
101-
error -> reportANR(scopes, options, error),
102-
options.getLogger(),
103-
context,
104-
options.getDebugManager());
98+
ANRWatchDog.create(options, error -> reportANR(scopes, options, error), context);
10599
anrWatchDog.start();
106100

107101
options.getLogger().log(SentryLevel.DEBUG, "AnrIntegration installed.");

‎sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java‎

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
import android.os.Handler;
66
import android.os.Looper;
7-
import android.os.SystemClock;
87
import io.sentry.IDebugManager;
98
import io.sentry.ILogger;
109
import io.sentry.IScopes;
@@ -15,12 +14,15 @@
1514
import io.sentry.SentryOptions;
1615
import io.sentry.android.core.AppState;
1716
import io.sentry.android.core.SentryAndroidOptions;
17+
import io.sentry.time.MonotonicTicker;
18+
import io.sentry.time.Stopwatch;
1819
import io.sentry.util.AutoClosableReentrantLock;
1920
import io.sentry.util.Objects;
2021
import io.sentry.util.SentryRandom;
2122
import java.io.Closeable;
2223
import java.io.File;
2324
import java.io.IOException;
25+
import java.util.concurrent.TimeUnit;
2426
import java.util.concurrent.atomic.AtomicBoolean;
2527
import java.util.concurrent.atomic.AtomicInteger;
2628
import org.jetbrains.annotations.ApiStatus;
@@ -44,12 +46,22 @@ public class AnrProfilingIntegration
4446
static final int MAX_NUM_STACKS = (int) (10_000 / POLLING_INTERVAL_MS);
4547

4648
private final AtomicBoolean enabled = new AtomicBoolean(true);
47-
private final Runnable updater = () -> lastMainThreadExecutionTime = SystemClock.uptimeMillis();
49+
50+
private volatile @Nullable MonotonicTicker ticker;
51+
52+
private final @NotNull Runnable updater =
53+
() -> {
54+
final @Nullable MonotonicTicker currentTicker = ticker;
55+
if (currentTicker != null) {
56+
lastMainThreadExecutionNanos = currentTicker.tickNanos();
57+
}
58+
};
59+
4860
private final @NotNull AutoClosableReentrantLock lifecycleLock = new AutoClosableReentrantLock();
4961
private final @NotNull AutoClosableReentrantLock profileManagerLock =
5062
new AutoClosableReentrantLock();
5163

52-
private volatile long lastMainThreadExecutionTime = SystemClock.uptimeMillis();
64+
private volatile long lastMainThreadExecutionNanos;
5365
final AtomicInteger numCollectedStacks = new AtomicInteger();
5466
private volatile MainThreadState mainThreadState = MainThreadState.IDLE;
5567
private volatile @Nullable AnrProfileManager profileManager;
@@ -69,6 +81,10 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions
6981
(options instanceof SentryAndroidOptions) ? (SentryAndroidOptions) options : null,
7082
"SentryAndroidOptions is required");
7183
this.logger = options.getLogger();
84+
final @NotNull MonotonicTicker ticker = options.getMonotonicTicker();
85+
// A tick's origin is arbitrary, so the default of 0 would read as a stall of unknown length.
86+
this.lastMainThreadExecutionNanos = ticker.tickNanos();
87+
this.ticker = ticker;
7288
this.debugManager = this.options.getDebugManager();
7389

7490
if (this.options.isAnrProfilingEnabled()) {
@@ -223,8 +239,12 @@ protected void checkMainThread(final @NotNull Thread mainThread) throws IOExcept
223239
return;
224240
}
225241

226-
final long now = SystemClock.uptimeMillis();
227-
final long diff = now - lastMainThreadExecutionTime;
242+
final @Nullable MonotonicTicker currentTicker = ticker;
243+
if (currentTicker == null) {
244+
return;
245+
}
246+
final long diff =
247+
TimeUnit.NANOSECONDS.toMillis(currentTicker.tickNanos() - lastMainThreadExecutionNanos);
228248

229249
if (diff < THRESHOLD_SUSPICION_MS) {
230250
mainThreadState = MainThreadState.IDLE;
@@ -253,14 +273,15 @@ protected void checkMainThread(final @NotNull Thread mainThread) throws IOExcept
253273
&& (mainThreadState == MainThreadState.SUSPICIOUS
254274
|| mainThreadState == MainThreadState.ANR_DETECTED)) {
255275
if (numCollectedStacks.get() < MAX_NUM_STACKS) {
256-
final long start = SystemClock.uptimeMillis();
276+
final @NotNull Stopwatch stopwatch = Stopwatch.started(currentTicker);
257277
final @NotNull AnrStackTrace trace =
258278
new AnrStackTrace(System.currentTimeMillis(), mainThread.getStackTrace());
259-
final long duration = SystemClock.uptimeMillis() - start;
260279
if (logger.isEnabled(SentryLevel.DEBUG)) {
261280
logger.log(
262281
SentryLevel.DEBUG,
263-
"AnrWatchdog: capturing main thread stacktrace took " + duration + "ms");
282+
"AnrWatchdog: capturing main thread stacktrace took "
283+
+ stopwatch.elapsed(TimeUnit.MILLISECONDS)
284+
+ "ms");
264285
}
265286
addStackTrace(trace);
266287
} else {

‎sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt‎

Lines changed: 48 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@ import android.app.ActivityManager
44
import android.app.ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING
55
import android.app.ActivityManager.ProcessErrorStateInfo.NO_ERROR
66
import android.content.Context
7-
import io.sentry.transport.ICurrentDateProvider
7+
import io.sentry.time.TestMonotonicTicker
88
import java.util.concurrent.CountDownLatch
99
import java.util.concurrent.Executors
1010
import java.util.concurrent.TimeUnit
11+
import java.util.concurrent.TimeUnit.MILLISECONDS
1112
import kotlin.test.Test
1213
import kotlin.test.assertEquals
1314
import kotlin.test.assertNotNull
@@ -20,12 +21,12 @@ import org.mockito.kotlin.mock
2021
import org.mockito.kotlin.whenever
2122

2223
class ANRWatchDogTest {
23-
private var currentTimeMs = 0L
24-
private val timeProvider = ICurrentDateProvider { currentTimeMs }
24+
private lateinit var ticker: TestMonotonicTicker
2525

2626
@Before
2727
fun `setup`() {
28-
currentTimeMs = 12341234
28+
// an arbitrary, non-zero origin: no caller may assume a tick counts from zero
29+
ticker = TestMonotonicTicker(MILLISECONDS.toNanos(12341234))
2930
}
3031

3132
@Test
@@ -44,7 +45,7 @@ class ANRWatchDogTest {
4445

4546
val sut =
4647
ANRWatchDog(
47-
timeProvider,
48+
ticker,
4849
interval,
4950
1L,
5051
true,
@@ -63,7 +64,7 @@ class ANRWatchDogTest {
6364
) // Wait until worker posts the job for the "UI thread"
6465
var waitCount = 0
6566
do {
66-
currentTimeMs += 100L
67+
ticker.advance(100, MILLISECONDS)
6768
Thread.sleep(100) // Let worker realize this is ANR
6869
} while (anr == null && waitCount++ < 100)
6970

@@ -91,7 +92,7 @@ class ANRWatchDogTest {
9192

9293
val sut =
9394
ANRWatchDog(
94-
timeProvider,
95+
ticker,
9596
interval,
9697
1L,
9798
true,
@@ -107,7 +108,7 @@ class ANRWatchDogTest {
107108

108109
var waitCount = 0
109110
do {
110-
currentTimeMs += 100L
111+
ticker.advance(100, MILLISECONDS)
111112
Thread.sleep(100) // Let worker realize his runner always runs
112113
} while (!invoked && waitCount++ < 100)
113114

@@ -143,7 +144,7 @@ class ANRWatchDogTest {
143144

144145
val sut =
145146
ANRWatchDog(
146-
timeProvider,
147+
ticker,
147148
interval,
148149
1L,
149150
true,
@@ -162,7 +163,7 @@ class ANRWatchDogTest {
162163
) // Wait until worker posts the job for the "UI thread"
163164
var waitCount = 0
164165
do {
165-
currentTimeMs += 100L
166+
ticker.advance(100, MILLISECONDS)
166167
Thread.sleep(100) // Let worker realize this is ANR
167168
} while (anr == null && waitCount++ < 100)
168169

@@ -199,7 +200,7 @@ class ANRWatchDogTest {
199200

200201
val sut =
201202
ANRWatchDog(
202-
timeProvider,
203+
ticker,
203204
interval,
204205
1L,
205206
true,
@@ -218,7 +219,7 @@ class ANRWatchDogTest {
218219
) // Wait until worker posts the job for the "UI thread"
219220
var waitCount = 0
220221
do {
221-
currentTimeMs += 100L
222+
ticker.advance(100, MILLISECONDS)
222223
Thread.sleep(100L) // Let worker realize this is ANR
223224
} while (anr == null && waitCount++ < 100)
224225
assertNull(anr) // callback never ran
@@ -227,4 +228,39 @@ class ANRWatchDogTest {
227228
es.shutdown()
228229
}
229230
}
231+
232+
@Test
233+
fun `measures the ANR threshold on the ticker, not on wall time`() {
234+
var anr: ApplicationNotResponding? = null
235+
val handler = mock<MainLooperHandler>()
236+
val latch = CountDownLatch(1)
237+
whenever(handler.post(any())).then { latch.countDown() }
238+
whenever(handler.thread).thenReturn(mock<Thread>())
239+
240+
// context is a mock, so ActivityManager is absent and any passed deadline reports an ANR
241+
val sut =
242+
ANRWatchDog(
243+
ticker,
244+
10L,
245+
1L,
246+
true,
247+
{ a -> anr = a },
248+
mock(),
249+
handler,
250+
mock(),
251+
AndroidDebugManager(),
252+
)
253+
val es = Executors.newSingleThreadExecutor()
254+
try {
255+
es.submit { sut.run() }
256+
257+
assertTrue(latch.await(10L, TimeUnit.SECONDS)) // wait until the watchdog is polling
258+
Thread.sleep(200) // hundreds of polls of wall time while the ticker stands still
259+
260+
assertNull(anr)
261+
} finally {
262+
sut.interrupt()
263+
es.shutdown()
264+
}
265+
}
230266
}

0 commit comments

Comments
 (0)