Skip to content

Commit 23b4b90

Browse files
runningcodeclaudesentry-junior[bot]markushi
authored
fix(core): Mark transactions that outlive their deadline as deadline_exceeded (JAVA-642) (#6599)
* fix(core): End transactions at the deadline after the device sleeps (JAVA-642) The deadline timer counts on System.nanoTime(), which stops while an Android device is suspended. It ran hours late, and after a process freeze it raced the main thread, so ui.load transactions ended hours after the deadline, or measured TTID, TTFD and the app start to a late frame and finished as ok. SentryTracer now measures the deadline on the monotonic ticker, which counts suspend, and ends the transaction and its open spans at the wall time the deadline was reached. Once it has passed, every way of finishing the transaction takes that outcome. ActivityLifecycleIntegration applies it before handling a late first frame, full display or destroy, and PerformanceAndroidEventProcessor adds no app start measurement when the app start span was cut short. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * changelog Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ref(core): Return a no-op span after the deadline without finishing Starting a span after the deadline finished and captured the whole transaction on the thread that started the span, which may hold a lock. Return the no-op span only: the overdue deadline timer ends the transaction at the deadline right after. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(core): Change only the status of spans that finish after the deadline Timings now stay exactly as before: the deadline timer ends spans at now() again, spans started after the deadline are recorded, and the ActivityLifecycleIntegration and PerformanceAndroidEventProcessor changes are reverted. Instead, once the monotonic-ticker deadline has passed, Span.finish gives the transaction and any span that finishes after it the status the deadline timer gives: the transaction's own status, or DEADLINE_EXCEEDED. Late frames after a device sleep then no longer report ok, so span.status:ok filters them out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * changelog Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ref(core): Return the deadline status only after the deadline passed getDeadlineStatus() was only correct after a hasDeadlinePassed() check. Fold the check in, so getDeadlineExceededStatus() returns null until the deadline passes, and keep the timer callback as it is on main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Markus Hintersteiner <markus.hintersteiner@sentry.io>
1 parent 4fc0b1e commit 23b4b90

6 files changed

Lines changed: 281 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
- Session Replay: Send Ktor client network request start and end times in milliseconds, so the requests line up with the replay ([#6619](https://github.com/getsentry/sentry-java/pull/6619))
2727
- Nav3: Stop attributing errors and spans from an Activity or ViewPager2 page without a `SentryNavEffect` to the most recently visited Nav3 root ([#6483](https://github.com/getsentry/sentry-java/pull/6483))
2828
- Android: Count deep sleep in breadcrumb, screenshot and view hierarchy debounce windows, so the first low-memory or battery breadcrumb after a long Doze is no longer dropped ([#6590](https://github.com/getsentry/sentry-java/pull/6590))
29+
- Android: Mark transactions and spans that finish after their deadline as `deadline_exceeded`, so `ui.load` transactions with TTID, TTFD or app start values that are hours long after a device sleep no longer report `ok` ([#6599](https://github.com/getsentry/sentry-java/pull/6599))
2930
- Android: Register network callbacks on API 24–25 when `AndroidConnectionStatusProvider` is created with a custom `Handler`, instead of failing because the `Handler` overload needs API 26 ([#6634](https://github.com/getsentry/sentry-java/pull/6634))
3031

3132
### Dependencies

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

Lines changed: 107 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import android.view.View
1515
import android.view.ViewTreeObserver
1616
import androidx.test.core.app.ApplicationProvider
1717
import androidx.test.ext.junit.runners.AndroidJUnit4
18+
import com.google.common.truth.Truth.assertThat
1819
import io.sentry.DateUtils
1920
import io.sentry.FullyDisplayedReporter
2021
import io.sentry.IScope
@@ -43,7 +44,9 @@ import io.sentry.protocol.MeasurementValue
4344
import io.sentry.protocol.SentryId
4445
import io.sentry.protocol.TransactionNameSource
4546
import io.sentry.test.DeferredExecutorService
47+
import io.sentry.test.ManualTimerExecutorService
4648
import io.sentry.test.getProperty
49+
import io.sentry.time.TestMonotonicTicker
4750
import java.util.concurrent.Future
4851
import java.util.concurrent.TimeUnit
4952
import kotlin.test.AfterTest
@@ -68,6 +71,7 @@ import org.mockito.kotlin.clearInvocations
6871
import org.mockito.kotlin.eq
6972
import org.mockito.kotlin.mock
7073
import org.mockito.kotlin.never
74+
import org.mockito.kotlin.spy
7175
import org.mockito.kotlin.times
7276
import org.mockito.kotlin.verify
7377
import org.mockito.kotlin.whenever
@@ -82,7 +86,12 @@ class ActivityLifecycleIntegrationTest {
8286
private class Fixture {
8387
val application = mock<Application>()
8488
val scopes = mock<Scopes>()
85-
val options = SentryAndroidOptions().apply { dsn = "https://key@sentry.io/proj" }
89+
val ticker = TestMonotonicTicker()
90+
// SentryAndroidOptions is final and has no ticker setter, so a spy supplies the ticker.
91+
val options =
92+
spy(SentryAndroidOptions().apply { dsn = "https://key@sentry.io/proj" }).also {
93+
whenever(it.monotonicTicker).thenReturn(ticker)
94+
}
8695
val bundle = mock<Bundle>()
8796
val activityFramesTracker = mock<ActivityFramesTracker>()
8897
val transactionFinishedCallback = mock<TransactionFinishedCallback>()
@@ -2558,6 +2567,99 @@ class ActivityLifecycleIntegrationTest {
25582567
assertNotEquals(0, lastUptimeMillis.nanoTimestamp())
25592568
}
25602569

2570+
@Test
2571+
fun `first frame drawn after the deadline passed changes only the status`() {
2572+
val timer = ManualTimerExecutorService()
2573+
val sut = fixture.getSut {
2574+
it.tracesSampleRate = 1.0
2575+
it.timerExecutorService = timer
2576+
}
2577+
var nowMillis = START_MILLIS
2578+
fixture.options.dateProvider = SentryDateProvider { SentryNanotimeDate(nowMillis, 0) }
2579+
setAppStartTime(SentryNanotimeDate(START_MILLIS, 0))
2580+
sut.register(fixture.scopes, fixture.options)
2581+
val view = fixture.createView()
2582+
val activity = createAndResumeActivity(sut, view)
2583+
val ttidSpan = sut.ttidSpanMap[activity]!!
2584+
val appStartSpan = sut.appStartSpan!!
2585+
2586+
// the device sleeps before the first frame, and the deadline timer hasn't run yet
2587+
fixture.ticker.advance(3, TimeUnit.HOURS)
2588+
nowMillis += TimeUnit.HOURS.toMillis(3)
2589+
runFirstDraw(view)
2590+
timer.runScheduled(fixture.options.idleTimeout!!)
2591+
2592+
val firstFrameNanos = TimeUnit.MILLISECONDS.toNanos(nowMillis)
2593+
for (span in listOf(ttidSpan, appStartSpan)) {
2594+
assertThat(span.status).isEqualTo(SpanStatus.DEADLINE_EXCEEDED)
2595+
assertThat(span.finishDate!!.nanoTimestamp()).isEqualTo(firstFrameNanos)
2596+
}
2597+
assertThat(
2598+
(ttidSpan as Span).measurements[MeasurementValue.KEY_TIME_TO_INITIAL_DISPLAY]!!.value,
2599+
)
2600+
.isEqualTo(TimeUnit.HOURS.toMillis(3))
2601+
assertThat(fixture.transaction.status).isEqualTo(SpanStatus.DEADLINE_EXCEEDED)
2602+
assertThat(fixture.transaction.finishDate!!.nanoTimestamp()).isEqualTo(firstFrameNanos)
2603+
}
2604+
2605+
@Test
2606+
fun `full display reported after the deadline passed changes only the status`() {
2607+
val sut = fixture.getSut {
2608+
it.tracesSampleRate = 1.0
2609+
it.isEnableTimeToFullDisplayTracing = true
2610+
}
2611+
var nowMillis = START_MILLIS
2612+
fixture.options.dateProvider = SentryDateProvider { SentryNanotimeDate(nowMillis, 0) }
2613+
setAppStartTime(SentryNanotimeDate(START_MILLIS, 0))
2614+
sut.register(fixture.scopes, fixture.options)
2615+
val view = fixture.createView()
2616+
val activity = createAndResumeActivity(sut, view)
2617+
val ttfdSpan = sut.ttfdSpanMap[activity]!!
2618+
runFirstDraw(view)
2619+
2620+
fixture.ticker.advance(3, TimeUnit.HOURS)
2621+
nowMillis += TimeUnit.HOURS.toMillis(3)
2622+
fixture.options.fullyDisplayedReporter.reportFullyDrawn()
2623+
2624+
assertThat(ttfdSpan.status).isEqualTo(SpanStatus.DEADLINE_EXCEEDED)
2625+
assertThat(ttfdSpan.finishDate!!.nanoTimestamp())
2626+
.isEqualTo(TimeUnit.MILLISECONDS.toNanos(nowMillis))
2627+
assertThat((ttfdSpan as Span).measurements[MeasurementValue.KEY_TIME_TO_FULL_DISPLAY]!!.value)
2628+
.isEqualTo(TimeUnit.HOURS.toMillis(3))
2629+
}
2630+
2631+
@Test
2632+
fun `first frame drawn before the deadline keeps its status`() {
2633+
val sut = fixture.getSut { it.tracesSampleRate = 1.0 }
2634+
var nowMillis = START_MILLIS
2635+
fixture.options.dateProvider = SentryDateProvider { SentryNanotimeDate(nowMillis, 0) }
2636+
setAppStartTime(SentryNanotimeDate(START_MILLIS, 0))
2637+
sut.register(fixture.scopes, fixture.options)
2638+
val view = fixture.createView()
2639+
val activity = createAndResumeActivity(sut, view)
2640+
val ttidSpan = sut.ttidSpanMap[activity]!!
2641+
2642+
fixture.ticker.advance(29, TimeUnit.SECONDS)
2643+
nowMillis += TimeUnit.SECONDS.toMillis(29)
2644+
runFirstDraw(view)
2645+
2646+
assertThat(ttidSpan.status).isEqualTo(SpanStatus.OK)
2647+
assertThat(ttidSpan.finishDate!!.nanoTimestamp())
2648+
.isEqualTo(TimeUnit.MILLISECONDS.toNanos(nowMillis))
2649+
assertThat(
2650+
(ttidSpan as Span).measurements[MeasurementValue.KEY_TIME_TO_INITIAL_DISPLAY]!!.value,
2651+
)
2652+
.isEqualTo(TimeUnit.SECONDS.toMillis(29))
2653+
}
2654+
2655+
private fun createAndResumeActivity(sut: ActivityLifecycleIntegration, view: View): Activity {
2656+
val activity = mock<Activity>()
2657+
whenever(activity.findViewById<View>(any())).thenReturn(view)
2658+
sut.onActivityCreated(activity, fixture.bundle)
2659+
sut.onActivityResumed(activity)
2660+
return activity
2661+
}
2662+
25612663
private fun SentryTracer.isFinishing() =
25622664
getProperty<Any>("finishStatus").getProperty<Boolean>("isFinishing")
25632665

@@ -2645,6 +2747,10 @@ class ActivityLifecycleIntegrationTest {
26452747
AppStartMetrics.getInstance().onActivityCreated(mock(), mock())
26462748
}
26472749
}
2750+
2751+
private companion object {
2752+
const val START_MILLIS = 1_000_000L
2753+
}
26482754
}
26492755

26502756
private open class SecondAppStartActivity : Activity()

‎sentry-test-support/src/main/kotlin/io/sentry/test/Mocks.kt‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,29 @@ class DeferredExecutorService : ISentryExecutorService {
7575
fun hasScheduledRunnables(): Boolean = scheduledRunnables.isNotEmpty()
7676
}
7777

78+
/**
79+
* Keeps the latest task scheduled with each delay instead of running it, so a test can run one
80+
* timer, such as an idle timeout, while another, such as a deadline, stays pending.
81+
*/
82+
class ManualTimerExecutorService : ISentryExecutorService {
83+
private val scheduled = mutableMapOf<Long, Runnable>()
84+
85+
fun runScheduled(delayMillis: Long) = synchronized(this) { scheduled.getValue(delayMillis) }.run()
86+
87+
override fun schedule(runnable: Runnable, delayMillis: Long): Future<*> {
88+
synchronized(this) { scheduled[delayMillis] = runnable }
89+
return FutureTask {}
90+
}
91+
92+
override fun submit(runnable: Runnable): Future<*> = FutureTask {}
93+
94+
override fun <T> submit(callable: Callable<T>): Future<T> = FutureTask(callable)
95+
96+
override fun close(timeoutMillis: Long) {}
97+
98+
override fun isClosed(): Boolean = false
99+
}
100+
78101
class NonOverridableNoOpSentryExecutorService : ISentryExecutorService {
79102
// mirrors NoOpSentryExecutorService: a task that is never run is reported as cancelled, so
80103
// callers can tell it apart from a queued one

‎sentry/src/main/java/io/sentry/SentryTracer.java‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import io.sentry.protocol.SentryId;
66
import io.sentry.protocol.SentryTransaction;
77
import io.sentry.protocol.TransactionNameSource;
8+
import io.sentry.time.Deadline;
89
import io.sentry.util.AutoClosableReentrantLock;
910
import io.sentry.util.CollectionUtils;
1011
import io.sentry.util.Objects;
@@ -15,6 +16,7 @@
1516
import java.util.Map;
1617
import java.util.concurrent.CopyOnWriteArrayList;
1718
import java.util.concurrent.Future;
19+
import java.util.concurrent.TimeUnit;
1820
import java.util.concurrent.atomic.AtomicBoolean;
1921
import java.util.concurrent.atomic.AtomicReference;
2022
import org.jetbrains.annotations.ApiStatus;
@@ -49,6 +51,15 @@ public final class SentryTracer implements ITransaction {
4951
private final @NotNull AtomicBoolean isIdleFinishTimerRunning = new AtomicBoolean(false);
5052
private final @NotNull AtomicBoolean isDeadlineTimerRunning = new AtomicBoolean(false);
5153

54+
/**
55+
* When the deadline timeout is reached, or null without one.
56+
*
57+
* <p>The deadline timer counts on a clock that stops while an Android device is suspended, so it
58+
* runs late after the device slept, and after the process was frozen the app's own threads can
59+
* finish spans before it. This deadline keeps counting through both.
60+
*/
61+
private volatile @Nullable Deadline deadline;
62+
5263
private @NotNull TransactionNameSource transactionNameSource;
5364
private final @NotNull Instrumenter instrumenter;
5465
private final @NotNull Contexts contexts = new Contexts();
@@ -153,6 +164,20 @@ private void onDeadlineTimeoutReached() {
153164
isDeadlineTimerRunning.set(false);
154165
}
155166

167+
/**
168+
* The status a span finishing now must take because the deadline timeout has been reached, even
169+
* if the deadline timer has not run yet, or null if it has not been reached.
170+
*/
171+
@Nullable
172+
SpanStatus getDeadlineExceededStatus() {
173+
final @Nullable Deadline deadline = this.deadline;
174+
if (deadline == null || !deadline.hasPassed()) {
175+
return null;
176+
}
177+
final @Nullable SpanStatus status = getStatus();
178+
return (status != null) ? status : SpanStatus.DEADLINE_EXCEEDED;
179+
}
180+
156181
@Override
157182
public void forceFinish(
158183
final @NotNull SpanStatus status, final boolean dropIfNoChildren, final @Nullable Hint hint) {
@@ -307,6 +332,9 @@ private void scheduleDeadlineTimeout() {
307332
if (timersEnabled) {
308333
cancelDeadlineTimer();
309334
isDeadlineTimerRunning.set(true);
335+
deadline =
336+
Deadline.after(
337+
scopes.getOptions().getMonotonicTicker(), deadlineTimeOut, TimeUnit.MILLISECONDS);
310338
try {
311339
deadlineTimeoutFuture =
312340
scopes

‎sentry/src/main/java/io/sentry/Span.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,11 @@ public void finish(final @Nullable SpanStatus status, final @Nullable SentryDate
196196
return;
197197
}
198198

199-
this.context.setStatus(status);
199+
// The deadline timer gives this status, but after the device slept or the process was frozen it
200+
// runs late, and the app's own finish can come first. Either way the span outlived the
201+
// deadline, and the status keeps it out of queries on span.status:ok.
202+
final @Nullable SpanStatus deadlineExceededStatus = transaction.getDeadlineExceededStatus();
203+
this.context.setStatus(deadlineExceededStatus != null ? deadlineExceededStatus : status);
200204
this.timestamp = timestamp == null ? scopes.getOptions().getDateProvider().now() : timestamp;
201205
if (options.isTrimStart() || options.isTrimEnd()) {
202206
@Nullable SentryDate minChildStart = null;

0 commit comments

Comments
 (0)