diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/AndroidManifest.xml b/sentry-android-integration-tests/sentry-samples-android/src/main/AndroidManifest.xml
index 3a8c263e0f4..a74c75f5519 100644
--- a/sentry-android-integration-tests/sentry-samples-android/src/main/AndroidManifest.xml
+++ b/sentry-android-integration-tests/sentry-samples-android/src/main/AndroidManifest.xml
@@ -123,9 +123,10 @@
android:exported="false"
android:theme="@style/AppTheme.Main" />
+
diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt
index 807fedad09a..107888d6cad 100644
--- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt
+++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt
@@ -99,10 +99,14 @@ class Nav3Activity : ComponentActivity() {
NavigationTransactionHistory.install()
+ // A recreated Activity doesn't repeat the requested run.
+ val performanceLaunch = if (savedInstanceState == null) intent.nav3PerformanceLaunch() else null
+
setContent {
Nav3SampleTheme {
Nav3SampleApp(
performanceState = performanceState,
+ performanceLaunch = performanceLaunch,
configuration = configuration,
transactions = NavigationTransactionHistory.transactions,
showActivityUiLoadTransactionDelayMessage = showActivityUiLoadTransactionDelayMessage,
@@ -161,6 +165,7 @@ class Nav3Activity : ComponentActivity() {
@Composable
private fun Nav3SampleApp(
performanceState: Nav3PerformanceState,
+ performanceLaunch: Nav3PerformanceLaunch?,
configuration: NavigationSampleConfig,
transactions: List,
showActivityUiLoadTransactionDelayMessage: Boolean,
@@ -288,6 +293,15 @@ private fun Nav3SampleApp(
controller = customTransactionController,
)
+ // Compose runs effects in composition order, so this and the effect after SentryNavEffect
+ // bracket the SDK's synchronous back stack work, mapper calls included.
+ if (isPerformanceScenario) {
+ DisposableEffect(sentryBackStack.toList(), sentryNavOptions) {
+ performanceState.beginSentryNavEffectTiming()
+ onDispose {}
+ }
+ }
+
SentryNavEffect(
backStack = sentryBackStack,
backStackEntryMapper = backStackEntryMapper,
@@ -336,6 +350,47 @@ private fun Nav3SampleApp(
}
}
+ val selectScenario: (Nav3Scenario) -> Unit = { scenario ->
+ // Selecting a scenario resets its back stack and counters, so stop any run first.
+ if (performanceState.performanceRunActive) {
+ performanceState.cancelPerformanceRun()
+ }
+ selectedScenario = scenario
+ performanceState.stopAutomaticWork()
+ backStack.openScenario(scenario)
+ if (scenario == Nav3Scenario.PERFORMANCE) {
+ performanceState.resetCounters()
+ performanceState.markNavigationMutation()
+ }
+ }
+
+ if (performanceLaunch != null) {
+ LaunchedEffect(Unit) {
+ selectScenario(Nav3Scenario.PERFORMANCE)
+ awaitNav3PerformanceFrames()
+ val preset = performanceLaunch.preset
+ if (
+ preset != null &&
+ !prepareNav3PerformancePreset(
+ preset = preset,
+ state = performanceState,
+ backStack = backStack,
+ onMaxCapturedBackStackEntriesChange = { maxCapturedBackStackEntries = it },
+ )
+ ) {
+ // Leaving Performance cancels the preset. Don't start the run on another scenario.
+ return@LaunchedEffect
+ }
+ performanceLaunch.integrationMode?.let { mode ->
+ performanceState.updateIntegrationMode(mode)
+ }
+ performanceLaunch.run?.let { run ->
+ awaitNav3PerformanceFrames()
+ runNav3Performance(run = run, state = performanceState, backStack = backStack)
+ }
+ }
+ }
+
LaunchedEffect(selectedScenario, sentryBackStack.lastOrNull()) {
tagCurrentNavigationSampleScenario(selectedScenario.label)
}
@@ -373,18 +428,7 @@ private fun Nav3SampleApp(
maxCapturedBackStackEntries = maxCapturedBackStackEntries,
onTransactionHistoryClick = onShowTransactionHistorySheet,
onRouteWorkSettingsClick = onShowRouteWorkSettings,
- onScenarioSelected = { scenario ->
- if (scenario != Nav3Scenario.PERFORMANCE && performanceState.performanceRunActive) {
- performanceState.cancelPerformanceRun()
- }
- selectedScenario = scenario
- performanceState.stopAutomaticWork()
- backStack.openScenario(scenario)
- if (scenario == Nav3Scenario.PERFORMANCE) {
- performanceState.resetCounters()
- performanceState.markNavigationMutation()
- }
- },
+ onScenarioSelected = selectScenario,
)
},
bottomBar = {
diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Performance.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Performance.kt
index 62c181b5b42..1f6929be9fc 100644
--- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Performance.kt
+++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Performance.kt
@@ -12,7 +12,10 @@ import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
+import io.sentry.Sentry
import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
@Composable
internal fun Nav3PerformanceRoute(
@@ -84,12 +87,13 @@ internal fun Nav3PerformanceRoute(
)
}
+/** Returns false if the preset was cancelled before it finished warming up. */
internal suspend fun prepareNav3PerformancePreset(
preset: Nav3PerformancePreset,
state: Nav3PerformanceState,
backStack: SnapshotStateList,
onMaxCapturedBackStackEntriesChange: (Int) -> Unit,
-) {
+): Boolean {
state.startPerformanceRun("Preparing ${preset.label}")
try {
state.stackDepth = preset.stackDepth
@@ -107,11 +111,12 @@ internal suspend fun prepareNav3PerformancePreset(
backStack = backStack,
)
) {
- return
+ return false
}
state.resetCounters()
state.suppressNextDestinationChange()
state.cancelPerformanceRun(status = "Ready: ${preset.label}")
+ return true
} catch (e: CancellationException) {
state.cancelPerformanceRun()
throw e
@@ -163,6 +168,10 @@ internal suspend fun runNav3Performance(
) {
return
}
+ state.stopCollectingMeasurements()
+ if (!flushSentryAndMeasureHeap(state)) {
+ return
+ }
state.finishPerformanceRun()
} catch (e: CancellationException) {
state.cancelPerformanceRun()
@@ -222,6 +231,10 @@ private suspend fun runNav3PerformanceAbComparison(
return
}
state.stopCollectingMeasurements()
+ // Also gives the next side an empty send queue.
+ if (!flushSentryAndMeasureHeap(state)) {
+ return
+ }
results += state.performanceSummary(mode.label)
}
} finally {
@@ -274,10 +287,22 @@ private fun performNav3PerformanceIteration(
}
}
+/** Sends what the run queued, then reads the heap again. Returns false if the run was cancelled. */
+private suspend fun flushSentryAndMeasureHeap(state: Nav3PerformanceState): Boolean {
+ state.updatePerformanceStatus("Sending queued events")
+ withContext(Dispatchers.IO) { Sentry.flush(PERFORMANCE_FLUSH_TIMEOUT_MILLIS) }
+ if (!state.performanceRunActive) {
+ return false
+ }
+ state.recordLiveHeapAfterFlush()
+ return true
+}
+
internal suspend fun awaitNav3PerformanceFrames() {
withFrameNanos {}
withFrameNanos {}
}
private const val PERFORMANCE_WARM_UP_ITERATIONS = 5
-private const val PERFORMANCE_MEASURED_ITERATIONS = 20
+private const val PERFORMANCE_FLUSH_TIMEOUT_MILLIS = 15_000L
+internal const val PERFORMANCE_MEASURED_ITERATIONS = 100
diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt
index e923948060f..7795e822fb4 100644
--- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt
+++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt
@@ -37,7 +37,12 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
+import io.sentry.DataCategory
+import io.sentry.Sentry
+import io.sentry.SentryOptions
+import io.sentry.clientreport.DiscardReason
import java.util.Locale
+import java.util.concurrent.atomic.AtomicLong
import kotlin.math.ceil
import kotlinx.coroutines.delay
@@ -99,6 +104,13 @@ internal class Nav3PerformanceState(
private val mutationToCompositionDurations = Nav3PerformanceDurations()
private val mutationToFirstDrawDurations = Nav3PerformanceDurations()
+ private val sentryNavEffectDurations = Nav3PerformanceDurations()
+ private var sentryNavEffectStartedAtNanos: Long? = null
+ private var liveHeapBeforeRunBytes: Long? = null
+ private var liveHeapAfterRunBytes: Long? = null
+ private var liveHeapAfterFlushBytes: Long? = null
+ private var queueOverflowDropsAtRunStart: Long? = null
+ private var queueOverflowDropsDuringRun: Long? = null
private var pendingOperation: PendingNav3PerformanceOperation? = null
private var pendingAbPhase: PendingNav3PerformanceTrace? = null
private var pendingMeasuredPhase: PendingNav3PerformanceTrace? = null
@@ -125,6 +137,13 @@ internal class Nav3PerformanceState(
pendingProcessedNavigationWork = false
mutationToCompositionDurations.clear()
mutationToFirstDrawDurations.clear()
+ sentryNavEffectDurations.clear()
+ sentryNavEffectStartedAtNanos = null
+ liveHeapBeforeRunBytes = null
+ liveHeapAfterRunBytes = null
+ liveHeapAfterFlushBytes = null
+ queueOverflowDropsAtRunStart = null
+ queueOverflowDropsDuringRun = null
comparisonResult = null
displayRevision++
}
@@ -238,10 +257,17 @@ internal class Nav3PerformanceState(
pendingOperation = null
}
+ fun beginSentryNavEffectTiming() {
+ sentryNavEffectStartedAtNanos = System.nanoTime()
+ }
+
fun recordSentryNavEffect(
processedCall: Boolean,
resolvedEntryCount: Int,
) {
+ val startedAtNanos = sentryNavEffectStartedAtNanos
+ sentryNavEffectStartedAtNanos = null
+ val durationNanos = startedAtNanos?.let { System.nanoTime() - it }
if (discardNextSentryNavEffectMeasurement) {
discardNextSentryNavEffectMeasurement = false
pendingProcessedNavigationWork = false
@@ -256,6 +282,7 @@ internal class Nav3PerformanceState(
if (shouldCountAsProcessed) {
sentryNavEffectProcessedCalls++
capturedEntriesResolved += resolvedEntryCount
+ durationNanos?.let { sentryNavEffectDurations.add(it) }
}
pendingProcessedNavigationWork = false
}
@@ -276,6 +303,9 @@ internal class Nav3PerformanceState(
finishMeasuredPhase()
resetCounters()
collectMeasurements = true
+ liveHeapBeforeRunBytes = measureLiveHeapBytes()
+ Nav3QueueOverflowDrops.installIfNeeded(Sentry.getCurrentScopes().options)
+ queueOverflowDropsAtRunStart = Nav3QueueOverflowDrops.count
val cookie = ++nextTraceCookie
pendingMeasuredPhase = PendingNav3PerformanceTrace(MEASURED_SECTION, cookie)
beginAsyncTraceSection(MEASURED_SECTION, cookie)
@@ -315,7 +345,11 @@ internal class Nav3PerformanceState(
}
fun performanceSummary(label: String): String =
- "$label: first draw ${mutationToFirstDrawDurations.compactSummary()}"
+ "$label: first draw ${mutationToFirstDrawDurations.compactSummary()}, " +
+ "SentryNavEffect ${sentryNavEffectDurations.compactSummary()}, " +
+ "live heap ${formatBytes(liveHeapBeforeRunBytes)} -> ${formatBytes(liveHeapAfterRunBytes)} " +
+ "(${formatBytes(liveHeapAfterFlushBytes)} after flush), " +
+ "transactions dropped for queue overflow ${queueOverflowDropsDuringRun ?: "n/a"}"
fun diagnosticsSummary(currentRoute: String, backStack: String): String = buildString {
appendLine("status=$performanceStatus")
@@ -331,10 +365,15 @@ internal class Nav3PerformanceState(
appendLine("arguments_extractor_calls=$argumentsExtractorCalls")
appendLine("name_extractor_avg=${nameExtractorAverageMicros()}")
appendLine("arguments_extractor_avg=${argumentsExtractorAverageMicros()}")
+ appendLine("sentry_nav_effect=${sentryNavEffectDurations.summary()}")
appendLine("mutation_to_composition=${mutationToCompositionSummary()}")
appendLine("mutation_to_first_draw=${mutationToFirstDrawSummary()}")
appendLine("first_draws_over_8_3_ms=${firstDrawsOver8Millis()}")
appendLine("first_draws_over_16_7_ms=${firstDrawsOver16Millis()}")
+ appendLine("live_heap_before_run=${formatBytes(liveHeapBeforeRunBytes)}")
+ appendLine("live_heap_after_run=${formatBytes(liveHeapAfterRunBytes)}")
+ appendLine("live_heap_after_flush=${formatBytes(liveHeapAfterFlushBytes)}")
+ appendLine("transactions_dropped_queue_overflow=${queueOverflowDropsDuringRun ?: "n/a"}")
comparisonResult?.let { append("ab_result=$it") }
}
@@ -385,10 +424,21 @@ internal class Nav3PerformanceState(
}
private fun finishMeasuredPhase() {
- pendingMeasuredPhase?.let { phase -> endAsyncTraceSection(phase.sectionName, phase.cookie) }
+ pendingMeasuredPhase?.let { phase ->
+ endAsyncTraceSection(phase.sectionName, phase.cookie)
+ liveHeapAfterRunBytes = measureLiveHeapBytes()
+ queueOverflowDropsDuringRun = queueOverflowDropsAtRunStart?.let {
+ Nav3QueueOverflowDrops.count - it
+ }
+ }
pendingMeasuredPhase = null
}
+ /** Call after Sentry.flush, so the reading leaves out envelopes that were waiting to be sent. */
+ fun recordLiveHeapAfterFlush() {
+ liveHeapAfterFlushBytes = measureLiveHeapBytes()
+ }
+
fun mutationToCompositionSummary(): String = mutationToCompositionDurations.summary()
fun mutationToFirstDrawSummary(): String = mutationToFirstDrawDurations.summary()
@@ -490,7 +540,11 @@ internal class Nav3PerformanceDurations {
}
fun compactSummary(): String =
- if (values.isEmpty()) "disabled" else "p50=${formatNanos(percentile(50))}"
+ if (values.isEmpty()) {
+ "no samples"
+ } else {
+ "p50=${formatNanos(percentile(50))}, p90=${formatNanos(percentile(90))}"
+ }
fun minus(other: Nav3PerformanceDurations): Nav3PerformanceDurations =
Nav3PerformanceDurations().also { result ->
@@ -528,9 +582,9 @@ internal enum class Nav3PerformanceIntegrationMode(
}
internal enum class Nav3PerformanceRun(val label: String) {
- UNRELATED_RECOMPOSITIONS("Run 20 recompositions"),
- TOP_REPLACEMENTS("Run 20 top replacements"),
- LOWER_ENTRY_MUTATIONS("Run 20 lower mutations"),
+ UNRELATED_RECOMPOSITIONS("Run $PERFORMANCE_MEASURED_ITERATIONS recompositions"),
+ TOP_REPLACEMENTS("Run $PERFORMANCE_MEASURED_ITERATIONS top replacements"),
+ LOWER_ENTRY_MUTATIONS("Run $PERFORMANCE_MEASURED_ITERATIONS lower mutations"),
AB_COMPARISON("Run A/B comparison"),
}
@@ -771,7 +825,11 @@ internal fun Nav3PerformancePanel(
enabled = !state.performanceRunActive,
options =
Nav3PerformanceIntegrationMode.entries.map { mode ->
- mode.label to { state.updateIntegrationMode(mode) }
+ mode.label to
+ {
+ state.updateIntegrationMode(mode)
+ state.resetCounters()
+ }
},
)
PerfStepper(
@@ -880,7 +938,11 @@ internal fun Nav3PerformancePanel(
enabled = !state.performanceRunActive,
options =
Nav3PerformanceExtractorMode.entries.map { mode ->
- mode.label to { state.extractorMode = mode }
+ mode.label to
+ {
+ state.extractorMode = mode
+ state.resetCounters()
+ }
},
)
PerfModeRow(
@@ -889,7 +951,11 @@ internal fun Nav3PerformancePanel(
enabled = !state.performanceRunActive,
options =
Nav3PerformanceArgumentMode.entries.map { mode ->
- mode.label to { state.argumentMode = mode }
+ mode.label to
+ {
+ state.argumentMode = mode
+ state.resetCounters()
+ }
},
)
}
@@ -1243,15 +1309,57 @@ private fun Nav3PerformanceState.argumentsExtractorAverageMicros(): String =
averageMicros(argumentsExtractorNanos, argumentsExtractorCalls)
private fun averageMicros(totalNanos: Long, count: Int): String =
- if (count == 0) "0 us" else "${totalNanos / count / 1_000} us"
+ if (count == 0) "n/a" else formatNanos(totalNanos / count)
private fun formatNanos(durationNanos: Long): String =
if (durationNanos < 1_000_000L) {
- "${durationNanos / 1_000} us"
+ String.format(Locale.US, "%.1f us", durationNanos / 1_000.0)
} else {
String.format(Locale.US, "%.2f ms", durationNanos / 1_000_000.0)
}
+// Collects first, so the result is live objects rather than garbage that happens to be uncollected.
+private fun measureLiveHeapBytes(): Long {
+ val runtime = Runtime.getRuntime()
+ runtime.gc()
+ return runtime.totalMemory() - runtime.freeMemory()
+}
+
+/**
+ * Counts transactions the SDK drops because its send queue is full. Installed once and kept for the
+ * process, like SampleBeforeSendTransactionHook, because the SDK holds a single onDiscard callback.
+ */
+private object Nav3QueueOverflowDrops {
+ private val dropped = AtomicLong()
+ @Volatile private var installed = false
+
+ val count: Long
+ get() = dropped.get()
+
+ fun installIfNeeded(options: SentryOptions) {
+ if (installed) {
+ return
+ }
+ synchronized(this) {
+ if (installed) {
+ return
+ }
+ val previous = options.onDiscard
+ // The SDK can call this from the transport's thread as well as the main thread.
+ options.onDiscard = SentryOptions.OnDiscardCallback { reason, category, number ->
+ if (reason == DiscardReason.QUEUE_OVERFLOW && category == DataCategory.Transaction) {
+ dropped.addAndGet(number)
+ }
+ previous?.execute(reason, category, number)
+ }
+ installed = true
+ }
+ }
+}
+
+private fun formatBytes(bytes: Long?): String =
+ if (bytes == null) "n/a" else String.format(Locale.US, "%.1f MB", bytes / (1024.0 * 1024.0))
+
private fun beginAsyncTraceSection(sectionName: String, cookie: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Trace.beginAsyncSection(sectionName, cookie)
diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceLaunch.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceLaunch.kt
new file mode 100644
index 00000000000..b5ce3d0faa7
--- /dev/null
+++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceLaunch.kt
@@ -0,0 +1,49 @@
+package io.sentry.samples.android.navigation.nav3
+
+import android.content.Intent
+
+/**
+ * A performance run requested through [Nav3Activity]'s intent extras, so runs can be started with
+ * `adb shell am start` instead of through the UI.
+ *
+ * Each extra takes an enum constant's name, case-insensitively. All are optional; [preset] is
+ * applied first, then [integrationMode], then [run] starts. For example:
+ * ```
+ * adb shell am start -n io.sentry.samples.android.debug/io.sentry.samples.android.navigation.nav3.Nav3Activity \
+ * --es nav3_perf_preset capture_100_of_100 --es nav3_perf_run ab_comparison
+ * ```
+ *
+ * The results are logged under the `NavPerformance` tag, between `NAV_PERF_DIAGNOSTICS_START` and
+ * `NAV_PERF_DIAGNOSTICS_END`.
+ */
+internal data class Nav3PerformanceLaunch(
+ val preset: Nav3PerformancePreset?,
+ val integrationMode: Nav3PerformanceIntegrationMode?,
+ val run: Nav3PerformanceRun?,
+)
+
+/** Returns the requested performance run, or null if the intent requests none. */
+internal fun Intent.nav3PerformanceLaunch(): Nav3PerformanceLaunch? {
+ val launch =
+ Nav3PerformanceLaunch(
+ preset = enumExtra(EXTRA_PERFORMANCE_PRESET),
+ integrationMode = enumExtra(EXTRA_PERFORMANCE_INTEGRATION_MODE),
+ run = enumExtra(EXTRA_PERFORMANCE_RUN),
+ )
+ return if (launch == Nav3PerformanceLaunch(null, null, null)) null else launch
+}
+
+// Fails on an unknown value, since a script that silently ran a different configuration would
+// report misleading numbers.
+private inline fun > Intent.enumExtra(name: String): T? {
+ val value = getStringExtra(name) ?: return null
+ return enumValues().firstOrNull { it.name.equals(value, ignoreCase = true) }
+ ?: throw IllegalArgumentException(
+ "Unknown $name '$value'. Expected one of: " +
+ enumValues().joinToString { it.name.lowercase() },
+ )
+}
+
+private const val EXTRA_PERFORMANCE_PRESET = "nav3_perf_preset"
+private const val EXTRA_PERFORMANCE_INTEGRATION_MODE = "nav3_perf_integration_mode"
+private const val EXTRA_PERFORMANCE_RUN = "nav3_perf_run"