From f181d7e3d7d28b55541f4d10caeae5ba773fc486 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Thu, 12 Nov 2026 09:38:43 +0100 Subject: [PATCH 1/2] fix(profiling): Place CPU and memory samples by their monotonic tick (JAVA-578) AndroidProfiler and PerfettoContinuousProfiler's chunk collector placed each CPU and memory sample on the profile timeline by projecting its wall-clock timestamp through one wall-to-elapsedRealtime offset taken when the profile ended. A wall-clock step during the profile shifted every earlier sample relative to the trace. PerformanceCollectionData now carries a tick from options.getMonotonicTicker(), read when the sample is taken. On Android that is SystemClock.elapsedRealtimeNanos(), the clock both profilers read their start from, so the offset is a plain subtraction. Fixes JAVA-578 Co-Authored-By: Claude Opus 5.5 --- .../sentry/android/core/AndroidProfiler.java | 12 ++------ .../core/PerfettoContinuousProfiler.java | 21 +++----------- .../core/AndroidContinuousProfilerTest.kt | 2 +- .../android/core/AndroidCpuCollectorTest.kt | 4 +-- .../core/AndroidMemoryCollectorTest.kt | 2 +- .../android/core/AndroidProfilerTest.kt | 29 +++++++++++++++++-- .../core/AndroidTransactionProfilerTest.kt | 4 +-- .../core/ChunkMeasurementCollectorTest.kt | 28 +++++++++++++++++- sentry/api/sentry.api | 3 +- .../DefaultCompositePerformanceCollector.java | 4 ++- .../io/sentry/PerformanceCollectionData.java | 14 ++++++++- .../java/io/sentry/JavaMemoryCollectorTest.kt | 2 +- 12 files changed, 86 insertions(+), 39 deletions(-) diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidProfiler.java index 19ea1c40659..a24af5bf280 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidProfiler.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidProfiler.java @@ -26,7 +26,6 @@ import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -303,13 +302,6 @@ public void close() { private void putPerformanceCollectionDataInMeasurements( final @Nullable List performanceCollectionData) { - // This difference is required, since the PerformanceCollectionData timestamps are expressed in - // terms of System.currentTimeMillis() and measurements timestamps require the nanoseconds since - // the beginning, expressed with SystemClock.elapsedRealtimeNanos() - long timestampDiff = - SystemClock.elapsedRealtimeNanos() - - profileStartNanos - - TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); if (performanceCollectionData != null) { final @NotNull ArrayDeque memoryUsageMeasurements = new ArrayDeque<>(performanceCollectionData.size()); @@ -321,7 +313,9 @@ private void putPerformanceCollectionDataInMeasurements( synchronized (performanceCollectionData) { for (final @NotNull PerformanceCollectionData data : performanceCollectionData) { final long nanoTimestamp = data.getNanoTimestamp(); - final long relativeStartNs = nanoTimestamp + timestampDiff; + // The tick comes from options.getMonotonicTicker(), which on Android is + // SystemClock.elapsedRealtimeNanos(), the clock profileStartNanos was read from. + final long relativeStartNs = data.getTickNanos() - profileStartNanos; if (data.hasCpuUsagePercentage()) { cpuUsageMeasurements.add( diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoContinuousProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoContinuousProfiler.java index e41bbbf28fb..f2bb54b2b2d 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoContinuousProfiler.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoContinuousProfiler.java @@ -42,7 +42,6 @@ import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import org.jetbrains.annotations.ApiStatus; @@ -673,14 +672,8 @@ Map stop() { @Nullable List performanceData = null; if (performanceCollector != null && chunkId != null) { performanceData = performanceCollector.stop(chunkId); - final long wallClockNowNanos = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - final long elapsedRealtimeNowNanos = SystemClock.elapsedRealtimeNanos(); addPerformanceDataToMeasurements( - performanceData, - measurements, - wallClockNowNanos, - elapsedRealtimeNowNanos, - profileStartElapsedRealtimeNanos); + performanceData, measurements, profileStartElapsedRealtimeNanos); } performanceCollector = null; chunkId = null; @@ -714,8 +707,6 @@ private void addFrameDataToMeasurements( private static void addPerformanceDataToMeasurements( final @Nullable List performanceData, final @NotNull Map measurements, - final long wallClockNowNanos, - final long elapsedRealtimeNowNanos, final long profileStartElapsedRealtimeNanos) { if (performanceData == null || performanceData.isEmpty()) { return; @@ -731,14 +722,10 @@ private static void addPerformanceDataToMeasurements( // still write to, so we synchronize on it while iterating, as AndroidProfiler does. synchronized (performanceData) { for (final @NotNull PerformanceCollectionData data : performanceData) { - // Convert sample timestamps (reported by CompositePerformanceCollector using - // System.currentTimeMillis), into the SystemClock.elapsedRealtime to report - // elapsed realtime nanos since chunk start final long nanoTimestamp = data.getNanoTimestamp(); - final long nanosSinceSample = wallClockNowNanos - nanoTimestamp; - final long sampleElapsedRealtimeNanos = elapsedRealtimeNowNanos - nanosSinceSample; - final long relativeStartNs = - sampleElapsedRealtimeNanos - profileStartElapsedRealtimeNanos; + // The tick comes from options.getMonotonicTicker(), which on Android is + // SystemClock.elapsedRealtimeNanos(), the clock the chunk start was read from. + final long relativeStartNs = data.getTickNanos() - profileStartElapsedRealtimeNanos; if (data.hasCpuUsagePercentage()) { cpuUsageMeasurements.addLast( new ProfileMeasurementValue( diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidContinuousProfilerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidContinuousProfilerTest.kt index a13f3fe1246..f4002759ca6 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidContinuousProfilerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidContinuousProfilerTest.kt @@ -196,7 +196,7 @@ class AndroidContinuousProfilerTest { @Test fun `profiler sends chunk with measurements`() { val performanceCollector = mock() - val collectionData = PerformanceCollectionData(10) + val collectionData = PerformanceCollectionData(10, 10) collectionData.usedHeapMemory = 2 collectionData.usedNativeMemory = 3 diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidCpuCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidCpuCollectorTest.kt index 422eb1ca804..5f364503cfb 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidCpuCollectorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidCpuCollectorTest.kt @@ -26,14 +26,14 @@ class AndroidCpuCollectorTest { @Test fun `collect works only after setup`() { - val data = PerformanceCollectionData(10) + val data = PerformanceCollectionData(10, 10) fixture.getSut().collect(data) assertThat(data.hasCpuUsagePercentage()).isFalse() } @Test fun `when collect cpu is collected`() { - val data = PerformanceCollectionData(10) + val data = PerformanceCollectionData(10, 10) val collector = fixture.getSut() collector.setup() collector.collect(data) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidMemoryCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidMemoryCollectorTest.kt index 4a7a621ede2..8c8b0fe03de 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidMemoryCollectorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidMemoryCollectorTest.kt @@ -15,7 +15,7 @@ class AndroidMemoryCollectorTest { @Test fun `when collect, both native and heap memory are collected`() { - val data = PerformanceCollectionData(10) + val data = PerformanceCollectionData(10, 10) val usedNativeMemory = Debug.getNativeHeapSize() - Debug.getNativeHeapFreeSize() val usedMemory = fixture.runtime.totalMemory() - fixture.runtime.freeMemory() fixture.collector.collect(data) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidProfilerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidProfilerTest.kt index f402af24f80..8b674c9f182 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidProfilerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidProfilerTest.kt @@ -17,6 +17,7 @@ import java.io.File import java.util.concurrent.Callable import java.util.concurrent.Future import java.util.concurrent.FutureTask +import java.util.concurrent.TimeUnit import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.assertContentEquals @@ -276,13 +277,13 @@ class AndroidProfilerTest { fun `profiler includes performance measurements when passed on end`() { val profiler = fixture.getSut() val performanceCollectionData = ArrayList() - var singleData = PerformanceCollectionData(10) + var singleData = PerformanceCollectionData(10, 10) singleData.usedHeapMemory = 2 singleData.usedNativeMemory = 3 singleData.cpuUsagePercentage = 1.4 performanceCollectionData.add(singleData) - singleData = PerformanceCollectionData(20) + singleData = PerformanceCollectionData(20, 20) singleData.usedHeapMemory = 3 singleData.usedNativeMemory = 4 performanceCollectionData.add(singleData) @@ -303,6 +304,30 @@ class AndroidProfilerTest { ) } + @Test + fun `performance measurements are placed by their tick, not their wall timestamp`() { + val profiler = fixture.getSut() + profiler.start() + val profileStartNanos = profiler.getProperty("profileStartNanos") + // Wall timestamps that disagree with the ticks, as after a clock step during the profile. + val samples = + listOf( + PerformanceCollectionData(0, profileStartNanos + 1_000_000).apply { usedHeapMemory = 2 }, + PerformanceCollectionData(TimeUnit.HOURS.toNanos(5), profileStartNanos + 2_000_000).apply { + usedHeapMemory = 3 + }, + ) + + val data = profiler.endAndCollect(false, samples) + + assertContentEquals( + listOf("1000000", "2000000"), + data!!.measurementsMap[ProfileMeasurement.ID_MEMORY_FOOTPRINT]!!.values.map { + it.relativeStartNs + }, + ) + } + @Test fun `profiler stops profiling, clear running flag and scheduled job on close`() { val profiler = fixture.getSut() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidTransactionProfilerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidTransactionProfilerTest.kt index b37a6bbdee5..e60d2e8ea6a 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidTransactionProfilerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidTransactionProfilerTest.kt @@ -472,13 +472,13 @@ class AndroidTransactionProfilerTest { fun `profiler includes performance measurements when passed on transaction finish`() { val profiler = fixture.getSut(context) val performanceCollectionData = ArrayList() - var singleData = PerformanceCollectionData(10) + var singleData = PerformanceCollectionData(10, 10) singleData.usedHeapMemory = 2 singleData.usedNativeMemory = 3 singleData.cpuUsagePercentage = 1.4 performanceCollectionData.add(singleData) - singleData = PerformanceCollectionData(20) + singleData = PerformanceCollectionData(20, 20) singleData.usedHeapMemory = 3 singleData.usedNativeMemory = 4 performanceCollectionData.add(singleData) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ChunkMeasurementCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ChunkMeasurementCollectorTest.kt index 0841f974961..a998a6172b7 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ChunkMeasurementCollectorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ChunkMeasurementCollectorTest.kt @@ -4,6 +4,7 @@ import io.sentry.CompositePerformanceCollector import io.sentry.PerformanceCollectionData import io.sentry.android.core.internal.util.SentryFrameMetricsCollector import io.sentry.profilemeasurements.ProfileMeasurement +import io.sentry.test.getProperty import java.util.concurrent.TimeUnit import kotlin.test.Test import kotlin.test.assertEquals @@ -105,6 +106,31 @@ class ChunkMeasurementCollectorTest { ) } + @Test + fun `performance samples are placed by their tick, not their wall timestamp`() { + val performanceCollector: CompositePerformanceCollector = mock() + val collector = PerfettoContinuousProfiler.ChunkMeasurementCollector(mock()) + collector.start(performanceCollector, "chunk") + val chunkStart = collector.getProperty("profileStartElapsedRealtimeNanos") + // Wall timestamps that disagree with the ticks, as after a clock step during the chunk. + whenever(performanceCollector.stop(any())) + .thenReturn( + listOf( + PerformanceCollectionData(0, chunkStart + 1_000_000).apply { usedHeapMemory = 1 }, + PerformanceCollectionData(TimeUnit.HOURS.toNanos(5), chunkStart + 2_000_000).apply { + usedHeapMemory = 2 + }, + ) + ) + + val measurements = collector.stop() + + assertEquals( + listOf("1000000", "2000000"), + measurements[ProfileMeasurement.ID_MEMORY_FOOTPRINT]!!.values.map { it.relativeStartNs }, + ) + } + /** * A frameEndNanos far enough ahead of the collector's own `System.nanoTime()` reading that the * chunk-relative timestamp stays positive regardless of test execution timing. @@ -113,7 +139,7 @@ class ChunkMeasurementCollectorTest { /** A null measurement is left unset, as it would be by a collector that did not report it. */ private fun perfData(nanos: Long, cpu: Double?, heap: Long?, native: Long?) = - PerformanceCollectionData(nanos).apply { + PerformanceCollectionData(nanos, nanos).apply { cpu?.let { cpuUsagePercentage = it } heap?.let { usedHeapMemory = it } native?.let { usedNativeMemory = it } diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index dfce80a93d8..cee5d0c95f3 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -2215,9 +2215,10 @@ public final class io/sentry/OutboxSender : io/sentry/IEnvelopeSender { } public final class io/sentry/PerformanceCollectionData { - public fun (J)V + public fun (JJ)V public fun getCpuUsagePercentage ()D public fun getNanoTimestamp ()J + public fun getTickNanos ()J public fun getUsedHeapMemory ()J public fun getUsedNativeMemory ()J public fun hasCpuUsagePercentage ()Z diff --git a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java index 2b5a386300b..45ee3cde680 100644 --- a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java +++ b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java @@ -114,7 +114,9 @@ public void run() { timedOutTransactions.clear(); final @NotNull PerformanceCollectionData tempData = - new PerformanceCollectionData(options.getDateProvider().now().nanoTimestamp()); + new PerformanceCollectionData( + options.getDateProvider().now().nanoTimestamp(), + options.getMonotonicTicker().tickNanos()); // Enrich tempData using collectors for (IPerformanceSnapshotCollector collector : snapshotCollectors) { diff --git a/sentry/src/main/java/io/sentry/PerformanceCollectionData.java b/sentry/src/main/java/io/sentry/PerformanceCollectionData.java index 365cacbeb6f..278ae11e0fa 100644 --- a/sentry/src/main/java/io/sentry/PerformanceCollectionData.java +++ b/sentry/src/main/java/io/sentry/PerformanceCollectionData.java @@ -18,9 +18,17 @@ public final class PerformanceCollectionData { private long usedNativeMemory; private boolean hasUsedNativeMemory; private final long nanoTimestamp; + private final long tickNanos; - public PerformanceCollectionData(final long nanoTimestamp) { + /** + * @param nanoTimestamp when the sample was taken, in epoch nanoseconds + * @param tickNanos when the sample was taken, on {@link SentryOptions#getMonotonicTicker()}. + * Profilers place samples on their timeline with it, because the wall clock can step while a + * profile runs. + */ + public PerformanceCollectionData(final long nanoTimestamp, final long tickNanos) { this.nanoTimestamp = nanoTimestamp; + this.tickNanos = tickNanos; } /** Set the cpu usage percentage. */ @@ -69,4 +77,8 @@ public boolean hasUsedNativeMemory() { public long getNanoTimestamp() { return nanoTimestamp; } + + public long getTickNanos() { + return tickNanos; + } } diff --git a/sentry/src/test/java/io/sentry/JavaMemoryCollectorTest.kt b/sentry/src/test/java/io/sentry/JavaMemoryCollectorTest.kt index 7f2b593b9a5..d47f80b607a 100644 --- a/sentry/src/test/java/io/sentry/JavaMemoryCollectorTest.kt +++ b/sentry/src/test/java/io/sentry/JavaMemoryCollectorTest.kt @@ -13,7 +13,7 @@ class JavaMemoryCollectorTest { @Test fun `when collect, only heap memory is collected`() { - val data = PerformanceCollectionData(10) + val data = PerformanceCollectionData(10, 10) val usedMemory = fixture.runtime.totalMemory() - fixture.runtime.freeMemory() fixture.collector.collect(data) assertThat(data.hasUsedNativeMemory()).isFalse() From c45c66666ab5d1966ccebabe660603a6596c44ee Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Thu, 12 Nov 2026 09:39:13 +0100 Subject: [PATCH 2/2] changelog --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bf5027ddd3..722d687c2e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ > - Java 8 support will be dropped. SDK 9.0.0 requires Java 11+. See [#6469](https://github.com/getsentry/sentry-java/issues/6469). > - The Android `minSdk` will be raised from 21 to 24. See [#5508](https://github.com/getsentry/sentry-java/issues/5508). +## Unreleased + +### Fixes + +- Android: Keep CPU and memory samples aligned with the profile when the device clock changes during profiling ([#6591](https://github.com/getsentry/sentry-java/pull/6591)) + ## 8.64.0 ### Breaking Changes