Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -303,13 +302,6 @@ public void close() {
private void putPerformanceCollectionDataInMeasurements(
final @Nullable List<PerformanceCollectionData> 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<ProfileMeasurementValue> memoryUsageMeasurements =
new ArrayDeque<>(performanceCollectionData.size());
Expand All @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -673,14 +672,8 @@ Map<String, ProfileMeasurement> stop() {
@Nullable List<PerformanceCollectionData> 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;
Expand Down Expand Up @@ -714,8 +707,6 @@ private void addFrameDataToMeasurements(
private static void addPerformanceDataToMeasurements(
final @Nullable List<PerformanceCollectionData> performanceData,
final @NotNull Map<String, ProfileMeasurement> measurements,
final long wallClockNowNanos,
final long elapsedRealtimeNowNanos,
final long profileStartElapsedRealtimeNanos) {
if (performanceData == null || performanceData.isEmpty()) {
return;
Expand All @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ class AndroidContinuousProfilerTest {
@Test
fun `profiler sends chunk with measurements`() {
val performanceCollector = mock<CompositePerformanceCollector>()
val collectionData = PerformanceCollectionData(10)
val collectionData = PerformanceCollectionData(10, 10)

collectionData.usedHeapMemory = 2
collectionData.usedNativeMemory = 3
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -276,13 +277,13 @@ class AndroidProfilerTest {
fun `profiler includes performance measurements when passed on end`() {
val profiler = fixture.getSut()
val performanceCollectionData = ArrayList<PerformanceCollectionData>()
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)
Expand All @@ -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<Long>("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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -472,13 +472,13 @@ class AndroidTransactionProfilerTest {
fun `profiler includes performance measurements when passed on transaction finish`() {
val profiler = fixture.getSut(context)
val performanceCollectionData = ArrayList<PerformanceCollectionData>()
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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Long>("profileStartElapsedRealtimeNanos")
// Wall timestamps that disagree with the ticks, as after a clock step during the chunk.
whenever(performanceCollector.stop(any<String>()))
.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.
Expand All @@ -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 }
Expand Down
3 changes: 2 additions & 1 deletion sentry/api/sentry.api
Original file line number Diff line number Diff line change
Expand Up @@ -2215,9 +2215,10 @@ public final class io/sentry/OutboxSender : io/sentry/IEnvelopeSender {
}

public final class io/sentry/PerformanceCollectionData {
public fun <init> (J)V
public fun <init> (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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
14 changes: 13 additions & 1 deletion sentry/src/main/java/io/sentry/PerformanceCollectionData.java
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -69,4 +77,8 @@ public boolean hasUsedNativeMemory() {
public long getNanoTimestamp() {
return nanoTimestamp;
}

public long getTickNanos() {
return tickNanos;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading