Skip to content

Commit 31ad03f

Browse files
runningcodeclaudemarkushi
authored
fix(core): Time out performance collection on a monotonic clock (#6739)
* fix(core): Time out performance collection on a monotonic clock The 30s collection timeout compared wall-clock readings, so a backward clock step kept collection running past the timeout and a forward step stopped it early. Measure it with a Deadline on the options' monotonic ticker instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * changelog --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Markus Hintersteiner <markus.hintersteiner@sentry.io>
1 parent 8f0f323 commit 31ad03f

3 files changed

Lines changed: 56 additions & 37 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
- Profiling: No longer crash on API 35+ devices whose framework can't load `ProfilingManager`. Perfetto profiling is turned off on those devices instead ([#6742](https://github.com/getsentry/sentry-java/pull/6742))
1414
- Android: Out-of-process crash reporting now supports Android 5.0 (API level 21) and later, previously required Android 11 (API level 30) ([#6614](https://github.com/getsentry/sentry-java/pull/6614))
1515
- Android profiling: Uploading a Perfetto profile chunk now keeps the trace in memory once instead of up to three times, lowering peak memory use for traces up to 50 MB ([#6743](https://github.com/getsentry/sentry-java/pull/6743))
16+
- Stop a transaction's CPU and memory collection 30 seconds after it starts even when the device's wall clock changes in between ([#6739](https://github.com/getsentry/sentry-java/pull/6739))
1617

1718
### Dependencies
1819

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

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package io.sentry;
22

3+
import io.sentry.time.Deadline;
34
import io.sentry.util.AutoClosableReentrantLock;
45
import io.sentry.util.Objects;
56
import java.util.ArrayList;
@@ -124,7 +125,7 @@ public void run() {
124125
// Add the enriched tempData to all transactions/profiles/objects that collect data.
125126
// Then Check if that object timed out.
126127
for (CompositeData data : compositeDataMap.values()) {
127-
if (data.addDataAndCheckTimeout(tempData, tempData.getNanoTimestamp())) {
128+
if (data.addDataAndCheckTimeout(tempData)) {
128129
// timed out
129130
if (data.transaction != null) {
130131
timedOutTransactions.add(data.transaction);
@@ -212,33 +213,31 @@ public void close() {
212213
private class CompositeData {
213214
private final @NotNull List<PerformanceCollectionData> dataList;
214215
private final @Nullable ITransaction transaction;
215-
private final long startTimestamp;
216+
private final @NotNull Deadline timeout;
216217

217218
private CompositeData(final @Nullable ITransaction transaction) {
218219
this.dataList = new ArrayList<>();
219220
this.transaction = transaction;
220-
this.startTimestamp = options.getDateProvider().now().nanoTimestamp();
221+
this.timeout =
222+
Deadline.after(
223+
options.getMonotonicTicker(),
224+
TRANSACTION_COLLECTION_TIMEOUT_MILLIS,
225+
TimeUnit.MILLISECONDS);
221226
}
222227

223228
/**
224229
* Adds the data to the internal list of PerformanceCollectionData. Then it checks if data
225230
* collection timed out (for transactions only).
226231
*
227-
* @param nowNanos the timestamp of the current collection, passed in so a single clock reading
228-
* is shared by every transaction in this collection round.
229232
* @return true if data collection timed out (for transactions only).
230233
*/
231-
boolean addDataAndCheckTimeout(
232-
final @NotNull PerformanceCollectionData data, final long nowNanos) {
234+
boolean addDataAndCheckTimeout(final @NotNull PerformanceCollectionData data) {
233235
// stop() hands dataList out while this timer thread may still be writing to it, so consumers
234236
// synchronize on the list while iterating. We must hold the same monitor here.
235237
synchronized (dataList) {
236238
dataList.add(data);
237239
}
238-
return transaction != null
239-
&& nowNanos
240-
> startTimestamp
241-
+ TimeUnit.MILLISECONDS.toNanos(TRANSACTION_COLLECTION_TIMEOUT_MILLIS);
240+
return transaction != null && timeout.hasPassed();
242241
}
243242
}
244243
}

‎sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt‎

Lines changed: 45 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@ package io.sentry
33
import io.sentry.test.getCtor
44
import io.sentry.test.getProperty
55
import io.sentry.test.injectForField
6+
import io.sentry.time.MonotonicTicker
7+
import io.sentry.time.TestMonotonicTicker
68
import io.sentry.util.thread.ThreadChecker
79
import java.util.Timer
810
import java.util.concurrent.TimeUnit
11+
import java.util.concurrent.atomic.AtomicReference
912
import kotlin.test.Test
1013
import kotlin.test.assertEquals
1114
import kotlin.test.assertFailsWith
@@ -33,7 +36,12 @@ class DefaultCompositePerformanceCollectorTest {
3336
lateinit var transaction2: ITransaction
3437
val id1 = "id1"
3538
val scopes: IScopes = mock()
36-
val options = SentryOptions()
39+
val ticker = TestMonotonicTicker()
40+
// SentryOptions has no ticker setter.
41+
val options =
42+
object : SentryOptions() {
43+
override fun getMonotonicTicker(): MonotonicTicker = ticker
44+
}
3745
var mockTimer: Timer? = null
3846

3947
val mockCpuCollector: IPerformanceSnapshotCollector =
@@ -183,26 +191,15 @@ class DefaultCompositePerformanceCollectorTest {
183191

184192
@Test
185193
fun `collector times out after 30 seconds`() {
186-
val mockDateProvider = mock<SentryDateProvider>()
187194
val mockCollector = mock<IPerformanceContinuousCollector>()
188-
val dates =
189-
listOf(
190-
SentryNanotimeDate(TimeUnit.SECONDS.toMillis(100), TimeUnit.SECONDS.toNanos(100)),
191-
SentryNanotimeDate(TimeUnit.SECONDS.toMillis(131), TimeUnit.SECONDS.toNanos(131)),
192-
)
193-
whenever(mockDateProvider.now()).thenReturn(dates[0], dates[0], dates[0], dates[1])
194-
val collector = fixture.getSut {
195-
it.dateProvider = mockDateProvider
196-
it.addPerformanceCollector(mockCollector)
197-
}
195+
val collector = fixture.getSut { it.addPerformanceCollector(mockCollector) }
198196
collector.start(fixture.transaction1)
199197
verify(fixture.mockTimer, never())!!.cancel()
200198

199+
fixture.ticker.advance(30, TimeUnit.SECONDS)
201200
// Let's sleep to make the collector get values
202201
Thread.sleep(300)
203202

204-
// When the collector gets the values, it checks the current date, set 31 seconds after the
205-
// begin. This means it should stop itself
206203
verify(fixture.mockTimer)!!.cancel()
207204

208205
// When the collector times out, the data collection for spans is stopped, too
@@ -215,29 +212,51 @@ class DefaultCompositePerformanceCollectorTest {
215212

216213
@Test
217214
fun `collector collects for 30 seconds`() {
218-
val mockDateProvider = mock<SentryDateProvider>()
219-
val dates =
220-
listOf(
221-
SentryNanotimeDate(TimeUnit.SECONDS.toMillis(100), TimeUnit.SECONDS.toNanos(100)),
222-
SentryNanotimeDate(TimeUnit.SECONDS.toMillis(130), TimeUnit.SECONDS.toNanos(130)),
223-
)
224-
whenever(mockDateProvider.now()).thenReturn(dates[0], dates[0], dates[0], dates[1])
225-
val collector = fixture.getSut { it.dateProvider = mockDateProvider }
215+
val collector = fixture.getSut()
226216
collector.start(fixture.transaction1)
227-
verify(fixture.mockTimer, never())!!.cancel()
228217

218+
fixture.ticker.advance(TimeUnit.SECONDS.toNanos(30) - 1, TimeUnit.NANOSECONDS)
229219
// Let's sleep to make the collector get values
230220
Thread.sleep(300)
231221

232-
// When the collector gets the values, it checks the current date, set 30 seconds after the
233-
// begin. This means it should continue without being cancelled
234222
verify(fixture.mockTimer, never())!!.cancel()
235223

236-
// Data is deleted after the collector times out
237224
val data1 = collector.stop(fixture.transaction1)
238225
assertNotNull(data1)
239226
}
240227

228+
@Test
229+
fun `collector keeps collecting when the wall clock steps forward`() {
230+
val wallClock = AtomicReference<SentryDate>(wallClockAt(TimeUnit.HOURS.toSeconds(2)))
231+
val collector = fixture.getSut { it.dateProvider = SentryDateProvider { wallClock.get() } }
232+
collector.start(fixture.transaction1)
233+
234+
wallClock.set(wallClockAt(TimeUnit.HOURS.toSeconds(3)))
235+
// Let's sleep to make the collector get values
236+
Thread.sleep(300)
237+
238+
verify(fixture.mockTimer, never())!!.cancel()
239+
assertNotNull(collector.stop(fixture.transaction1))
240+
}
241+
242+
@Test
243+
fun `collector times out when the wall clock steps backward`() {
244+
val wallClock = AtomicReference<SentryDate>(wallClockAt(TimeUnit.HOURS.toSeconds(2)))
245+
val collector = fixture.getSut { it.dateProvider = SentryDateProvider { wallClock.get() } }
246+
collector.start(fixture.transaction1)
247+
248+
wallClock.set(wallClockAt(TimeUnit.HOURS.toSeconds(1)))
249+
fixture.ticker.advance(30, TimeUnit.SECONDS)
250+
// Let's sleep to make the collector get values
251+
Thread.sleep(300)
252+
253+
verify(fixture.mockTimer)!!.cancel()
254+
assertNull(collector.stop(fixture.transaction1))
255+
}
256+
257+
private fun wallClockAt(seconds: Long) =
258+
SentryNanotimeDate(TimeUnit.SECONDS.toMillis(seconds), TimeUnit.SECONDS.toNanos(seconds))
259+
241260
@Test
242261
fun `collector has no IPerformanceCollector by default`() {
243262
val collector = fixture.getSut(null, null)

0 commit comments

Comments
 (0)