From 497cb69f53b50b67aba694d23e30b9c35b193b58 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Mon, 23 Nov 2026 11:14:31 +0100 Subject: [PATCH 1/2] fix(android): Detect startup crashes on the boottime clock Startup crash detection measured the time since SDK init with SystemClock.uptimeMillis(), which stops while the device is in deep sleep. A crash long after init, with sleep in between, could fall under the threshold and be marked as a startup crash. Both SDK init entry points now also start a Stopwatch on the MonotonicTicker, which counts deep sleep, and AndroidEnvelopeCache reads that. The TimeSpan stays on uptime because changing its base is a v9 decision. This removes the last production use of AndroidCurrentDateProvider; the class itself goes away in v9. Fixes JAVA-729 Co-Authored-By: Claude Opus 5.5 --- .../api/sentry-android-core.api | 2 + .../io/sentry/android/core/SentryAndroid.java | 7 +++ .../core/SentryPerformanceProvider.java | 7 +++ .../core/cache/AndroidEnvelopeCache.java | 24 +++------ .../core/performance/AppStartMetrics.java | 18 +++++++ .../sentry/android/core/SentryAndroidTest.kt | 7 +++ .../core/SentryPerformanceProviderTest.kt | 2 + .../core/cache/AndroidEnvelopeCacheTest.kt | 52 +++++++++++-------- 8 files changed, 79 insertions(+), 40 deletions(-) diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 5ab0634a499..768470d7b84 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -863,6 +863,7 @@ public final class io/sentry/android/core/performance/AppStartMetrics : io/sentr public fun getClassLoadedUptimeMs ()J public fun getContentProviderOnCreateTimeSpans ()Ljava/util/List; public static fun getInstance ()Lio/sentry/android/core/performance/AppStartMetrics; + public fun getSdkInitStopwatch ()Lio/sentry/time/Stopwatch; public fun getSdkInitTimeSpan ()Lio/sentry/android/core/performance/TimeSpan; public fun isAppLaunchedInForeground ()Z public fun onActivityCreated (Landroid/app/Activity;Landroid/os/Bundle;)V @@ -889,6 +890,7 @@ public final class io/sentry/android/core/performance/AppStartMetrics : io/sentr public fun setCachedStartInfo (Landroid/app/ApplicationStartInfo;)V public fun setClassLoadedUptimeMs (J)V public fun setHeadlessAppStartListener (Lio/sentry/android/core/performance/AppStartMetrics$HeadlessAppStartListener;)V + public fun setSdkInitStopwatch (Lio/sentry/time/Stopwatch;)V public fun shouldSendStartMeasurements ()Z public fun shouldSendStartMeasurements (Z)Z } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java index e3eb33af048..827f047ccd3 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java @@ -15,10 +15,12 @@ import io.sentry.SentryLevel; import io.sentry.SentryOptions; import io.sentry.Session; +import io.sentry.android.core.internal.time.AndroidMonotonicTicker; import io.sentry.android.core.performance.AppStartMetrics; import io.sentry.android.core.performance.TimeSpan; import io.sentry.android.fragment.FragmentLifecycleIntegration; import io.sentry.android.timber.SentryTimberIntegration; +import io.sentry.time.Stopwatch; import io.sentry.util.AutoClosableReentrantLock; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -33,6 +35,10 @@ public final class SentryAndroid { // SystemClock.uptimeMillis() isn't affected by phone provider or clock changes. private static final long sdkInitMillis = SystemClock.uptimeMillis(); + // There are no options to take the ticker from at class load. + private static final @NotNull Stopwatch sdkInitStopwatch = + Stopwatch.started(AndroidMonotonicTicker.getInstance()); + static final String SENTRY_FRAGMENT_INTEGRATION_CLASS_NAME = "io.sentry.android.fragment.FragmentLifecycleIntegration"; @@ -180,6 +186,7 @@ public static void init( final @NotNull TimeSpan sdkInitTimeSpan = appStartMetrics.getSdkInitTimeSpan(); if (sdkInitTimeSpan.hasNotStarted()) { sdkInitTimeSpan.setStartedAt(sdkInitMillis); + appStartMetrics.setSdkInitStopwatch(sdkInitStopwatch); } AndroidOptionsInitializer.initializeIntegrationsAndProcessors( diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java index 9d1f2e13ec4..5829077b3cf 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryPerformanceProvider.java @@ -20,9 +20,11 @@ import io.sentry.SentryOptions; import io.sentry.TracesSampler; import io.sentry.TracesSamplingDecision; +import io.sentry.android.core.internal.time.AndroidMonotonicTicker; import io.sentry.android.core.internal.util.SentryFrameMetricsCollector; import io.sentry.android.core.performance.AppStartMetrics; import io.sentry.android.core.performance.TimeSpan; +import io.sentry.time.Stopwatch; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -41,6 +43,10 @@ public final class SentryPerformanceProvider extends EmptySecureContentProvider // SystemClock.uptimeMillis() isn't affected by phone provider or clock changes. private static final long sdkInitMillis = SystemClock.uptimeMillis(); + // There are no options to take the ticker from at class load. + private static final @NotNull Stopwatch sdkInitStopwatch = + Stopwatch.started(AndroidMonotonicTicker.getInstance()); + private @Nullable Application app; private final @NotNull ILogger logger; @@ -257,6 +263,7 @@ private void onAppLaunched( // sdk-init uses static field init as start time final @NotNull TimeSpan sdkInitTimeSpan = appStartMetrics.getSdkInitTimeSpan(); sdkInitTimeSpan.setStartedAt(sdkInitMillis); + appStartMetrics.setSdkInitStopwatch(sdkInitStopwatch); // performance v2: Uses Process.getStartUptimeMillis() // requires API level 24+ diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/cache/AndroidEnvelopeCache.java b/sentry-android-core/src/main/java/io/sentry/android/core/cache/AndroidEnvelopeCache.java index 245950a17ee..cf7c21b3209 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/cache/AndroidEnvelopeCache.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/cache/AndroidEnvelopeCache.java @@ -12,11 +12,9 @@ import io.sentry.android.core.MemoryLimiterIntegration; import io.sentry.android.core.SentryAndroidOptions; import io.sentry.android.core.TombstoneIntegration; -import io.sentry.android.core.internal.util.AndroidCurrentDateProvider; import io.sentry.android.core.performance.AppStartMetrics; -import io.sentry.android.core.performance.TimeSpan; import io.sentry.cache.EnvelopeCache; -import io.sentry.transport.ICurrentDateProvider; +import io.sentry.time.Stopwatch; import io.sentry.util.FileUtils; import io.sentry.util.HintUtils; import io.sentry.util.Objects; @@ -26,6 +24,7 @@ import java.io.OutputStream; import java.util.Arrays; import java.util.List; +import java.util.concurrent.TimeUnit; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -38,22 +37,11 @@ public final class AndroidEnvelopeCache extends EnvelopeCache { public static final String LAST_TOMBSTONE_REPORT = "last_tombstone_report"; public static final String LAST_MEMORY_LIMITER_REPORT = "last_memory_limiter_report"; - private final @NotNull ICurrentDateProvider currentDateProvider; - - // TODO: JAVA-729 - @SuppressWarnings("deprecation") public AndroidEnvelopeCache(final @NotNull SentryAndroidOptions options) { - this(options, AndroidCurrentDateProvider.getInstance()); - } - - AndroidEnvelopeCache( - final @NotNull SentryAndroidOptions options, - final @NotNull ICurrentDateProvider currentDateProvider) { super( options, Objects.requireNonNull(options.getCacheDirPath(), "cacheDirPath must not be null"), options.getMaxCacheItems()); - this.currentDateProvider = currentDateProvider; } @SuppressWarnings("deprecation") @@ -71,12 +59,12 @@ private boolean storeInternalAndroid(@NotNull SentryEnvelope envelope, @NotNull final boolean didStore = super.storeEnvelope(envelope, hint); final SentryAndroidOptions options = (SentryAndroidOptions) this.options; - final TimeSpan sdkInitTimeSpan = AppStartMetrics.getInstance().getSdkInitTimeSpan(); + final @Nullable Stopwatch sdkInitStopwatch = + AppStartMetrics.getInstance().getSdkInitStopwatch(); if (HintUtils.hasType(hint, UncaughtExceptionHandlerIntegration.UncaughtExceptionHint.class) - && sdkInitTimeSpan.hasStarted()) { - long timeSinceSdkInit = - currentDateProvider.getCurrentTimeMillis() - sdkInitTimeSpan.getStartUptimeMs(); + && sdkInitStopwatch != null) { + final long timeSinceSdkInit = sdkInitStopwatch.elapsed(TimeUnit.MILLISECONDS); if (timeSinceSdkInit <= options.getStartupCrashDurationThresholdMillis()) { options .getLogger() diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java b/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java index 4051ae6ebf4..715604b5844 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java @@ -29,6 +29,7 @@ import io.sentry.android.core.SentryAndroidOptions; import io.sentry.android.core.internal.util.FirstDrawDoneListener; import io.sentry.protocol.SentryId; +import io.sentry.time.Stopwatch; import io.sentry.util.AutoClosableReentrantLock; import java.util.ArrayList; import java.util.Collections; @@ -79,6 +80,8 @@ public enum AppStartType { private final @NotNull TimeSpan appStartSpan; private final @NotNull TimeSpan sdkInitTimeSpan; + // Written on the thread that initializes the SDK and read on the thread that crashes. + private volatile @Nullable Stopwatch sdkInitStopwatch; private final @NotNull TimeSpan applicationOnCreate; private final @NotNull Map contentProviderOnCreates; private final @NotNull List activityLifecycles; @@ -159,6 +162,20 @@ public AppStartMetrics() { return sdkInitTimeSpan; } + /** + * Measures the time since SDK init on a {@link io.sentry.time.MonotonicTicker}, which keeps + * counting through deep sleep. {@link #getSdkInitTimeSpan()} runs on {@link + * SystemClock#uptimeMillis()}, which does not, so it can't tell how long ago the SDK really + * started. Set by the same two entry points as {@link #getSdkInitTimeSpan()}. + */ + public @Nullable Stopwatch getSdkInitStopwatch() { + return sdkInitStopwatch; + } + + public void setSdkInitStopwatch(final @NotNull Stopwatch sdkInitStopwatch) { + this.sdkInitStopwatch = sdkInitStopwatch; + } + public @NotNull TimeSpan getApplicationOnCreateTimeSpan() { return applicationOnCreate; } @@ -401,6 +418,7 @@ public void clear() { appStartType = AppStartType.UNKNOWN; appStartSpan.reset(); sdkInitTimeSpan.reset(); + sdkInitStopwatch = null; applicationOnCreate.reset(); contentProviderOnCreates.clear(); activityLifecycles.clear(); diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt index 2717128af95..91efa4f8dc6 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt @@ -48,6 +48,8 @@ import io.sentry.cache.tape.QueueFile import io.sentry.protocol.Contexts import io.sentry.spotlight.SpotlightIntegration import io.sentry.test.applyTestOptions +import io.sentry.time.Stopwatch +import io.sentry.time.TestMonotonicTicker import io.sentry.transport.NoOpEnvelopeCache import io.sentry.util.StringUtils import java.io.ByteArrayOutputStream @@ -64,6 +66,7 @@ import kotlin.test.assertFalse import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull +import kotlin.test.assertSame import kotlin.test.assertTrue import org.awaitility.kotlin.await import org.awaitility.kotlin.withAlias @@ -530,12 +533,15 @@ class SentryAndroidTest { } assertEquals(42, AppStartMetrics.getInstance().appStartTimeSpan.startUptimeMs) assertTrue(AppStartMetrics.getInstance().sdkInitTimeSpan.hasStarted()) + assertNotNull(AppStartMetrics.getInstance().sdkInitStopwatch) } @Test fun `init does not backfill sdk init and app start times if already set`() { AppStartMetrics.getInstance().clear() AppStartMetrics.getInstance().sdkInitTimeSpan.setStartedAt(99) + val sdkInitStopwatch = Stopwatch.started(TestMonotonicTicker()) + AppStartMetrics.getInstance().setSdkInitStopwatch(sdkInitStopwatch) AppStartMetrics.getInstance().appStartTimeSpan.setStartedAt(99) SentryShadowProcess.setStartUptimeMillis(42) @@ -545,6 +551,7 @@ class SentryAndroidTest { } assertEquals(99, AppStartMetrics.getInstance().sdkInitTimeSpan.startUptimeMs) + assertSame(sdkInitStopwatch, AppStartMetrics.getInstance().sdkInitStopwatch) assertEquals(99, AppStartMetrics.getInstance().appStartTimeSpan.startUptimeMs) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryPerformanceProviderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryPerformanceProviderTest.kt index f5a6bfcd919..d3f76ea8d48 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryPerformanceProviderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryPerformanceProviderTest.kt @@ -103,9 +103,11 @@ class SentryPerformanceProviderTest { @Test fun `provider starts appStartTimeSpan`() { assertTrue(AppStartMetrics.getInstance().sdkInitTimeSpan.hasNotStarted()) + assertNull(AppStartMetrics.getInstance().sdkInitStopwatch) assertTrue(AppStartMetrics.getInstance().appStartTimeSpan.hasNotStarted()) fixture.getSut() assertTrue(AppStartMetrics.getInstance().sdkInitTimeSpan.hasStarted()) + assertNotNull(AppStartMetrics.getInstance().sdkInitStopwatch) assertTrue(AppStartMetrics.getInstance().appStartTimeSpan.hasStarted()) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/cache/AndroidEnvelopeCacheTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/cache/AndroidEnvelopeCacheTest.kt index d6e37383dea..96b0ff12b40 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/cache/AndroidEnvelopeCacheTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/cache/AndroidEnvelopeCacheTest.kt @@ -17,11 +17,14 @@ import io.sentry.android.core.MemoryLimiterIntegration.MemoryLimiterHint import io.sentry.android.core.SentryAndroidOptions import io.sentry.android.core.performance.AppStartMetrics import io.sentry.cache.EnvelopeCache -import io.sentry.transport.ICurrentDateProvider +import io.sentry.time.Stopwatch +import io.sentry.time.TestMonotonicTicker import io.sentry.util.HintUtils import java.io.File import java.lang.IllegalArgumentException import java.util.Date +import java.util.concurrent.TimeUnit.HOURS +import java.util.concurrent.TimeUnit.SECONDS import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals @@ -40,15 +43,14 @@ class AndroidEnvelopeCacheTest { private class Fixture { val envelope = mock { whenever(it.header).thenReturn(mock()) } val options = SentryAndroidOptions() - val dateProvider = mock() + val ticker = TestMonotonicTicker() lateinit var startupCrashMarkerFile: File lateinit var lastReportedAnrFile: File lateinit var lastReportedMemoryLimiterFile: File fun getSut( dir: TemporaryFolder, - appStartMillis: Long? = null, - currentTimeMillis: Long? = null, + sdkInitStarted: Boolean = false, optionsCallback: ((SentryOptions) -> Unit)? = null, ): AndroidEnvelopeCache { options.cacheDirPath = dir.newFolder("sentry-cache").absolutePath @@ -61,21 +63,11 @@ class AndroidEnvelopeCacheTest { lastReportedMemoryLimiterFile = File(options.cacheDirPath!!, AndroidEnvelopeCache.LAST_MEMORY_LIMITER_REPORT) - if (appStartMillis != null) { - AppStartMetrics.getInstance().apply { - if (options.isEnablePerformanceV2) { - appStartTimeSpan.setStartedAt(appStartMillis) - sdkInitTimeSpan.setStartedAt(appStartMillis) - } else { - sdkInitTimeSpan.setStartedAt(appStartMillis) - } - } - } - if (currentTimeMillis != null) { - whenever(dateProvider.currentTimeMillis).thenReturn(currentTimeMillis) + if (sdkInitStarted) { + AppStartMetrics.getInstance().setSdkInitStopwatch(Stopwatch.started(ticker)) } - return AndroidEnvelopeCache(options, dateProvider) + return AndroidEnvelopeCache(options) } } @@ -96,7 +88,7 @@ class AndroidEnvelopeCacheTest { } @Test - fun `when startup time is null, does not write startup crash file`() { + fun `when sdk init has not started, does not write startup crash file`() { val cache = fixture.getSut(tmpDir) val hints = HintUtils.createWithTypeCheckHint(UncaughtHint()) @@ -107,7 +99,20 @@ class AndroidEnvelopeCacheTest { @Test fun `when time since sdk init is more than duration threshold, does not write startup crash file`() { - val cache = fixture.getSut(dir = tmpDir, appStartMillis = 1000L, currentTimeMillis = 5000L) + val cache = fixture.getSut(dir = tmpDir, sdkInitStarted = true) + fixture.ticker.advance(4, SECONDS) + + val hints = HintUtils.createWithTypeCheckHint(UncaughtHint()) + cache.storeEnvelope(fixture.envelope, hints) + + assertFalse(fixture.startupCrashMarkerFile.exists()) + } + + @Test + fun `when the device slept through the threshold since sdk init, does not write startup crash file`() { + val cache = fixture.getSut(dir = tmpDir, sdkInitStarted = true) + // The ticker counts deep sleep, which an uptime clock would have left out. + fixture.ticker.advance(5, HOURS) val hints = HintUtils.createWithTypeCheckHint(UncaughtHint()) cache.storeEnvelope(fixture.envelope, hints) @@ -117,7 +122,8 @@ class AndroidEnvelopeCacheTest { @Test fun `when outbox dir is not set, does not write startup crash file`() { - val cache = fixture.getSut(dir = tmpDir, appStartMillis = 1000L, currentTimeMillis = 2000L) + val cache = fixture.getSut(dir = tmpDir, sdkInitStarted = true) + fixture.ticker.advance(1, SECONDS) fixture.options.cacheDirPath = null @@ -129,7 +135,8 @@ class AndroidEnvelopeCacheTest { @Test fun `when time since sdk init is less than duration threshold, writes startup crash file`() { - val cache = fixture.getSut(dir = tmpDir, appStartMillis = 1000L, currentTimeMillis = 2000L) + val cache = fixture.getSut(dir = tmpDir, sdkInitStarted = true) + fixture.ticker.advance(1, SECONDS) val hints = HintUtils.createWithTypeCheckHint(UncaughtHint()) cache.storeEnvelope(fixture.envelope, hints) @@ -139,7 +146,8 @@ class AndroidEnvelopeCacheTest { @Test fun `creates outbox dir when writing startup crash file and dir does not exist yet`() { - val cache = fixture.getSut(dir = tmpDir, appStartMillis = 1000L, currentTimeMillis = 2000L) + val cache = fixture.getSut(dir = tmpDir, sdkInitStarted = true) + fixture.ticker.advance(1, SECONDS) val outboxDir = File(fixture.options.outboxPath!!) assertTrue(outboxDir.deleteRecursively()) From 7e7a282c272cefa51a3a9f7f6c02e54c9ef2d759 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Mon, 23 Nov 2026 11:14:52 +0100 Subject: [PATCH 2/2] changelog Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ba5871de41..accfeb1e582 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ### Fixes +- Android: A crash long after `Sentry.init` is no longer marked as a startup crash when the device slept in between, because the time since init now counts deep sleep ([#6738](https://github.com/getsentry/sentry-java/pull/6738)) - Nav3: Drop an entry’s arguments with `duplicate_key` when distinct map keys stringify to the same key, instead of silently overwriting a value ([#6714](https://github.com/getsentry/sentry-java/pull/6714)) - Nav3: Serialize `NaN` and infinite navigation arguments as strings so they cannot prevent the containing error report or transaction from being serialized ([#6713](https://github.com/getsentry/sentry-java/pull/6713)) - Kotlin now sees `Attachment.getBytes()`, `Device.getArchs()`, `Spring.getActiveProfiles()` and `JsonSerializationUtils.bytesFrom(...)` as nullable, because `@Nullable` now annotates the returned array instead of its elements ([#6558](https://github.com/getsentry/sentry-java/pull/6558))