From 11a18a107fce318e804f25d441d8c1ba4ba7cee5 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Thu, 12 Nov 2026 09:38:43 +0100 Subject: [PATCH 1/6] 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 +- .../io/sentry/PerformanceCollectionData.java | 14 ++++++++- .../java/io/sentry/JavaMemoryCollectorTest.kt | 2 +- 11 files changed, 83 insertions(+), 38 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 63512b7dd99..8c0cd7c2bee 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; @@ -672,14 +671,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; @@ -713,8 +706,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; @@ -730,14 +721,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 5a27a303342..abbdf92f916 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 8f493343d1e..6d8220b5fd8 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 3dc8ed74c4a..4f460b9753c 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -2228,9 +2228,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/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 d9e154efb4e9f79e3c916c7a805b7f6496c062ef Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Thu, 12 Nov 2026 09:39:13 +0100 Subject: [PATCH 2/6] changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 67ebd245813..d0d2e31b26c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - Session Replay: Stop dropping or freezing video when the device clock changes mid-recording ([#6542](https://github.com/getsentry/sentry-java/pull/6542)) - Breadcrumbs and errors stay aligned with the video. In a full-session recording, the video since the last segment sent before the change (up to 5s) is dropped. When recording only for errors, what was buffered before the change is kept, and the replay of a later error shows the change as a gap or an overlap. - A forward change longer than the session duration (1h) ends a full-session recording, as reaching that duration does. When recording only for errors, such a change drops what was buffered before it. +- 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.67.0 From 100d29d332cd1ec6e30b3661a20c48f9a348eedb Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Mon, 23 Nov 2026 11:19:55 +0100 Subject: [PATCH 3/6] test(profiling): Read the profile start from start() instead of reflection start() already returns the start tick in ProfileStartData, so the test no longer depends on a private field name. Co-Authored-By: Claude Opus 5.5 --- .../test/java/io/sentry/android/core/AndroidProfilerTest.kt | 3 +-- .../io/sentry/android/core/ChunkMeasurementCollectorTest.kt | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) 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 6d8220b5fd8..da00dd87626 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 @@ -307,8 +307,7 @@ 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") + val profileStartNanos = profiler.start()!!.startNanos // Wall timestamps that disagree with the ticks, as after a clock step during the profile. val samples = listOf( 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 a998a6172b7..1518b8a5004 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 @@ -120,7 +120,7 @@ class ChunkMeasurementCollectorTest { PerformanceCollectionData(TimeUnit.HOURS.toNanos(5), chunkStart + 2_000_000).apply { usedHeapMemory = 2 }, - ) + ), ) val measurements = collector.stop() From 408a98192fa56f41910ec7d804c66ec9d4c4dc8d Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Fri, 4 Dec 2026 14:49:44 +0100 Subject: [PATCH 4/6] fix(profiling): Time CPU and memory samples from the profile start A sample's absolute timestamp was still read from the wall clock when it was taken, so a clock change during a profile moved it. The frontend places continuous profile measurements by that timestamp, not by elapsed_since_start_ns. Samples now carry only their monotonic tick. Each profiler reads the wall clock once when it starts and computes both the offset and the timestamp of every sample from that reading and the sample's tick. The PerformanceCollectionData constructor keeps its single long argument, now the tick. Refs JAVA-578 Co-Authored-By: Claude Opus 5.5 --- .../sentry/android/core/AndroidProfiler.java | 9 +++-- .../core/PerfettoContinuousProfiler.java | 20 ++++++++--- .../core/AndroidContinuousProfilerTest.kt | 2 +- .../android/core/AndroidCpuCollectorTest.kt | 4 +-- .../core/AndroidMemoryCollectorTest.kt | 2 +- .../android/core/AndroidProfilerTest.kt | 34 +++++++++++-------- .../core/AndroidTransactionProfilerTest.kt | 4 +-- .../core/ChunkMeasurementCollectorTest.kt | 25 ++++++++------ sentry/api/sentry.api | 3 +- .../DefaultCompositePerformanceCollector.java | 2 +- .../io/sentry/PerformanceCollectionData.java | 15 +++----- .../java/io/sentry/JavaMemoryCollectorTest.kt | 4 +-- 12 files changed, 69 insertions(+), 55 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 a24af5bf280..0e05c076e9d 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 @@ -79,6 +79,9 @@ public ProfileEndData( private static final int PROFILING_TIMEOUT_MILLIS = 30_000; private long profileStartNanos = 0; + // Wall-clock time read alongside profileStartNanos. CPU and memory samples get their timestamps + // by adding their elapsed time to it, so a clock change during the profile cannot move them. + private long profileStartEpochNanos = 0; private final @NotNull File traceFilesDir; private final int intervalUs; private @Nullable Future scheduledFinish = null; @@ -201,7 +204,9 @@ public void onFrameMetricCollected( } profileStartNanos = SystemClock.elapsedRealtimeNanos(); - final @NotNull Date profileStartTimestamp = DateUtils.getCurrentDateTime(); + final long profileStartMillis = System.currentTimeMillis(); + final @NotNull Date profileStartTimestamp = DateUtils.getDateTime(profileStartMillis); + profileStartEpochNanos = DateUtils.millisToNanos(profileStartMillis); long profileStartCpuMillis = Process.getElapsedCpuTime(); // We don't make any check on the file existence or writeable state, because we don't want to @@ -312,10 +317,10 @@ private void putPerformanceCollectionDataInMeasurements( synchronized (performanceCollectionData) { for (final @NotNull PerformanceCollectionData data : performanceCollectionData) { - final long nanoTimestamp = data.getNanoTimestamp(); // The tick comes from options.getMonotonicTicker(), which on Android is // SystemClock.elapsedRealtimeNanos(), the clock profileStartNanos was read from. final long relativeStartNs = data.getTickNanos() - profileStartNanos; + final long nanoTimestamp = profileStartEpochNanos + relativeStartNs; 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 8c0cd7c2bee..2ed24da1cfe 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 @@ -8,6 +8,7 @@ import androidx.annotation.RequiresApi; import io.sentry.CompositePerformanceCollector; import io.sentry.DataCategory; +import io.sentry.DateUtils; import io.sentry.IContinuousProfiler; import io.sentry.ILogger; import io.sentry.IScopes; @@ -582,10 +583,14 @@ static final class ChunkMeasurementCollector { screenFrameRateMeasurements = new ConcurrentLinkedDeque<>(); // Elapsed realtime when the measurement was started (nanosecond precision). - // Used to convert wall-time clock values into ns-since-chunk-start for the measurements - // payload. + // Measurements are placed on the chunk's timeline relative to it. private long profileStartElapsedRealtimeNanos = 0; + // Wall-clock time read alongside profileStartElapsedRealtimeNanos. CPU and memory samples get + // their timestamps by adding their elapsed time to it, so a clock change during the chunk + // cannot move them. + private long profileStartEpochNanos = 0; + ChunkMeasurementCollector(final @NotNull SentryFrameMetricsCollector frameMetricsCollector) { this.frameMetricsCollector = frameMetricsCollector; } @@ -596,6 +601,7 @@ void start( this.performanceCollector = performanceCollector; this.chunkId = chunkId; this.profileStartElapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos(); + this.profileStartEpochNanos = DateUtils.millisToNanos(System.currentTimeMillis()); // Start frame metrics collection (runs on the FrameMetrics HandlerThread) slowFrameRenderMeasurements.clear(); @@ -672,7 +678,10 @@ Map stop() { if (performanceCollector != null && chunkId != null) { performanceData = performanceCollector.stop(chunkId); addPerformanceDataToMeasurements( - performanceData, measurements, profileStartElapsedRealtimeNanos); + performanceData, + measurements, + profileStartElapsedRealtimeNanos, + profileStartEpochNanos); } performanceCollector = null; chunkId = null; @@ -706,7 +715,8 @@ private void addFrameDataToMeasurements( private static void addPerformanceDataToMeasurements( final @Nullable List performanceData, final @NotNull Map measurements, - final long profileStartElapsedRealtimeNanos) { + final long profileStartElapsedRealtimeNanos, + final long profileStartEpochNanos) { if (performanceData == null || performanceData.isEmpty()) { return; } @@ -721,10 +731,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) { - final long nanoTimestamp = data.getNanoTimestamp(); // 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; + final long nanoTimestamp = profileStartEpochNanos + relativeStartNs; 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 abbdf92f916..5a27a303342 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, 10) + val collectionData = PerformanceCollectionData(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 5f364503cfb..422eb1ca804 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, 10) + val data = PerformanceCollectionData(10) fixture.getSut().collect(data) assertThat(data.hasCpuUsagePercentage()).isFalse() } @Test fun `when collect cpu is collected`() { - val data = PerformanceCollectionData(10, 10) + val data = PerformanceCollectionData(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 8c8b0fe03de..4a7a621ede2 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, 10) + val data = PerformanceCollectionData(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 da00dd87626..5c4f1ee6d59 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 @@ -3,6 +3,7 @@ package io.sentry.android.core import android.content.Context import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.sentry.DateUtils import io.sentry.ILogger import io.sentry.ISentryExecutorService import io.sentry.PerformanceCollectionData @@ -17,7 +18,6 @@ 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 @@ -277,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, 10) + var singleData = PerformanceCollectionData(10) singleData.usedHeapMemory = 2 singleData.usedNativeMemory = 3 singleData.cpuUsagePercentage = 1.4 performanceCollectionData.add(singleData) - singleData = PerformanceCollectionData(20, 20) + singleData = PerformanceCollectionData(20) singleData.usedHeapMemory = 3 singleData.usedNativeMemory = 4 performanceCollectionData.add(singleData) @@ -305,25 +305,29 @@ class AndroidProfilerTest { } @Test - fun `performance measurements are placed by their tick, not their wall timestamp`() { + fun `performance measurements are timed by their tick from the profile start`() { val profiler = fixture.getSut() - val profileStartNanos = profiler.start()!!.startNanos - // Wall timestamps that disagree with the ticks, as after a clock step during the profile. + val start = profiler.start()!! + val startEpochNanos = DateUtils.millisToNanos(start.startTimestamp.time) val samples = listOf( - PerformanceCollectionData(0, profileStartNanos + 1_000_000).apply { usedHeapMemory = 2 }, - PerformanceCollectionData(TimeUnit.HOURS.toNanos(5), profileStartNanos + 2_000_000).apply { - usedHeapMemory = 3 - }, + PerformanceCollectionData(start.startNanos + 1_000_000).apply { usedHeapMemory = 2 }, + PerformanceCollectionData(start.startNanos + 2_000_000).apply { usedHeapMemory = 3 }, ) - val data = profiler.endAndCollect(false, samples) + val values = + profiler + .endAndCollect(false, samples)!! + .measurementsMap[ProfileMeasurement.ID_MEMORY_FOOTPRINT]!! + .values + assertContentEquals(listOf("1000000", "2000000"), values.map { it.relativeStartNs }) assertContentEquals( - listOf("1000000", "2000000"), - data!!.measurementsMap[ProfileMeasurement.ID_MEMORY_FOOTPRINT]!!.values.map { - it.relativeStartNs - }, + listOf( + DateUtils.nanosToSeconds(startEpochNanos + 1_000_000), + DateUtils.nanosToSeconds(startEpochNanos + 2_000_000), + ), + values.map { it.timestamp }, ) } 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 e60d2e8ea6a..b37a6bbdee5 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, 10) + var singleData = PerformanceCollectionData(10) singleData.usedHeapMemory = 2 singleData.usedNativeMemory = 3 singleData.cpuUsagePercentage = 1.4 performanceCollectionData.add(singleData) - singleData = PerformanceCollectionData(20, 20) + singleData = PerformanceCollectionData(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 1518b8a5004..fbe1cc23e80 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 @@ -1,6 +1,7 @@ package io.sentry.android.core import io.sentry.CompositePerformanceCollector +import io.sentry.DateUtils import io.sentry.PerformanceCollectionData import io.sentry.android.core.internal.util.SentryFrameMetricsCollector import io.sentry.profilemeasurements.ProfileMeasurement @@ -107,27 +108,29 @@ class ChunkMeasurementCollectorTest { } @Test - fun `performance samples are placed by their tick, not their wall timestamp`() { + fun `performance samples are timed by their tick from the chunk start`() { 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. + val chunkStartTick = collector.getProperty("profileStartElapsedRealtimeNanos") + val chunkStartEpochNanos = collector.getProperty("profileStartEpochNanos") 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 - }, + PerformanceCollectionData(chunkStartTick + 1_000_000).apply { usedHeapMemory = 1 }, + PerformanceCollectionData(chunkStartTick + 2_000_000).apply { usedHeapMemory = 2 }, ), ) - val measurements = collector.stop() + val values = collector.stop()[ProfileMeasurement.ID_MEMORY_FOOTPRINT]!!.values + assertEquals(listOf("1000000", "2000000"), values.map { it.relativeStartNs }) assertEquals( - listOf("1000000", "2000000"), - measurements[ProfileMeasurement.ID_MEMORY_FOOTPRINT]!!.values.map { it.relativeStartNs }, + listOf( + DateUtils.nanosToSeconds(chunkStartEpochNanos + 1_000_000), + DateUtils.nanosToSeconds(chunkStartEpochNanos + 2_000_000), + ), + values.map { it.timestamp }, ) } @@ -139,7 +142,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, nanos).apply { + PerformanceCollectionData(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 4f460b9753c..7c13f683d21 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -2228,9 +2228,8 @@ public final class io/sentry/OutboxSender : io/sentry/IEnvelopeSender { } public final class io/sentry/PerformanceCollectionData { - public fun (JJ)V + public fun (J)V public fun getCpuUsagePercentage ()D - public fun getNanoTimestamp ()J public fun getTickNanos ()J public fun getUsedHeapMemory ()J public fun getUsedNativeMemory ()J diff --git a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java index 44934b314d6..2277d1e279d 100644 --- a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java +++ b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java @@ -121,7 +121,7 @@ private void setupAndScheduleCollect(final long scheduledGeneration) { private void collectAndReschedule(final long scheduledGeneration) { final @NotNull PerformanceCollectionData tempData = - new PerformanceCollectionData(options.getDateProvider().now().nanoTimestamp()); + new PerformanceCollectionData(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 278ae11e0fa..fb1e5331826 100644 --- a/sentry/src/main/java/io/sentry/PerformanceCollectionData.java +++ b/sentry/src/main/java/io/sentry/PerformanceCollectionData.java @@ -17,17 +17,14 @@ public final class PerformanceCollectionData { private boolean hasUsedHeapMemory; private long usedNativeMemory; private boolean hasUsedNativeMemory; - private final long nanoTimestamp; private final long tickNanos; /** - * @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. + * @param tickNanos when the sample was taken, on {@link SentryOptions#getMonotonicTicker()}. A + * sample carries no wall-clock time, because the wall clock can change while a profile runs: + * each profiler projects the tick onto the wall-clock time it read when it started. */ - public PerformanceCollectionData(final long nanoTimestamp, final long tickNanos) { - this.nanoTimestamp = nanoTimestamp; + public PerformanceCollectionData(final long tickNanos) { this.tickNanos = tickNanos; } @@ -74,10 +71,6 @@ public boolean hasUsedNativeMemory() { return 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 d47f80b607a..0cd57e3205e 100644 --- a/sentry/src/test/java/io/sentry/JavaMemoryCollectorTest.kt +++ b/sentry/src/test/java/io/sentry/JavaMemoryCollectorTest.kt @@ -13,12 +13,12 @@ class JavaMemoryCollectorTest { @Test fun `when collect, only heap memory is collected`() { - val data = PerformanceCollectionData(10, 10) + val data = PerformanceCollectionData(10) val usedMemory = fixture.runtime.totalMemory() - fixture.runtime.freeMemory() fixture.collector.collect(data) assertThat(data.hasUsedNativeMemory()).isFalse() assertThat(data.hasUsedHeapMemory()).isTrue() assertThat(data.usedHeapMemory).isEqualTo(usedMemory) - assertThat(data.nanoTimestamp).isEqualTo(10) + assertThat(data.tickNanos).isEqualTo(10) } } From c1dba0b03ea0503683314e07951c09eb07d0480a Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Fri, 4 Dec 2026 15:54:56 +0100 Subject: [PATCH 5/6] ref(profiling): Time samples with AnchoredClock and injected clocks The profilers now get their EpochClock and MonotonicTicker through their constructors and project sample timestamps with AnchoredClock, instead of reading System.currentTimeMillis() and SystemClock directly. The sample ticks come from options.getMonotonicTicker(), and MonotonicTicker forbids comparing ticks from different tickers, so the profile start now comes from the same ticker. AnchoredClock.at(tick) is now public, because samples are stamped on the collector thread and projected later. App start profiling has no options yet, so it passes the clocks SentryAndroidOptions returns. AndroidProfiler keeps its old constructor for sentry-react-native. Refs JAVA-578 Co-Authored-By: Claude Opus 5.5 --- .../api/sentry-android-core.api | 5 +- .../core/AndroidContinuousProfiler.java | 14 +++- .../core/AndroidOptionsInitializer.java | 8 ++- .../sentry/android/core/AndroidProfiler.java | 69 +++++++++++++------ .../core/AndroidTransactionProfiler.java | 26 +++++-- .../core/PerfettoContinuousProfiler.java | 61 +++++++++------- .../core/SentryPerformanceProvider.java | 11 ++- .../core/AndroidContinuousProfilerTest.kt | 2 + .../android/core/AndroidProfilerTest.kt | 37 +++++++--- .../core/ChunkMeasurementCollectorTest.kt | 47 +++++++++---- .../core/PerfettoContinuousProfilerTest.kt | 2 + sentry/api/sentry.api | 1 + .../java/io/sentry/time/AnchoredClock.java | 6 +- .../java/io/sentry/time/AnchoredClockTest.kt | 11 +++ 14 files changed, 218 insertions(+), 82 deletions(-) diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index dd207c3ef69..dc161e22cad 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -41,7 +41,7 @@ public final class io/sentry/android/core/ActivityLifecycleIntegration : android } public final class io/sentry/android/core/AndroidContinuousProfiler : io/sentry/IContinuousProfiler, io/sentry/transport/RateLimiter$IRateLimitObserver { - public fun (Lio/sentry/android/core/BuildInfoProvider;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/ILogger;Ljava/lang/String;ILio/sentry/util/LazyEvaluator$Evaluator;)V + public fun (Lio/sentry/android/core/BuildInfoProvider;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/ILogger;Ljava/lang/String;ILio/sentry/util/LazyEvaluator$Evaluator;Lio/sentry/time/EpochClock;Lio/sentry/time/MonotonicTicker;)V public fun close (Z)V public fun getChunkId ()Lio/sentry/protocol/SentryId; public fun getProfileRecordingState (Lio/sentry/protocol/SentryId;Lio/sentry/SentryDate;Lio/sentry/SentryDate;)Lio/sentry/profiling/ProfileRecordingState; @@ -120,6 +120,7 @@ public final class io/sentry/android/core/AndroidMetricsBatchProcessorFactory : public final class io/sentry/android/core/AndroidProfiler { public fun (Ljava/lang/String;ILio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/util/LazyEvaluator$Evaluator;Lio/sentry/ILogger;)V + public fun (Ljava/lang/String;ILio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/util/LazyEvaluator$Evaluator;Lio/sentry/ILogger;Lio/sentry/time/EpochClock;Lio/sentry/time/MonotonicTicker;)V public fun close ()V public fun endAndCollect (ZLjava/util/List;)Lio/sentry/android/core/AndroidProfiler$ProfileEndData; public fun start ()Lio/sentry/android/core/AndroidProfiler$ProfileStartData; @@ -394,7 +395,7 @@ public final class io/sentry/android/core/NetworkBreadcrumbsIntegration : io/sen } public final class io/sentry/android/core/PerfettoContinuousProfiler : io/sentry/IContinuousProfiler, io/sentry/transport/RateLimiter$IRateLimitObserver { - public fun (Lio/sentry/ILogger;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/util/LazyEvaluator$Evaluator;Ljava/util/function/Supplier;)V + public fun (Lio/sentry/ILogger;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/util/LazyEvaluator$Evaluator;Ljava/util/function/Supplier;Lio/sentry/time/EpochClock;Lio/sentry/time/MonotonicTicker;)V public fun close (Z)V public fun getChunkId ()Lio/sentry/protocol/SentryId; public fun getProfileRecordingState (Lio/sentry/protocol/SentryId;Lio/sentry/SentryDate;Lio/sentry/SentryDate;)Lio/sentry/profiling/ProfileRecordingState; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidContinuousProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidContinuousProfiler.java index 622f74ca55a..09d2be75f5a 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidContinuousProfiler.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidContinuousProfiler.java @@ -25,6 +25,8 @@ import io.sentry.android.core.internal.util.SentryFrameMetricsCollector; import io.sentry.profiling.ProfileRecordingState; import io.sentry.protocol.SentryId; +import io.sentry.time.EpochClock; +import io.sentry.time.MonotonicTicker; import io.sentry.transport.RateLimiter; import io.sentry.util.AutoClosableReentrantLock; import io.sentry.util.LazyEvaluator; @@ -53,6 +55,8 @@ public final class AndroidContinuousProfiler private final @Nullable String profilingTracesDirPath; private final int profilingTracesHz; private final @NotNull LazyEvaluator.Evaluator executorServiceSupplier; + private final @NotNull EpochClock epochClock; + private final @NotNull MonotonicTicker ticker; private final @NotNull BuildInfoProvider buildInfoProvider; private boolean isInitialized = false; private final @NotNull SentryFrameMetricsCollector frameMetricsCollector; @@ -80,13 +84,17 @@ public AndroidContinuousProfiler( final @NotNull ILogger logger, final @Nullable String profilingTracesDirPath, final int profilingTracesHz, - final @NotNull LazyEvaluator.Evaluator executorServiceSupplier) { + final @NotNull LazyEvaluator.Evaluator executorServiceSupplier, + final @NotNull EpochClock epochClock, + final @NotNull MonotonicTicker ticker) { this.logger = logger; this.frameMetricsCollector = frameMetricsCollector; this.buildInfoProvider = buildInfoProvider; this.profilingTracesDirPath = profilingTracesDirPath; this.profilingTracesHz = profilingTracesHz; this.executorServiceSupplier = executorServiceSupplier; + this.epochClock = epochClock; + this.ticker = ticker; } private void init() { @@ -115,7 +123,9 @@ private void init() { (int) SECONDS.toMicros(1) / profilingTracesHz, frameMetricsCollector, null, - logger); + logger, + epochClock, + ticker); } @Override diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java index 52a54b339dc..1cec778d59c 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java @@ -389,7 +389,9 @@ private static void setupProfiler( () -> options.getExecutorService(), () -> new PerfettoProfiler( - appContext, options.getLogger(), options.getExecutorService()))); + appContext, options.getLogger(), options.getExecutorService()), + options.getEpochClock(), + options.getMonotonicTicker())); // Report adoption of the Perfetto continuous profiling backend (API 35+). addIntegrationToSdkVersion("PerfettoContinuousProfiling"); } else if (options.isEnableLegacyProfiling()) { @@ -400,7 +402,9 @@ private static void setupProfiler( options.getLogger(), options.getProfilingTracesDirPath(), options.getProfilingTracesHz(), - () -> options.getExecutorService())); + () -> options.getExecutorService(), + options.getEpochClock(), + options.getMonotonicTicker())); } else { options .getLogger() 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 0e05c076e9d..fa1072366ad 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 @@ -3,7 +3,6 @@ import android.annotation.SuppressLint; import android.os.Debug; import android.os.Process; -import android.os.SystemClock; import io.sentry.DateUtils; import io.sentry.ILogger; import io.sentry.ISentryExecutorService; @@ -12,9 +11,14 @@ import io.sentry.SentryLevel; import io.sentry.SentryNanotimeDate; import io.sentry.SentryUUID; +import io.sentry.android.core.internal.time.AndroidMonotonicTicker; import io.sentry.android.core.internal.util.SentryFrameMetricsCollector; import io.sentry.profilemeasurements.ProfileMeasurement; import io.sentry.profilemeasurements.ProfileMeasurementValue; +import io.sentry.time.AnchoredClock; +import io.sentry.time.EpochClock; +import io.sentry.time.MonotonicTicker; +import io.sentry.time.SystemEpochClock; import io.sentry.util.AutoClosableReentrantLock; import io.sentry.util.LazyEvaluator; import io.sentry.util.Objects; @@ -79,9 +83,11 @@ public ProfileEndData( private static final int PROFILING_TIMEOUT_MILLIS = 30_000; private long profileStartNanos = 0; - // Wall-clock time read alongside profileStartNanos. CPU and memory samples get their timestamps - // by adding their elapsed time to it, so a clock change during the profile cannot move them. - private long profileStartEpochNanos = 0; + // CPU and memory samples get their timestamps from it rather than from the wall clock when they + // were taken, so a clock change during the profile cannot move them. + private @Nullable AnchoredClock profileClock = null; + private final @NotNull EpochClock epochClock; + private final @NotNull MonotonicTicker ticker; private final @NotNull File traceFilesDir; private final int intervalUs; private @Nullable Future scheduledFinish = null; @@ -101,6 +107,7 @@ public ProfileEndData( private volatile boolean isRunning = false; final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); + /** Kept for sentry-react-native, which calls this constructor. */ public AndroidProfiler( final @NotNull String tracesFilesDirPath, final int intervalUs, @@ -108,6 +115,29 @@ public AndroidProfiler( final @Nullable LazyEvaluator.Evaluator timeoutExecutorServiceSupplier, final @NotNull ILogger logger) { + this( + tracesFilesDirPath, + intervalUs, + frameMetricsCollector, + timeoutExecutorServiceSupplier, + logger, + SystemEpochClock.getInstance(), + AndroidMonotonicTicker.getInstance()); + } + + /** + * @param ticker must be the {@link io.sentry.SentryOptions#getMonotonicTicker()} that stamps the + * {@link PerformanceCollectionData} passed to {@link #endAndCollect}. + */ + public AndroidProfiler( + final @NotNull String tracesFilesDirPath, + final int intervalUs, + final @NotNull SentryFrameMetricsCollector frameMetricsCollector, + final @Nullable LazyEvaluator.Evaluator + timeoutExecutorServiceSupplier, + final @NotNull ILogger logger, + final @NotNull EpochClock epochClock, + final @NotNull MonotonicTicker ticker) { this.traceFilesDir = new File(Objects.requireNonNull(tracesFilesDirPath, "TracesFilesDirPath is required")); this.intervalUs = intervalUs; @@ -116,6 +146,8 @@ public AndroidProfiler( this.timeoutExecutorServiceSupplier = timeoutExecutorServiceSupplier; this.frameMetricsCollector = Objects.requireNonNull(frameMetricsCollector, "SentryFrameMetricsCollector is required"); + this.epochClock = epochClock; + this.ticker = ticker; } @SuppressLint("NewApi") @@ -155,15 +187,12 @@ public void onFrameMetricCollected( final boolean isSlow, final boolean isFrozen, final float refreshRate) { - // profileStartNanos is calculated through SystemClock.elapsedRealtimeNanos(), - // but frameEndNanos uses System.nanotime(), so we convert it to get the timestamp - // relative to profileStartNanos + // profileStartNanos is read from the ticker, but frameEndNanos uses + // System.nanotime(), so we convert it to get the timestamp relative to + // profileStartNanos final long timestampNanos = new SentryNanotimeDate().nanoTimestamp(); final long frameTimestampRelativeNanos = - frameEndNanos - - System.nanoTime() - + SystemClock.elapsedRealtimeNanos() - - profileStartNanos; + frameEndNanos - System.nanoTime() + ticker.tickNanos() - profileStartNanos; // We don't allow negative relative timestamps. // So we add a check, even if this should never happen. @@ -203,10 +232,11 @@ public void onFrameMetricCollected( e); } - profileStartNanos = SystemClock.elapsedRealtimeNanos(); - final long profileStartMillis = System.currentTimeMillis(); - final @NotNull Date profileStartTimestamp = DateUtils.getDateTime(profileStartMillis); - profileStartEpochNanos = DateUtils.millisToNanos(profileStartMillis); + profileStartNanos = ticker.tickNanos(); + final @NotNull AnchoredClock clock = AnchoredClock.create(epochClock, ticker); + profileClock = clock; + final @NotNull Date profileStartTimestamp = + DateUtils.getDateTime(clock.startTime().epochMillis()); long profileStartCpuMillis = Process.getElapsedCpuTime(); // We don't make any check on the file existence or writeable state, because we don't want to @@ -251,7 +281,7 @@ public void onFrameMetricCollected( } frameMetricsCollector.stopCollection(frameMetricsCollectorId); - long transactionEndNanos = SystemClock.elapsedRealtimeNanos(); + long transactionEndNanos = ticker.tickNanos(); long transactionEndCpuMillis = Process.getElapsedCpuTime(); if (traceFile == null) { @@ -307,7 +337,8 @@ public void close() { private void putPerformanceCollectionDataInMeasurements( final @Nullable List performanceCollectionData) { - if (performanceCollectionData != null) { + final @Nullable AnchoredClock clock = profileClock; + if (performanceCollectionData != null && clock != null) { final @NotNull ArrayDeque memoryUsageMeasurements = new ArrayDeque<>(performanceCollectionData.size()); final @NotNull ArrayDeque nativeMemoryUsageMeasurements = @@ -317,10 +348,8 @@ private void putPerformanceCollectionDataInMeasurements( synchronized (performanceCollectionData) { for (final @NotNull PerformanceCollectionData data : performanceCollectionData) { - // The tick comes from options.getMonotonicTicker(), which on Android is - // SystemClock.elapsedRealtimeNanos(), the clock profileStartNanos was read from. final long relativeStartNs = data.getTickNanos() - profileStartNanos; - final long nanoTimestamp = profileStartEpochNanos + relativeStartNs; + final long nanoTimestamp = clock.at(data.getTickNanos()).epochNanos(); if (data.hasCpuUsagePercentage()) { cpuUsageMeasurements.add( diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidTransactionProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidTransactionProfiler.java index e44ed746a08..8ae4aaf2dd4 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidTransactionProfiler.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidTransactionProfiler.java @@ -19,6 +19,8 @@ import io.sentry.SentryOptions; import io.sentry.android.core.internal.util.CpuInfoUtils; import io.sentry.android.core.internal.util.SentryFrameMetricsCollector; +import io.sentry.time.EpochClock; +import io.sentry.time.MonotonicTicker; import io.sentry.util.AutoClosableReentrantLock; import io.sentry.util.LazyEvaluator; import io.sentry.util.Objects; @@ -36,6 +38,8 @@ final class AndroidTransactionProfiler implements ITransactionProfiler { private final boolean isProfilingEnabled; private final int profilingTracesHz; private final @NotNull LazyEvaluator.Evaluator executorServiceSupplier; + private final @NotNull EpochClock epochClock; + private final @NotNull MonotonicTicker ticker; private final @NotNull BuildInfoProvider buildInfoProvider; private boolean isInitialized = false; private final @NotNull AtomicBoolean isRunning = new AtomicBoolean(false); @@ -66,7 +70,9 @@ public AndroidTransactionProfiler( sentryAndroidOptions.getProfilingTracesDirPath(), sentryAndroidOptions.isProfilingEnabled(), sentryAndroidOptions.getProfilingTracesHz(), - () -> sentryAndroidOptions.getExecutorService()); + () -> sentryAndroidOptions.getExecutorService(), + sentryAndroidOptions.getEpochClock(), + sentryAndroidOptions.getMonotonicTicker()); } public AndroidTransactionProfiler( @@ -77,7 +83,9 @@ public AndroidTransactionProfiler( final @Nullable String profilingTracesDirPath, final boolean isProfilingEnabled, final int profilingTracesHz, - final @NotNull ISentryExecutorService executorService) { + final @NotNull ISentryExecutorService executorService, + final @NotNull EpochClock epochClock, + final @NotNull MonotonicTicker ticker) { this( context, buildInfoProvider, @@ -86,7 +94,9 @@ public AndroidTransactionProfiler( profilingTracesDirPath, isProfilingEnabled, profilingTracesHz, - () -> executorService); + () -> executorService, + epochClock, + ticker); } public AndroidTransactionProfiler( @@ -97,7 +107,9 @@ public AndroidTransactionProfiler( final @Nullable String profilingTracesDirPath, final boolean isProfilingEnabled, final int profilingTracesHz, - final @NotNull LazyEvaluator.Evaluator executorServiceSupplier) { + final @NotNull LazyEvaluator.Evaluator executorServiceSupplier, + final @NotNull EpochClock epochClock, + final @NotNull MonotonicTicker ticker) { this.context = Objects.requireNonNull( ContextUtils.getApplicationContext(context), "The application context is required"); @@ -112,6 +124,8 @@ public AndroidTransactionProfiler( this.executorServiceSupplier = Objects.requireNonNull( executorServiceSupplier, "A supplier for ISentryExecutorService is required."); + this.epochClock = epochClock; + this.ticker = ticker; this.profileStartTimestamp = DateUtils.getCurrentDateTime(); } @@ -146,7 +160,9 @@ private void init() { (int) SECONDS.toMicros(1) / profilingTracesHz, frameMetricsCollector, executorServiceSupplier, - logger); + logger, + epochClock, + ticker); } @Override 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 2ed24da1cfe..df0626cff95 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 @@ -4,11 +4,9 @@ import static io.sentry.IConnectionStatusProvider.ConnectionStatus.DISCONNECTED; import android.os.Build; -import android.os.SystemClock; import androidx.annotation.RequiresApi; import io.sentry.CompositePerformanceCollector; import io.sentry.DataCategory; -import io.sentry.DateUtils; import io.sentry.IContinuousProfiler; import io.sentry.ILogger; import io.sentry.IScopes; @@ -30,6 +28,9 @@ import io.sentry.profilemeasurements.ProfileMeasurementValue; import io.sentry.profiling.ProfileRecordingState; import io.sentry.protocol.SentryId; +import io.sentry.time.AnchoredClock; +import io.sentry.time.EpochClock; +import io.sentry.time.MonotonicTicker; import io.sentry.transport.RateLimiter; import io.sentry.util.AutoClosableReentrantLock; import io.sentry.util.LazyEvaluator; @@ -121,9 +122,12 @@ public PerfettoContinuousProfiler( final @NotNull ILogger logger, final @NotNull SentryFrameMetricsCollector frameMetricsCollector, final @NotNull LazyEvaluator.Evaluator executorServiceSupplier, - final @NotNull Supplier perfettoProfilerFactory) { + final @NotNull Supplier perfettoProfilerFactory, + final @NotNull EpochClock epochClock, + final @NotNull MonotonicTicker ticker) { this.logger = logger; - this.chunkMeasurements = new ChunkMeasurementCollector(frameMetricsCollector); + this.chunkMeasurements = + new ChunkMeasurementCollector(frameMetricsCollector, epochClock, ticker); this.executorServiceSupplier = executorServiceSupplier; this.perfettoProfilerFactory = perfettoProfilerFactory; } @@ -582,17 +586,29 @@ static final class ChunkMeasurementCollector { private final @NotNull ConcurrentLinkedDeque screenFrameRateMeasurements = new ConcurrentLinkedDeque<>(); - // Elapsed realtime when the measurement was started (nanosecond precision). + private final @NotNull EpochClock epochClock; + private final @NotNull MonotonicTicker ticker; + + // The ticker's reading when the measurement was started. // Measurements are placed on the chunk's timeline relative to it. private long profileStartElapsedRealtimeNanos = 0; - // Wall-clock time read alongside profileStartElapsedRealtimeNanos. CPU and memory samples get - // their timestamps by adding their elapsed time to it, so a clock change during the chunk - // cannot move them. - private long profileStartEpochNanos = 0; + // CPU and memory samples get their timestamps from it rather than from the wall clock when + // they were taken, so a clock change during the chunk cannot move them. + private @Nullable AnchoredClock profileClock = null; - ChunkMeasurementCollector(final @NotNull SentryFrameMetricsCollector frameMetricsCollector) { + /** + * @param ticker must be the {@link SentryOptions#getMonotonicTicker()} that stamps the {@link + * PerformanceCollectionData} of the {@link CompositePerformanceCollector} passed to {@link + * #start}. + */ + ChunkMeasurementCollector( + final @NotNull SentryFrameMetricsCollector frameMetricsCollector, + final @NotNull EpochClock epochClock, + final @NotNull MonotonicTicker ticker) { this.frameMetricsCollector = frameMetricsCollector; + this.epochClock = epochClock; + this.ticker = ticker; } void start( @@ -600,8 +616,8 @@ void start( final @NotNull String chunkId) { this.performanceCollector = performanceCollector; this.chunkId = chunkId; - this.profileStartElapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos(); - this.profileStartEpochNanos = DateUtils.millisToNanos(System.currentTimeMillis()); + this.profileStartElapsedRealtimeNanos = ticker.tickNanos(); + this.profileClock = AnchoredClock.create(epochClock, ticker); // Start frame metrics collection (runs on the FrameMetrics HandlerThread) slowFrameRenderMeasurements.clear(); @@ -623,12 +639,9 @@ public void onFrameMetricCollected( final float refreshRate) { final long timestampNanos = new SentryNanotimeDate().nanoTimestamp(); // Convert frameEndNanos (reported by FrameMetricsCollector using System.nanoTime - // / - // SystemClock.uptimeMillis), into the SystemClock.elapsedRealtime to report - // elapsed - // realtime nanos since chunk start + // / SystemClock.uptimeMillis) onto the ticker, to report nanos since chunk start final long frameEndElapsedRealtimeNanos = - frameEndNanos - System.nanoTime() + SystemClock.elapsedRealtimeNanos(); + frameEndNanos - System.nanoTime() + ticker.tickNanos(); final long frameTimestampRelativeNanos = frameEndElapsedRealtimeNanos - profileStartElapsedRealtimeNanos; @@ -675,13 +688,11 @@ Map stop() { // Stop performance collection @Nullable List performanceData = null; - if (performanceCollector != null && chunkId != null) { + final @Nullable AnchoredClock clock = profileClock; + if (performanceCollector != null && chunkId != null && clock != null) { performanceData = performanceCollector.stop(chunkId); addPerformanceDataToMeasurements( - performanceData, - measurements, - profileStartElapsedRealtimeNanos, - profileStartEpochNanos); + performanceData, measurements, profileStartElapsedRealtimeNanos, clock); } performanceCollector = null; chunkId = null; @@ -716,7 +727,7 @@ private static void addPerformanceDataToMeasurements( final @Nullable List performanceData, final @NotNull Map measurements, final long profileStartElapsedRealtimeNanos, - final long profileStartEpochNanos) { + final @NotNull AnchoredClock profileClock) { if (performanceData == null || performanceData.isEmpty()) { return; } @@ -731,10 +742,8 @@ 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) { - // 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; - final long nanoTimestamp = profileStartEpochNanos + relativeStartNs; + final long nanoTimestamp = profileClock.at(data.getTickNanos()).epochNanos(); if (data.hasCpuUsagePercentage()) { cpuUsageMeasurements.addLast( new ProfileMeasurementValue( 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 5829077b3cf..52dbb0f455a 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 @@ -25,6 +25,7 @@ import io.sentry.android.core.performance.AppStartMetrics; import io.sentry.android.core.performance.TimeSpan; import io.sentry.time.Stopwatch; +import io.sentry.time.SystemEpochClock; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -209,7 +210,10 @@ private void createAndStartContinuousProfiler( logger, profilingOptions.getProfilingTracesDirPath(), profilingOptions.getProfilingTracesHz(), - () -> startupExecutorService); + () -> startupExecutorService, + // No options exist yet; these are the clocks SentryAndroidOptions returns. + SystemEpochClock.getInstance(), + AndroidMonotonicTicker.getInstance()); appStartMetrics.setAppStartProfiler(null); appStartMetrics.setAppStartContinuousProfiler(appStartContinuousProfiler); logger.log(SentryLevel.DEBUG, "App start continuous profiling started."); @@ -249,7 +253,10 @@ private void createAndStartTransactionProfiler( profilingOptions.getProfilingTracesDirPath(), profilingOptions.isProfilingEnabled(), profilingOptions.getProfilingTracesHz(), - () -> executorService); + () -> executorService, + // No options exist yet; these are the clocks SentryAndroidOptions returns. + SystemEpochClock.getInstance(), + AndroidMonotonicTicker.getInstance()); appStartMetrics.setAppStartContinuousProfiler(null); appStartMetrics.setAppStartProfiler(appStartProfiler); logger.log(SentryLevel.DEBUG, "App start profiling started."); 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 5a27a303342..f9c7aa8afa5 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 @@ -95,6 +95,8 @@ class AndroidContinuousProfilerTest { options.profilingTracesDirPath, options.profilingTracesHz, { options.executorService }, + options.epochClock, + options.monotonicTicker, ) } } 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 5c4f1ee6d59..4e21ae79338 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 @@ -9,15 +9,23 @@ import io.sentry.ISentryExecutorService import io.sentry.PerformanceCollectionData import io.sentry.SentryExecutorService import io.sentry.SentryLevel +import io.sentry.android.core.internal.time.AndroidMonotonicTicker import io.sentry.android.core.internal.util.SentryFrameMetricsCollector import io.sentry.profilemeasurements.ProfileMeasurement import io.sentry.test.getCtor import io.sentry.test.getProperty +import io.sentry.time.EpochClock +import io.sentry.time.MonotonicTicker +import io.sentry.time.SystemEpochClock +import io.sentry.time.TestMonotonicTicker +import io.sentry.time.Timestamp import io.sentry.util.LazyEvaluator import java.io.File import java.util.concurrent.Callable import java.util.concurrent.Future import java.util.concurrent.FutureTask +import java.util.concurrent.TimeUnit.HOURS +import java.util.concurrent.TimeUnit.SECONDS import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.assertContentEquals @@ -95,13 +103,19 @@ class AndroidProfilerTest { val frameMetricsCollector: SentryFrameMetricsCollector = mock() - fun getSut(interval: Int = 1): AndroidProfiler = + fun getSut( + interval: Int = 1, + epochClock: EpochClock = SystemEpochClock.getInstance(), + ticker: MonotonicTicker = AndroidMonotonicTicker.getInstance(), + ): AndroidProfiler = AndroidProfiler( options.profilingTracesDirPath!!, interval, frameMetricsCollector, { options.executorService }, options.logger, + epochClock, + ticker, ) } @@ -305,14 +319,17 @@ class AndroidProfilerTest { } @Test - fun `performance measurements are timed by their tick from the profile start`() { - val profiler = fixture.getSut() - val start = profiler.start()!! - val startEpochNanos = DateUtils.millisToNanos(start.startTimestamp.time) + fun `performance measurements keep their place when the clock changes during the profile`() { + val ticker = TestMonotonicTicker(SECONDS.toNanos(5_000)) + var wallNanos = SECONDS.toNanos(1_700_000_000) + val profiler = + fixture.getSut(epochClock = { Timestamp.ofEpochNanos(wallNanos) }, ticker = ticker) + val startTick = profiler.start()!!.startNanos + wallNanos -= HOURS.toNanos(1) val samples = listOf( - PerformanceCollectionData(start.startNanos + 1_000_000).apply { usedHeapMemory = 2 }, - PerformanceCollectionData(start.startNanos + 2_000_000).apply { usedHeapMemory = 3 }, + PerformanceCollectionData(startTick + SECONDS.toNanos(1)).apply { usedHeapMemory = 2 }, + PerformanceCollectionData(startTick + SECONDS.toNanos(3)).apply { usedHeapMemory = 3 }, ) val values = @@ -321,11 +338,11 @@ class AndroidProfilerTest { .measurementsMap[ProfileMeasurement.ID_MEMORY_FOOTPRINT]!! .values - assertContentEquals(listOf("1000000", "2000000"), values.map { it.relativeStartNs }) + assertContentEquals(listOf("1000000000", "3000000000"), values.map { it.relativeStartNs }) assertContentEquals( listOf( - DateUtils.nanosToSeconds(startEpochNanos + 1_000_000), - DateUtils.nanosToSeconds(startEpochNanos + 2_000_000), + DateUtils.nanosToSeconds(SECONDS.toNanos(1_700_000_001)), + DateUtils.nanosToSeconds(SECONDS.toNanos(1_700_000_003)), ), values.map { it.timestamp }, ) 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 fbe1cc23e80..ef68cde73a2 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 @@ -3,10 +3,15 @@ package io.sentry.android.core import io.sentry.CompositePerformanceCollector import io.sentry.DateUtils import io.sentry.PerformanceCollectionData +import io.sentry.android.core.internal.time.AndroidMonotonicTicker import io.sentry.android.core.internal.util.SentryFrameMetricsCollector import io.sentry.profilemeasurements.ProfileMeasurement -import io.sentry.test.getProperty +import io.sentry.time.SystemEpochClock +import io.sentry.time.TestMonotonicTicker +import io.sentry.time.Timestamp import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeUnit.HOURS +import java.util.concurrent.TimeUnit.SECONDS import kotlin.test.Test import kotlin.test.assertEquals import org.mockito.kotlin.any @@ -26,7 +31,7 @@ class ChunkMeasurementCollectorTest { fun `each start-stop cycle returns its own independent measurements`() { val frameMetricsCollector: SentryFrameMetricsCollector = mock() val performanceCollector: CompositePerformanceCollector = mock() - val collector = PerfettoContinuousProfiler.ChunkMeasurementCollector(frameMetricsCollector) + val collector = systemClockCollector(frameMetricsCollector) val listenerCaptor = argumentCaptor() // Return distinct performance data for each stop() call. @@ -81,7 +86,7 @@ class ChunkMeasurementCollectorTest { @Test fun `frames ending before the chunk started are dropped`() { val frameMetricsCollector: SentryFrameMetricsCollector = mock() - val collector = PerfettoContinuousProfiler.ChunkMeasurementCollector(frameMetricsCollector) + val collector = systemClockCollector(frameMetricsCollector) val listenerCaptor = argumentCaptor() collector.start(null, "chunk-1") @@ -108,32 +113,50 @@ class ChunkMeasurementCollectorTest { } @Test - fun `performance samples are timed by their tick from the chunk start`() { + fun `performance samples keep their place when the clock changes during the chunk`() { + val ticker = TestMonotonicTicker(SECONDS.toNanos(5_000)) + var wallNanos = SECONDS.toNanos(1_700_000_000) val performanceCollector: CompositePerformanceCollector = mock() - val collector = PerfettoContinuousProfiler.ChunkMeasurementCollector(mock()) + val collector = + PerfettoContinuousProfiler.ChunkMeasurementCollector( + mock(), + { Timestamp.ofEpochNanos(wallNanos) }, + ticker, + ) collector.start(performanceCollector, "chunk") - val chunkStartTick = collector.getProperty("profileStartElapsedRealtimeNanos") - val chunkStartEpochNanos = collector.getProperty("profileStartEpochNanos") + val chunkStartTick = ticker.tickNanos() + wallNanos -= HOURS.toNanos(1) whenever(performanceCollector.stop(any())) .thenReturn( listOf( - PerformanceCollectionData(chunkStartTick + 1_000_000).apply { usedHeapMemory = 1 }, - PerformanceCollectionData(chunkStartTick + 2_000_000).apply { usedHeapMemory = 2 }, + PerformanceCollectionData(chunkStartTick + SECONDS.toNanos(1)).apply { + usedHeapMemory = 1 + }, + PerformanceCollectionData(chunkStartTick + SECONDS.toNanos(3)).apply { + usedHeapMemory = 2 + }, ), ) val values = collector.stop()[ProfileMeasurement.ID_MEMORY_FOOTPRINT]!!.values - assertEquals(listOf("1000000", "2000000"), values.map { it.relativeStartNs }) + assertEquals(listOf("1000000000", "3000000000"), values.map { it.relativeStartNs }) assertEquals( listOf( - DateUtils.nanosToSeconds(chunkStartEpochNanos + 1_000_000), - DateUtils.nanosToSeconds(chunkStartEpochNanos + 2_000_000), + DateUtils.nanosToSeconds(SECONDS.toNanos(1_700_000_001)), + DateUtils.nanosToSeconds(SECONDS.toNanos(1_700_000_003)), ), values.map { it.timestamp }, ) } + private fun systemClockCollector(frameMetricsCollector: SentryFrameMetricsCollector) = + PerfettoContinuousProfiler.ChunkMeasurementCollector( + frameMetricsCollector, + SystemEpochClock.getInstance(), + AndroidMonotonicTicker.getInstance(), + ) + /** * 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. diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoContinuousProfilerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoContinuousProfilerTest.kt index cc0d63bb6a1..b8796513536 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoContinuousProfilerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoContinuousProfilerTest.kt @@ -90,6 +90,8 @@ class PerfettoContinuousProfilerTest { frameMetricsCollector, { options.executorService }, { mockPerfettoProfiler }, + options.epochClock, + options.monotonicTicker, ) } } diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 7c13f683d21..e4e4202a8db 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -7723,6 +7723,7 @@ public final class io/sentry/rrweb/RRWebVideoEvent$JsonKeys { } public final class io/sentry/time/AnchoredClock { + public fun at (J)Lio/sentry/time/Timestamp; public static fun create (Lio/sentry/time/EpochClock;Lio/sentry/time/MonotonicTicker;)Lio/sentry/time/AnchoredClock; public fun now ()Lio/sentry/time/Timestamp; public fun startTime ()Lio/sentry/time/Timestamp; diff --git a/sentry/src/main/java/io/sentry/time/AnchoredClock.java b/sentry/src/main/java/io/sentry/time/AnchoredClock.java index 3e0718455a8..e412eb37e7a 100644 --- a/sentry/src/main/java/io/sentry/time/AnchoredClock.java +++ b/sentry/src/main/java/io/sentry/time/AnchoredClock.java @@ -51,7 +51,11 @@ private AnchoredClock( return at(ticker.tickNanos()); } - private @NotNull Timestamp at(final long tickNanos) { + /** + * The instant of a tick read earlier, such as one recorded with a sample on another thread. The + * tick must come from the ticker this clock was created with. + */ + public @NotNull Timestamp at(final long tickNanos) { return Timestamp.ofEpochNanos(epochNanos + (tickNanos - anchorTick)); } } diff --git a/sentry/src/test/java/io/sentry/time/AnchoredClockTest.kt b/sentry/src/test/java/io/sentry/time/AnchoredClockTest.kt index 000858ad90a..cf45818a395 100644 --- a/sentry/src/test/java/io/sentry/time/AnchoredClockTest.kt +++ b/sentry/src/test/java/io/sentry/time/AnchoredClockTest.kt @@ -23,6 +23,17 @@ class AnchoredClockTest { .isEqualTo(SECONDS.toNanos(1_700_000_000) + MILLISECONDS.toNanos(120)) } + @Test + fun `at projects a tick read earlier, across a wall-clock step`() { + ticker.advance(120, MILLISECONDS) + val tick = ticker.tickNanos() + ticker.advance(5, SECONDS) + epoch.epochNanos -= SECONDS.toNanos(30) + + assertThat(anchored.at(tick).epochNanos()) + .isEqualTo(SECONDS.toNanos(1_700_000_000) + MILLISECONDS.toNanos(120)) + } + @Test fun `a wall-clock step does not move a projected instant`() { ticker.advance(120, MILLISECONDS) From 83ab3c914836b4917add69abc1e09dac7bcc34ba Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Fri, 4 Dec 2026 16:08:53 +0100 Subject: [PATCH 6/6] docs(profiling): Say why app start profiling passes clock singletons Co-Authored-By: Claude Opus 5.5 --- .../io/sentry/android/core/SentryPerformanceProvider.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 52dbb0f455a..333ed420c96 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 @@ -211,7 +211,8 @@ private void createAndStartContinuousProfiler( profilingOptions.getProfilingTracesDirPath(), profilingOptions.getProfilingTracesHz(), () -> startupExecutorService, - // No options exist yet; these are the clocks SentryAndroidOptions returns. + // This ContentProvider runs before the SDK is initialized, so there are no options yet. + // These are the clocks SentryAndroidOptions returns. SystemEpochClock.getInstance(), AndroidMonotonicTicker.getInstance()); appStartMetrics.setAppStartProfiler(null); @@ -254,7 +255,8 @@ private void createAndStartTransactionProfiler( profilingOptions.isProfilingEnabled(), profilingOptions.getProfilingTracesHz(), () -> executorService, - // No options exist yet; these are the clocks SentryAndroidOptions returns. + // This ContentProvider runs before the SDK is initialized, so there are no options yet. + // These are the clocks SentryAndroidOptions returns. SystemEpochClock.getInstance(), AndroidMonotonicTicker.getInstance()); appStartMetrics.setAppStartContinuousProfiler(null);