From dd1a7173befb6be2d48ce2fafc2007dcde7be7a4 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Thu, 12 Nov 2026 09:31:24 +0100 Subject: [PATCH 1/3] ref(core): Sample performance data on the timer executor (JAVA-837) DefaultCompositePerformanceCollector sampled CPU and memory every 100ms on a java.util.Timer, the last one in the SDK. Timer schedules on the wall clock, so a backward clock step stopped sampling, and the 30s collection budget check that runs in the same task, until the clock caught back up. The loop now runs on options.getTimerExecutorService(), which schedules on System.nanoTime(). The executor only has one-shot schedule(), so each run reschedules itself. A generation counter, bumped in close(), stops a run that is already in flight from rescheduling a cancelled chain. Based on #5816. Fixes JAVA-837 Co-Authored-By: Claude Opus 5.5 --- .../DefaultCompositePerformanceCollector.java | 139 ++++++++++-------- ...efaultCompositePerformanceCollectorTest.kt | 85 ++++++----- 2 files changed, 129 insertions(+), 95 deletions(-) diff --git a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java index 89373516e2c..2c22c93d3bc 100644 --- a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java +++ b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java @@ -5,9 +5,9 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.jetbrains.annotations.ApiStatus; @@ -19,7 +19,14 @@ public final class DefaultCompositePerformanceCollector implements CompositePerf private static final long TRANSACTION_COLLECTION_INTERVAL_MILLIS = 100; private static final long TRANSACTION_COLLECTION_TIMEOUT_MILLIS = 30000; private final @NotNull AutoClosableReentrantLock timerLock = new AutoClosableReentrantLock(); - private volatile @Nullable Timer timer = null; + private volatile @Nullable Future collectFuture = null; + + /** + * Incremented on close() so an in-flight collect run doesn't reschedule itself after its chain + * was cancelled. Guarded by timerLock. + */ + private long generation = 0; + private final @NotNull Map compositeDataMap = new ConcurrentHashMap<>(); private final @NotNull List snapshotCollectors; private final @NotNull List continuousCollectors; @@ -71,6 +78,7 @@ public void start(final @NotNull ITransaction transaction) { } @Override + @SuppressWarnings("FutureReturnValueIgnored") public void start(final @NotNull String id) { if (hasNoCollectors) { options @@ -88,61 +96,75 @@ public void start(final @NotNull String id) { } if (!isStarted.getAndSet(true)) { try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) { - if (timer == null) { - timer = new Timer(true); - } - // We schedule the timer to call setup() on collectors immediately in the background. - timer.schedule( - new TimerTask() { - @Override - public void run() { - for (IPerformanceSnapshotCollector collector : snapshotCollectors) { - collector.setup(); - } - } - }, - 0L); - // We schedule the timer to start after a delay, so we let some time pass between setup() - // and collect() calls. + final long currentGeneration = generation; + // We schedule the executor to call setup() on collectors immediately in the background. + options + .getTimerExecutorService() + .schedule( + () -> { + for (IPerformanceSnapshotCollector collector : snapshotCollectors) { + collector.setup(); + } + }, + 0L); + // We schedule the collection to start after a delay, so we let some time pass between + // setup() and collect() calls. // This way ICollectors that collect average stats based on time intervals, like // AndroidCpuCollector, can have an actual time interval to evaluate. - final @NotNull List timedOutTransactions = new ArrayList<>(); - TimerTask timerTask = - new TimerTask() { - @Override - public void run() { - timedOutTransactions.clear(); - - final @NotNull PerformanceCollectionData tempData = - new PerformanceCollectionData(options.getDateProvider().now().nanoTimestamp()); - - // Enrich tempData using collectors - for (IPerformanceSnapshotCollector collector : snapshotCollectors) { - collector.collect(tempData); - } - - // Add the enriched tempData to all transactions/profiles/objects that collect data. - // Then Check if that object timed out. - for (CompositeData data : compositeDataMap.values()) { - if (data.addDataAndCheckTimeout(tempData, tempData.getNanoTimestamp())) { - // timed out - if (data.transaction != null) { - timedOutTransactions.add(data.transaction); - } - } - } - // Stop timed out transactions outside compositeDataMap loop, as stop() modifies the - // map - for (final @NotNull ITransaction t : timedOutTransactions) { - stop(t); - } - } - }; - timer.schedule( - timerTask, - TRANSACTION_COLLECTION_INTERVAL_MILLIS, - TRANSACTION_COLLECTION_INTERVAL_MILLIS); + collectFuture = + options + .getTimerExecutorService() + .schedule( + () -> collectAndReschedule(currentGeneration), + TRANSACTION_COLLECTION_INTERVAL_MILLIS); + } catch (RejectedExecutionException e) { + options + .getLogger() + .log(SentryLevel.WARNING, "Failed to schedule performance collection.", e); + } + } + } + + private void collectAndReschedule(final long scheduledGeneration) { + final @NotNull PerformanceCollectionData tempData = + new PerformanceCollectionData(options.getDateProvider().now().nanoTimestamp()); + + // Enrich tempData using collectors + for (IPerformanceSnapshotCollector collector : snapshotCollectors) { + collector.collect(tempData); + } + + // Add the enriched tempData to all transactions/profiles/objects that collect data. + // Then Check if that object timed out. + final @NotNull List timedOutTransactions = new ArrayList<>(); + for (CompositeData data : compositeDataMap.values()) { + if (data.addDataAndCheckTimeout(tempData, tempData.getNanoTimestamp())) { + // timed out + if (data.transaction != null) { + timedOutTransactions.add(data.transaction); + } + } + } + // Stop timed out transactions outside compositeDataMap loop, as stop() modifies the map + for (final @NotNull ITransaction t : timedOutTransactions) { + stop(t); + } + + try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) { + // stopping a timed out transaction above may have closed this collector; only reschedule if + // this run still belongs to the current collection chain + if (scheduledGeneration == generation) { + collectFuture = + options + .getTimerExecutorService() + .schedule( + () -> collectAndReschedule(scheduledGeneration), + TRANSACTION_COLLECTION_INTERVAL_MILLIS); } + } catch (RejectedExecutionException e) { + options + .getLogger() + .log(SentryLevel.WARNING, "Failed to reschedule performance collection.", e); } } @@ -201,9 +223,10 @@ public void close() { } if (isStarted.getAndSet(false)) { try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) { - if (timer != null) { - timer.cancel(); - timer = null; + generation++; + if (collectFuture != null) { + collectFuture.cancel(false); + collectFuture = null; } } } diff --git a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt index 5726b6ca25c..c3ea5ce65eb 100644 --- a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt +++ b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt @@ -2,9 +2,9 @@ package io.sentry import io.sentry.test.getCtor import io.sentry.test.getProperty -import io.sentry.test.injectForField import io.sentry.util.thread.ThreadChecker -import java.util.Timer +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Future import java.util.concurrent.TimeUnit import kotlin.test.Test import kotlin.test.assertEquals @@ -34,7 +34,8 @@ class DefaultCompositePerformanceCollectorTest { val id1 = "id1" val scopes: IScopes = mock() val options = SentryOptions() - var mockTimer: Timer? = null + // a real executor so scheduled collection tasks actually run, recording schedule delays + val executorService = RecordingExecutorService(SentryExecutorService(options)) val mockCpuCollector: IPerformanceSnapshotCollector = object : IPerformanceSnapshotCollector { @@ -47,6 +48,7 @@ class DefaultCompositePerformanceCollectorTest { init { whenever(scopes.options).thenReturn(options) + options.setTimerExecutorService(executorService) } fun getSut( @@ -65,14 +67,23 @@ class DefaultCompositePerformanceCollectorTest { optionsConfiguration.configure(options) transaction1 = SentryTracer(TransactionContext("", ""), scopes) transaction2 = SentryTracer(TransactionContext("", ""), scopes) - val collector = DefaultCompositePerformanceCollector(options) - val timer: Timer = collector.getProperty("timer") ?: Timer(true) - mockTimer = spy(timer) - collector.injectForField("timer", mockTimer) - return collector + return DefaultCompositePerformanceCollector(options) } } + private class RecordingExecutorService(private val delegate: ISentryExecutorService) : + ISentryExecutorService by delegate { + val scheduledDelays = CopyOnWriteArrayList() + + override fun schedule(runnable: Runnable, delayMillis: Long): Future<*> { + scheduledDelays.add(delayMillis) + return delegate.schedule(runnable, delayMillis) + } + } + + private fun CompositePerformanceCollector.collectFuture(): Future<*>? = + getProperty?>("collectFuture") + @Test fun `when null param is provided, invalid argument is thrown`() { val ctor = className.getCtor(ctorTypes) @@ -85,7 +96,7 @@ class DefaultCompositePerformanceCollectorTest { val collector = fixture.getSut(null, null) assertTrue(fixture.options.performanceCollectors.isEmpty()) collector.start(fixture.transaction1) - verify(fixture.mockTimer, never())!!.schedule(any(), any(), any()) + assertTrue(fixture.executorService.scheduledDelays.isEmpty()) } @Test @@ -100,43 +111,43 @@ class DefaultCompositePerformanceCollectorTest { } @Test - fun `when start, timer is scheduled every 100 milliseconds`() { + fun `when start, collection is scheduled every 100 milliseconds`() { val collector = fixture.getSut() collector.start(fixture.transaction1) - verify(fixture.mockTimer)!!.schedule(any(), any(), eq(100)) + assertTrue(fixture.executorService.scheduledDelays.contains(100L)) } @Test - fun `when start with a string, timer is scheduled every 100 milliseconds`() { + fun `when start with a string, collection is scheduled every 100 milliseconds`() { val collector = fixture.getSut() collector.start(fixture.id1) - verify(fixture.mockTimer)!!.schedule(any(), any(), eq(100)) + assertTrue(fixture.executorService.scheduledDelays.contains(100L)) } @Test - fun `when stop, timer is stopped`() { + fun `when stop, collection is stopped`() { val collector = fixture.getSut() collector.start(fixture.transaction1) + assertNotNull(collector.collectFuture()) collector.stop(fixture.transaction1) - verify(fixture.mockTimer)!!.schedule(any(), any(), eq(100)) - verify(fixture.mockTimer)!!.cancel() + assertNull(collector.collectFuture()) } @Test - fun `when stop with a string, timer is stopped`() { + fun `when stop with a string, collection is stopped`() { val collector = fixture.getSut() collector.start(fixture.id1) + assertNotNull(collector.collectFuture()) collector.stop(fixture.id1) - verify(fixture.mockTimer)!!.schedule(any(), any(), eq(100)) - verify(fixture.mockTimer)!!.cancel() + assertNull(collector.collectFuture()) } @Test fun `stopping a not collected transaction return null`() { val collector = fixture.getSut() val data = collector.stop(fixture.transaction1) - verify(fixture.mockTimer, never())!!.schedule(any(), any(), eq(100)) - verify(fixture.mockTimer, never())!!.cancel() + assertTrue(fixture.executorService.scheduledDelays.isEmpty()) + assertNull(collector.collectFuture()) assertNull(data) } @@ -144,8 +155,8 @@ class DefaultCompositePerformanceCollectorTest { fun `stopping a not collected id return null`() { val collector = fixture.getSut() val data = collector.stop(fixture.id1) - verify(fixture.mockTimer, never())!!.schedule(any(), any(), eq(100)) - verify(fixture.mockTimer, never())!!.cancel() + assertTrue(fixture.executorService.scheduledDelays.isEmpty()) + assertNull(collector.collectFuture()) assertNull(data) } @@ -159,16 +170,16 @@ class DefaultCompositePerformanceCollectorTest { Thread.sleep(300) val data1 = collector.stop(fixture.transaction1) - // There is still a transaction and an id running: the timer shouldn't stop now - verify(fixture.mockTimer, never())!!.cancel() + // There is still a transaction and an id running: the collection shouldn't stop now + assertNotNull(collector.collectFuture()) val data2 = collector.stop(fixture.transaction2) - // There is still an id running: the timer shouldn't stop now - verify(fixture.mockTimer, never())!!.cancel() + // There is still an id running: the collection shouldn't stop now + assertNotNull(collector.collectFuture()) val data3 = collector.stop(fixture.id1) - // There are no more transactions or ids running: the time should stop now - verify(fixture.mockTimer)!!.cancel() + // There are no more transactions or ids running: the collection should stop now + assertNull(collector.collectFuture()) assertNotNull(data1) assertNotNull(data2) @@ -196,14 +207,14 @@ class DefaultCompositePerformanceCollectorTest { it.addPerformanceCollector(mockCollector) } collector.start(fixture.transaction1) - verify(fixture.mockTimer, never())!!.cancel() + assertNotNull(collector.collectFuture()) // Let's sleep to make the collector get values Thread.sleep(300) // When the collector gets the values, it checks the current date, set 31 seconds after the // begin. This means it should stop itself - verify(fixture.mockTimer)!!.cancel() + assertNull(collector.collectFuture()) // When the collector times out, the data collection for spans is stopped, too verify(mockCollector).onSpanFinished(eq(fixture.transaction1)) @@ -224,14 +235,14 @@ class DefaultCompositePerformanceCollectorTest { whenever(mockDateProvider.now()).thenReturn(dates[0], dates[0], dates[0], dates[1]) val collector = fixture.getSut { it.dateProvider = mockDateProvider } collector.start(fixture.transaction1) - verify(fixture.mockTimer, never())!!.cancel() + assertNotNull(collector.collectFuture()) // Let's sleep to make the collector get values Thread.sleep(300) // When the collector gets the values, it checks the current date, set 30 seconds after the // begin. This means it should continue without being cancelled - verify(fixture.mockTimer, never())!!.cancel() + assertNotNull(collector.collectFuture()) // Data is deleted after the collector times out val data1 = collector.stop(fixture.transaction1) @@ -298,14 +309,14 @@ class DefaultCompositePerformanceCollectorTest { } @Test - fun `when close, timer is stopped and data is cleared`() { + fun `when close, collection is stopped and data is cleared`() { val collector = fixture.getSut() collector.start(fixture.transaction1) collector.close() - // Timer was canceled - verify(fixture.mockTimer)!!.schedule(any(), any(), eq(100)) - verify(fixture.mockTimer)!!.cancel() + // Collection was canceled + assertTrue(fixture.executorService.scheduledDelays.contains(100L)) + assertNull(collector.collectFuture()) // Data was cleared assertNull(collector.stop(fixture.transaction1)) From 9c6c989a7e1383d62b3f8b15c997042d1284555e Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Wed, 25 Nov 2026 15:54:32 +0100 Subject: [PATCH 2/3] fix(core): Run the first collect a full interval after setup setup() and the first collect() were separate tasks on the shared timer thread, so a busy thread made them run back to back and AndroidCpuCollector divided by a near-zero interval. Co-Authored-By: Claude Opus 5.5 --- .../DefaultCompositePerformanceCollector.java | 45 +++++++++---------- ...efaultCompositePerformanceCollectorTest.kt | 39 +++++++++++++++- 2 files changed, 58 insertions(+), 26 deletions(-) diff --git a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java index 2c22c93d3bc..c4f0297a135 100644 --- a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java +++ b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java @@ -22,8 +22,8 @@ public final class DefaultCompositePerformanceCollector implements CompositePerf private volatile @Nullable Future collectFuture = null; /** - * Incremented on close() so an in-flight collect run doesn't reschedule itself after its chain - * was cancelled. Guarded by timerLock. + * Incremented on close() so an in-flight setup or collect run doesn't schedule the next collect + * after its chain was cancelled. Guarded by timerLock. */ private long generation = 0; @@ -78,7 +78,6 @@ public void start(final @NotNull ITransaction transaction) { } @Override - @SuppressWarnings("FutureReturnValueIgnored") public void start(final @NotNull String id) { if (hasNoCollectors) { options @@ -97,26 +96,10 @@ public void start(final @NotNull String id) { if (!isStarted.getAndSet(true)) { try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) { final long currentGeneration = generation; - // We schedule the executor to call setup() on collectors immediately in the background. - options - .getTimerExecutorService() - .schedule( - () -> { - for (IPerformanceSnapshotCollector collector : snapshotCollectors) { - collector.setup(); - } - }, - 0L); - // We schedule the collection to start after a delay, so we let some time pass between - // setup() and collect() calls. - // This way ICollectors that collect average stats based on time intervals, like - // AndroidCpuCollector, can have an actual time interval to evaluate. collectFuture = options .getTimerExecutorService() - .schedule( - () -> collectAndReschedule(currentGeneration), - TRANSACTION_COLLECTION_INTERVAL_MILLIS); + .schedule(() -> setupAndScheduleCollect(currentGeneration), 0L); } catch (RejectedExecutionException e) { options .getLogger() @@ -125,6 +108,16 @@ public void start(final @NotNull String id) { } } + private void setupAndScheduleCollect(final long scheduledGeneration) { + for (IPerformanceSnapshotCollector collector : snapshotCollectors) { + collector.setup(); + } + // The first collect() is scheduled only after setup() ran, not alongside it: if the shared + // timer thread was busy, both would be due at once and run back to back, leaving collectors + // that average over the time since the previous call, like AndroidCpuCollector, no interval. + scheduleCollect(scheduledGeneration); + } + private void collectAndReschedule(final long scheduledGeneration) { final @NotNull PerformanceCollectionData tempData = new PerformanceCollectionData(options.getDateProvider().now().nanoTimestamp()); @@ -150,9 +143,13 @@ private void collectAndReschedule(final long scheduledGeneration) { stop(t); } + scheduleCollect(scheduledGeneration); + } + + private void scheduleCollect(final long scheduledGeneration) { try (final @NotNull ISentryLifecycleToken ignored = timerLock.acquire()) { - // stopping a timed out transaction above may have closed this collector; only reschedule if - // this run still belongs to the current collection chain + // close() may have run since this chain was scheduled, even from the calling run by stopping + // a timed out transaction; only continue if the chain is still the current one if (scheduledGeneration == generation) { collectFuture = options @@ -162,9 +159,7 @@ private void collectAndReschedule(final long scheduledGeneration) { TRANSACTION_COLLECTION_INTERVAL_MILLIS); } } catch (RejectedExecutionException e) { - options - .getLogger() - .log(SentryLevel.WARNING, "Failed to reschedule performance collection.", e); + options.getLogger().log(SentryLevel.WARNING, "Failed to schedule performance collection.", e); } } diff --git a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt index c3ea5ce65eb..0a61839cbe9 100644 --- a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt +++ b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt @@ -1,11 +1,14 @@ package io.sentry +import com.google.common.truth.Truth.assertThat import io.sentry.test.getCtor import io.sentry.test.getProperty import io.sentry.util.thread.ThreadChecker import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch import java.util.concurrent.Future import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicLong import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -114,6 +117,7 @@ class DefaultCompositePerformanceCollectorTest { fun `when start, collection is scheduled every 100 milliseconds`() { val collector = fixture.getSut() collector.start(fixture.transaction1) + Thread.sleep(300) assertTrue(fixture.executorService.scheduledDelays.contains(100L)) } @@ -121,6 +125,7 @@ class DefaultCompositePerformanceCollectorTest { fun `when start with a string, collection is scheduled every 100 milliseconds`() { val collector = fixture.getSut() collector.start(fixture.id1) + Thread.sleep(300) assertTrue(fixture.executorService.scheduledDelays.contains(100L)) } @@ -291,6 +296,38 @@ class DefaultCompositePerformanceCollectorTest { assertEquals(memoryData.size, cpuData.size) } + @Test + fun `first collect runs a full interval after setup even when the timer thread was busy`() { + val setupNanos = AtomicLong() + val firstCollectNanos = AtomicLong() + val collected = CountDownLatch(1) + val timingCollector = + object : IPerformanceSnapshotCollector { + override fun setup() { + setupNanos.set(System.nanoTime()) + } + + override fun collect(performanceCollectionData: PerformanceCollectionData) { + if (firstCollectNanos.compareAndSet(0, System.nanoTime())) { + collected.countDown() + } + } + } + val collector = fixture.getSut(memoryCollector = null, cpuCollector = timingCollector) + val timerThreadBusy = CountDownLatch(1) + fixture.executorService.schedule({ timerThreadBusy.await() }, 0L) + + collector.start(fixture.transaction1) + // keep the timer thread busy past the collection interval + Thread.sleep(200) + timerThreadBusy.countDown() + + assertTrue(collected.await(1, TimeUnit.SECONDS)) + assertThat(firstCollectNanos.get() - setupNanos.get()) + .isAtLeast(TimeUnit.MILLISECONDS.toNanos(100)) + collector.stop(fixture.transaction1) + } + @Test fun `setup and collect happen on background thread`() { val threadCheckerCollector = spy(ThreadCheckerCollector()) @@ -315,7 +352,7 @@ class DefaultCompositePerformanceCollectorTest { collector.close() // Collection was canceled - assertTrue(fixture.executorService.scheduledDelays.contains(100L)) + assertTrue(fixture.executorService.scheduledDelays.isNotEmpty()) assertNull(collector.collectFuture()) // Data was cleared From 2f9f42d3dc04e7636b1855989a4b8ba06b148fac Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Thu, 26 Nov 2026 16:10:01 +0100 Subject: [PATCH 3/3] test(core): Step the performance collector on a fake timer executor The tests ran collection on a real executor and slept, so they only proved a 100ms delay was requested, and a collector started for a string id kept running until the JVM exited. A hand-advanced fake executor lets the tests count each collect and leaves nothing running after a test ends. Co-Authored-By: Claude Opus 5.5 --- ...efaultCompositePerformanceCollectorTest.kt | 137 ++++++++++++------ 1 file changed, 95 insertions(+), 42 deletions(-) diff --git a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt index 0a61839cbe9..06a8faf545d 100644 --- a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt +++ b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt @@ -1,14 +1,12 @@ package io.sentry -import com.google.common.truth.Truth.assertThat import io.sentry.test.getCtor import io.sentry.test.getProperty import io.sentry.util.thread.ThreadChecker -import java.util.concurrent.CopyOnWriteArrayList -import java.util.concurrent.CountDownLatch +import java.util.concurrent.Callable import java.util.concurrent.Future +import java.util.concurrent.FutureTask import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicLong import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -37,8 +35,7 @@ class DefaultCompositePerformanceCollectorTest { val id1 = "id1" val scopes: IScopes = mock() val options = SentryOptions() - // a real executor so scheduled collection tasks actually run, recording schedule delays - val executorService = RecordingExecutorService(SentryExecutorService(options)) + val executorService = FakeTimerExecutorService() val mockCpuCollector: IPerformanceSnapshotCollector = object : IPerformanceSnapshotCollector { @@ -74,14 +71,56 @@ class DefaultCompositePerformanceCollectorTest { } } - private class RecordingExecutorService(private val delegate: ISentryExecutorService) : - ISentryExecutorService by delegate { - val scheduledDelays = CopyOnWriteArrayList() + /** + * Runs scheduled tasks on the calling thread, only when the test advances its clock, so tests can + * step through each collection and nothing keeps running after a test ends. + */ + private class FakeTimerExecutorService : ISentryExecutorService { + private class ScheduledTask(val runAtMillis: Long, runnable: Runnable) : + FutureTask(runnable, Unit) + + var nowMillis = 0L + private set + + private val tasks = mutableListOf() + val scheduledDelays = mutableListOf() override fun schedule(runnable: Runnable, delayMillis: Long): Future<*> { scheduledDelays.add(delayMillis) - return delegate.schedule(runnable, delayMillis) + return ScheduledTask(nowMillis + delayMillis, runnable).also { tasks.add(it) } + } + + /** Runs, in order, every task due within [millis], including tasks those tasks schedule. */ + fun advanceBy(millis: Long) { + val targetMillis = nowMillis + millis + while (true) { + val next = + tasks + .filterNot { it.isCancelled } + .minByOrNull { it.runAtMillis } + ?.takeIf { + it.runAtMillis <= targetMillis + } ?: break + tasks.remove(next) + nowMillis = maxOf(nowMillis, next.runAtMillis) + next.run() + } + nowMillis = maxOf(nowMillis, targetMillis) } + + /** Called from a running task to simulate it holding the timer thread for [millis]. */ + fun busyFor(millis: Long) { + nowMillis += millis + } + + override fun submit(runnable: Runnable): Future<*> = throw UnsupportedOperationException() + + override fun submit(callable: Callable): Future = + throw UnsupportedOperationException() + + override fun close(timeoutMillis: Long) {} + + override fun isClosed(): Boolean = false } private fun CompositePerformanceCollector.collectFuture(): Future<*>? = @@ -108,25 +147,46 @@ class DefaultCompositePerformanceCollectorTest { val cpuCollector = mock() val collector = fixture.getSut(memoryCollector, cpuCollector) collector.start(fixture.transaction1) - Thread.sleep(300) + fixture.executorService.advanceBy(0) verify(memoryCollector).setup() verify(cpuCollector).setup() } @Test - fun `when start, collection is scheduled every 100 milliseconds`() { - val collector = fixture.getSut() + fun `when start, collection runs every 100 milliseconds`() { + val collector = fixture.getSut(memoryCollector = null, cpuCollector = countingCollector) collector.start(fixture.transaction1) - Thread.sleep(300) - assertTrue(fixture.executorService.scheduledDelays.contains(100L)) + + assertCollectsEvery100Millis() } @Test - fun `when start with a string, collection is scheduled every 100 milliseconds`() { - val collector = fixture.getSut() + fun `when start with a string, collection runs every 100 milliseconds`() { + val collector = fixture.getSut(memoryCollector = null, cpuCollector = countingCollector) collector.start(fixture.id1) - Thread.sleep(300) - assertTrue(fixture.executorService.scheduledDelays.contains(100L)) + + assertCollectsEvery100Millis() + } + + private var collectCount = 0 + private val countingCollector = + object : IPerformanceSnapshotCollector { + override fun setup() {} + + override fun collect(performanceCollectionData: PerformanceCollectionData) { + collectCount++ + } + } + + private fun assertCollectsEvery100Millis() { + fixture.executorService.advanceBy(99) + assertEquals(0, collectCount) + fixture.executorService.advanceBy(1) + assertEquals(1, collectCount) + fixture.executorService.advanceBy(100) + assertEquals(2, collectCount) + fixture.executorService.advanceBy(100) + assertEquals(3, collectCount) } @Test @@ -171,8 +231,7 @@ class DefaultCompositePerformanceCollectorTest { collector.start(fixture.transaction1) collector.start(fixture.transaction2) collector.start(fixture.id1) - // Let's sleep to make the collector get values - Thread.sleep(300) + fixture.executorService.advanceBy(300) val data1 = collector.stop(fixture.transaction1) // There is still a transaction and an id running: the collection shouldn't stop now @@ -214,8 +273,7 @@ class DefaultCompositePerformanceCollectorTest { collector.start(fixture.transaction1) assertNotNull(collector.collectFuture()) - // Let's sleep to make the collector get values - Thread.sleep(300) + fixture.executorService.advanceBy(300) // When the collector gets the values, it checks the current date, set 31 seconds after the // begin. This means it should stop itself @@ -242,8 +300,7 @@ class DefaultCompositePerformanceCollectorTest { collector.start(fixture.transaction1) assertNotNull(collector.collectFuture()) - // Let's sleep to make the collector get values - Thread.sleep(300) + fixture.executorService.advanceBy(300) // When the collector gets the values, it checks the current date, set 30 seconds after the // begin. This means it should continue without being cancelled @@ -280,8 +337,7 @@ class DefaultCompositePerformanceCollectorTest { assertEquals(3, fixture.options.performanceCollectors.size) collector.start(fixture.transaction1) - // Let's sleep to make the collector get values - Thread.sleep(300) + fixture.executorService.advanceBy(300) val data1 = collector.stop(fixture.transaction1) assertNotNull(data1) val memoryData = data1.filter { it.hasUsedHeapMemory() } @@ -298,38 +354,34 @@ class DefaultCompositePerformanceCollectorTest { @Test fun `first collect runs a full interval after setup even when the timer thread was busy`() { - val setupNanos = AtomicLong() - val firstCollectNanos = AtomicLong() - val collected = CountDownLatch(1) + var setupMillis = -1L + var firstCollectMillis = -1L val timingCollector = object : IPerformanceSnapshotCollector { override fun setup() { - setupNanos.set(System.nanoTime()) + setupMillis = fixture.executorService.nowMillis } override fun collect(performanceCollectionData: PerformanceCollectionData) { - if (firstCollectNanos.compareAndSet(0, System.nanoTime())) { - collected.countDown() + if (firstCollectMillis == -1L) { + firstCollectMillis = fixture.executorService.nowMillis } } } val collector = fixture.getSut(memoryCollector = null, cpuCollector = timingCollector) - val timerThreadBusy = CountDownLatch(1) - fixture.executorService.schedule({ timerThreadBusy.await() }, 0L) + fixture.executorService.schedule({ fixture.executorService.busyFor(200) }, 0L) collector.start(fixture.transaction1) - // keep the timer thread busy past the collection interval - Thread.sleep(200) - timerThreadBusy.countDown() + fixture.executorService.advanceBy(300) - assertTrue(collected.await(1, TimeUnit.SECONDS)) - assertThat(firstCollectNanos.get() - setupNanos.get()) - .isAtLeast(TimeUnit.MILLISECONDS.toNanos(100)) - collector.stop(fixture.transaction1) + assertEquals(200, setupMillis) + assertEquals(300, firstCollectMillis) } @Test fun `setup and collect happen on background thread`() { + val executorService = SentryExecutorService(fixture.options) + fixture.options.setTimerExecutorService(executorService) val threadCheckerCollector = spy(ThreadCheckerCollector()) fixture.options.addPerformanceCollector(threadCheckerCollector) val collector = fixture.getSut() @@ -340,6 +392,7 @@ class DefaultCompositePerformanceCollectorTest { // Let's sleep to make the collector get values Thread.sleep(300) collector.stop(fixture.transaction1) + executorService.close(0) verify(threadCheckerCollector).setup() verify(threadCheckerCollector, atLeast(1)).collect(any())