Skip to content

Commit 934244e

Browse files
authored
fix(android): Prevent Relay from rejecting single-sample ANR profiles (#5872)
Relay currently rejects ANR profiles with a single sample, even though they're still useful to customers. (Relay's policy was developed with continuous profiles in mind, before ANR profiles were a thing.) Commit updates our StackTraceConverter to add a second, synthetic sample whenever an ANR profile would otherwise only contain one. The synthetic sample duplicates the original, save for a minor offset to its timestamp (to avoid misleading the user about the ANRs cause or duration).
1 parent 5cb2c36 commit 934244e

7 files changed

Lines changed: 132 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
### Fixes
66

7+
- Preserve single-sample ANR profile chunks so profiles remain available on ANR events ([#5872](https://github.com/getsentry/sentry-java/pull/5872))
78
- Prevent inflated cold app start when the OS spawns the process in the background (e.g. FCM push) on API 35+ ([#5841](https://github.com/getsentry/sentry-java/pull/5841))
89
- Avoid a CPU busy-loop when recording discarded log or metric envelopes under rate limiting ([#5835](https://github.com/getsentry/sentry-java/pull/5835))
910
- `ClientReportRecorder` now reads the item count from the envelope item header instead of deserializing the payload, which under sustained rate limiting could pin CPU cores while repeatedly throwing exceptions

‎sentry-android-core/src/main/java/io/sentry/android/core/anr/StackTraceConverter.java‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,14 @@ public final class StackTraceConverter {
3333
private static final String MAIN_THREAD_ID = "0";
3434
private static final String MAIN_THREAD_NAME = "main";
3535

36+
/**
37+
* Timestamp offset used with synthetic ANR profile samples. (Currently 33 ms.)
38+
*
39+
* <p>Places the synthetic sample halfway to the next ANR polling tick.
40+
*/
41+
private static final double SYNTHETIC_SAMPLE_OFFSET_SECONDS =
42+
(AnrProfilingIntegration.POLLING_INTERVAL_MS / 2.0d) / 1000.0d;
43+
3644
/**
3745
* Converts a list of {@link AnrStackTrace} objects to a {@link SentryProfile}.
3846
*
@@ -80,6 +88,15 @@ public static SentryProfile convert(final @NotNull AnrProfile anrProfile) {
8088
profile.getSamples().add(sample);
8189
}
8290

91+
// Relay will reject ANR profiles with only one sample, even though they're still useful.
92+
// (Relay's policy was defined with continuous profiles in mind, before ANR profiles were a
93+
// thing.) If we only have one sample, synthesize another that only differs in its timestamp.
94+
if (profile.getSamples().size() == 1) {
95+
final @NotNull SentrySample originalSample = profile.getSamples().get(0);
96+
final @NotNull SentrySample syntheticSample = createSyntheticSample(originalSample);
97+
profile.getSamples().add(syntheticSample);
98+
}
99+
83100
profile.setFrames(frames);
84101
profile.setStacks(stacks);
85102

@@ -147,4 +164,18 @@ private static SentryStackFrame createSentryStackFrame(@NotNull StackTraceElemen
147164
}
148165
return frame;
149166
}
167+
168+
/**
169+
* Creates a {@link SentrySample} identical to {@code originalSample}, save that its timestamp is
170+
* advanced by {@link #SYNTHETIC_SAMPLE_OFFSET_SECONDS}.
171+
*
172+
* <p>Lets us produce a plausible synthetic sample without misleading the user about the ANR's
173+
* actual duration or cause.
174+
*/
175+
@NotNull
176+
private static SentrySample createSyntheticSample(@NotNull SentrySample originalSample) {
177+
final @NotNull SentrySample syntheticSample = new SentrySample(originalSample);
178+
syntheticSample.setTimestamp(originalSample.getTimestamp() + SYNTHETIC_SAMPLE_OFFSET_SECONDS);
179+
return syntheticSample;
180+
}
150181
}

‎sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitInfoEventProcessorTest.kt‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1012,9 +1012,15 @@ class ApplicationExitInfoEventProcessorTest {
10121012
mockedSentry.`when`<Any> { Sentry.getCurrentScopes() }.thenReturn(scopes)
10131013

10141014
val processed = processor.process(SentryEvent(), hint)
1015+
val chunkCaptor = argumentCaptor<ProfileChunk>()
1016+
verify(scopes).captureProfileChunk(chunkCaptor.capture())
1017+
val sentryProfile = chunkCaptor.firstValue.sentryProfile
10151018

10161019
assertNotNull(processed?.contexts?.profile)
10171020
assertNotNull(processed.contexts.profile?.profilerId)
1021+
assertNotNull(sentryProfile)
1022+
// Two samples are present b/c the converter adds a synthetic one to keep Relay happy.
1023+
assertEquals(2, sentryProfile.samples.size)
10181024
}
10191025
}
10201026

‎sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrStackTraceConverterTest.kt‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ class AnrStackTraceConverterTest {
1919
val profile = StackTraceConverter.convert(AnrProfile(anrStackTraces))
2020

2121
Assert.assertNotNull(profile)
22-
Assert.assertEquals(1, profile.samples.size)
22+
// Two samples are present b/c the converter adds a synthetic one to keep Relay happy.
23+
Assert.assertEquals(2, profile.samples.size)
2324
Assert.assertEquals(2, profile.frames.size)
2425
Assert.assertEquals(1, profile.stacks.size)
2526

@@ -46,6 +47,57 @@ class AnrStackTraceConverterTest {
4647
Assert.assertEquals(1.0, sample.timestamp, 0.001) // 1000ms = 1s
4748
}
4849

50+
@Test
51+
fun testAddSyntheticSampleIfOnlyOneSamplePresent() {
52+
val elements = arrayOf(StackTraceElement("com.example.MyClass", "method1", "MyClass.java", 42))
53+
54+
val anrStackTraces: MutableList<AnrStackTrace?> = ArrayList()
55+
anrStackTraces.add(AnrStackTrace(1000, elements))
56+
57+
val profile = StackTraceConverter.convert(AnrProfile(anrStackTraces))
58+
59+
val originalSample = profile.samples[0]
60+
val syntheticSample = profile.samples[1]
61+
val expectedOffsetSeconds = AnrProfilingIntegration.POLLING_INTERVAL_MS / 2.0 / 1000.0
62+
63+
Assert.assertEquals(
64+
originalSample.timestamp + expectedOffsetSeconds,
65+
syntheticSample.timestamp,
66+
0.001,
67+
)
68+
69+
Assert.assertTrue(profile.stacks[syntheticSample.stackId].isNotEmpty())
70+
Assert.assertEquals(2, profile.samples.size)
71+
Assert.assertEquals(1, profile.stacks.size)
72+
Assert.assertEquals(1, profile.frames.size)
73+
}
74+
75+
@Test
76+
fun testDoNotAddSyntheticSampleIfMultipleSamplesPresent() {
77+
val elements = arrayOf(StackTraceElement("com.example.MyClass", "method1", "MyClass.java", 42))
78+
79+
val anrStackTraces: MutableList<AnrStackTrace?> = ArrayList()
80+
anrStackTraces.add(AnrStackTrace(1000, elements))
81+
anrStackTraces.add(AnrStackTrace(2000, elements))
82+
83+
val profile = StackTraceConverter.convert(AnrProfile(anrStackTraces))
84+
85+
Assert.assertEquals(2, profile.samples.size)
86+
Assert.assertEquals(1.0, profile.samples[0].timestamp, 0.001)
87+
Assert.assertEquals(2.0, profile.samples[1].timestamp, 0.001)
88+
Assert.assertEquals(1, profile.stacks.size)
89+
Assert.assertEquals(1, profile.frames.size)
90+
}
91+
92+
@Test
93+
fun testDoNotAddSyntheticSampleIfNoSamplesPresent() {
94+
val profile = StackTraceConverter.convert(AnrProfile(ArrayList()))
95+
96+
Assert.assertEquals(0, profile.samples.size)
97+
Assert.assertEquals(0, profile.stacks.size)
98+
Assert.assertEquals(0, profile.frames.size)
99+
}
100+
49101
@Test
50102
fun testFrameDeduplication() {
51103
// Create two stack traces with duplicate frames

‎sentry/api/sentry.api‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7066,6 +7066,7 @@ public final class io/sentry/protocol/profiling/SentryProfile$JsonKeys {
70667066

70677067
public final class io/sentry/protocol/profiling/SentrySample : io/sentry/JsonSerializable, io/sentry/JsonUnknown {
70687068
public fun <init> ()V
7069+
public fun <init> (Lio/sentry/protocol/profiling/SentrySample;)V
70697070
public fun getStackId ()I
70707071
public fun getThreadId ()Ljava/lang/String;
70717072
public fun getTimestamp ()D

‎sentry/src/main/java/io/sentry/protocol/profiling/SentrySample.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import io.sentry.JsonUnknown;
99
import io.sentry.ObjectReader;
1010
import io.sentry.ObjectWriter;
11+
import io.sentry.util.CollectionUtils;
1112
import io.sentry.vendor.gson.stream.JsonToken;
1213
import java.io.IOException;
1314
import java.util.HashMap;
@@ -27,6 +28,15 @@ public final class SentrySample implements JsonUnknown, JsonSerializable {
2728

2829
private @Nullable Map<String, Object> unknown;
2930

31+
public SentrySample() {}
32+
33+
public SentrySample(final @NotNull SentrySample sample) {
34+
this.timestamp = sample.timestamp;
35+
this.stackId = sample.stackId;
36+
this.threadId = sample.threadId;
37+
this.unknown = CollectionUtils.newConcurrentHashMap(sample.unknown);
38+
}
39+
3040
public double getTimestamp() {
3141
return timestamp;
3242
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package io.sentry.protocol.profiling
2+
3+
import com.google.common.truth.Truth.assertThat
4+
import org.junit.Test
5+
6+
class SentrySampleTest {
7+
8+
@Test
9+
fun `copying sample keeps values and copies unknown`() {
10+
val unknown = mutableMapOf<String, Any>("key" to "value")
11+
val original =
12+
SentrySample().apply {
13+
timestamp = 1.23
14+
stackId = 4
15+
threadId = "main"
16+
setUnknown(unknown)
17+
}
18+
19+
val copy = SentrySample(original)
20+
21+
assertThat(copy.timestamp).isEqualTo(original.timestamp)
22+
assertThat(copy.stackId).isEqualTo(original.stackId)
23+
assertThat(copy.threadId).isEqualTo(original.threadId)
24+
assertThat(copy.unknown).containsExactlyEntriesIn(original.unknown)
25+
assertThat(copy.unknown).isNotSameInstanceAs(original.unknown)
26+
27+
unknown["key"] = "changed"
28+
assertThat(copy.unknown).containsEntry("key", "value")
29+
}
30+
}

0 commit comments

Comments
 (0)