From 7f88357407cae5362586cc3aa2354002daa161d8 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 09:07:13 +0100 Subject: [PATCH 1/6] feat(samples): Start Nav3 performance runs from intent extras A run needed UI automation through MainActivity, Integrations, Nav3 setup and the Performance tab, because Nav3Activity wasn't exported. Export it and read the preset, integration mode and run from intent extras, so runs can be scripted with adb shell am start and their results read from logcat. Co-Authored-By: Claude Opus 5.5 --- .../src/main/AndroidManifest.xml | 3 +- .../android/navigation/nav3/Nav3Activity.kt | 51 ++++++++++++++----- .../navigation/nav3/Nav3PerformanceLaunch.kt | 49 ++++++++++++++++++ 3 files changed, 90 insertions(+), 13 deletions(-) create mode 100644 sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceLaunch.kt 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..d48cfc09d16 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, @@ -336,6 +341,39 @@ private fun Nav3SampleApp( } } + val selectScenario: (Nav3Scenario) -> Unit = { scenario -> + if (scenario != Nav3Scenario.PERFORMANCE && 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() + performanceLaunch.preset?.let { preset -> + prepareNav3PerformancePreset( + preset = preset, + state = performanceState, + backStack = backStack, + onMaxCapturedBackStackEntriesChange = { maxCapturedBackStackEntries = it }, + ) + } + 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 +411,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/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..33d38d308d3 --- /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" From ca02ac9f638ff15a38799080545ffd7b0d1305bc Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 09:12:50 +0100 Subject: [PATCH 2/6] feat(samples): Time SentryNavEffect and report heap in the Nav3 performance tab First draw lands on two 60 Hz frames, so it can't show the SDK's sub-frame cost. Time the SDK's synchronous back stack work directly, between effects placed before and after SentryNavEffect, and report its p50 and p90. Also measure 100 iterations instead of 20, report p90 for both sides of the A/B comparison, report live heap after a GC before and after each measured run, and show extractor averages below 1 us instead of truncating them to 0 us. Co-Authored-By: Claude Opus 5.5 --- .../android/navigation/nav3/Nav3Activity.kt | 13 ++++- .../navigation/nav3/Nav3Performance.kt | 2 +- .../nav3/Nav3PerformanceControls.kt | 55 ++++++++++++++++--- .../navigation/nav3/Nav3PerformanceLaunch.kt | 2 +- 4 files changed, 61 insertions(+), 11 deletions(-) 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 d48cfc09d16..f12d380ac0e 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 @@ -293,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, @@ -366,7 +375,9 @@ private fun Nav3SampleApp( onMaxCapturedBackStackEntriesChange = { maxCapturedBackStackEntries = it }, ) } - performanceLaunch.integrationMode?.let { mode -> performanceState.updateIntegrationMode(mode) } + performanceLaunch.integrationMode?.let { mode -> + performanceState.updateIntegrationMode(mode) + } performanceLaunch.run?.let { run -> awaitNav3PerformanceFrames() runNav3Performance(run = run, state = performanceState, backStack = backStack) 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..c69a54d169e 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 @@ -280,4 +280,4 @@ internal suspend fun awaitNav3PerformanceFrames() { } private const val PERFORMANCE_WARM_UP_ITERATIONS = 5 -private const val PERFORMANCE_MEASURED_ITERATIONS = 20 +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..c5992ec1f93 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 @@ -99,6 +99,10 @@ 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 pendingOperation: PendingNav3PerformanceOperation? = null private var pendingAbPhase: PendingNav3PerformanceTrace? = null private var pendingMeasuredPhase: PendingNav3PerformanceTrace? = null @@ -125,6 +129,10 @@ internal class Nav3PerformanceState( pendingProcessedNavigationWork = false mutationToCompositionDurations.clear() mutationToFirstDrawDurations.clear() + sentryNavEffectDurations.clear() + sentryNavEffectStartedAtNanos = null + liveHeapBeforeRunBytes = null + liveHeapAfterRunBytes = null comparisonResult = null displayRevision++ } @@ -238,10 +246,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 +271,7 @@ internal class Nav3PerformanceState( if (shouldCountAsProcessed) { sentryNavEffectProcessedCalls++ capturedEntriesResolved += resolvedEntryCount + durationNanos?.let { sentryNavEffectDurations.add(it) } } pendingProcessedNavigationWork = false } @@ -276,6 +292,7 @@ internal class Nav3PerformanceState( finishMeasuredPhase() resetCounters() collectMeasurements = true + liveHeapBeforeRunBytes = measureLiveHeapBytes() val cookie = ++nextTraceCookie pendingMeasuredPhase = PendingNav3PerformanceTrace(MEASURED_SECTION, cookie) beginAsyncTraceSection(MEASURED_SECTION, cookie) @@ -315,7 +332,9 @@ 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)}" fun diagnosticsSummary(currentRoute: String, backStack: String): String = buildString { appendLine("status=$performanceStatus") @@ -331,10 +350,13 @@ 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)}") comparisonResult?.let { append("ab_result=$it") } } @@ -385,7 +407,10 @@ internal class Nav3PerformanceState( } private fun finishMeasuredPhase() { - pendingMeasuredPhase?.let { phase -> endAsyncTraceSection(phase.sectionName, phase.cookie) } + pendingMeasuredPhase?.let { phase -> + endAsyncTraceSection(phase.sectionName, phase.cookie) + liveHeapAfterRunBytes = measureLiveHeapBytes() + } pendingMeasuredPhase = null } @@ -490,7 +515,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 +557,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"), } @@ -1243,15 +1272,25 @@ 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() +} + +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 index 33d38d308d3..b5ce3d0faa7 100644 --- 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 @@ -40,7 +40,7 @@ private inline fun > Intent.enumExtra(name: String): T? { return enumValues().firstOrNull { it.name.equals(value, ignoreCase = true) } ?: throw IllegalArgumentException( "Unknown $name '$value'. Expected one of: " + - enumValues().joinToString { it.name.lowercase() } + enumValues().joinToString { it.name.lowercase() }, ) } From 37fb543253352b6528cde87a817536432e8431f6 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 09:18:59 +0100 Subject: [PATCH 3/6] fix(samples): Reset Nav3 performance counters when a mode changes Changing the integration mode, extractor cost or argument shape kept the counters, so the panel mixed measurements from the old mode with the new one. Reset them, as a run already does before it measures. Co-Authored-By: Claude Opus 5.5 --- .../navigation/nav3/Nav3PerformanceControls.kt | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) 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 c5992ec1f93..6724b96c83a 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 @@ -800,7 +800,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( @@ -909,7 +913,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( @@ -918,7 +926,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() + } }, ) } From 8cc2496e0a13b73981130d2351c68ddb84e47210 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 11:02:09 +0100 Subject: [PATCH 4/6] feat(samples): Report queue overflow drops and post-flush heap in Nav3 runs A burst of navigations fills the SDK's send queue, so the after-run heap reading mostly measured envelopes waiting to be sent, and dropped transactions went unreported. Count transactions dropped for queue overflow through onDiscard, then flush and read the heap again after each measured run. In an A/B run, the flush also gives the second side an empty queue. Co-Authored-By: Claude Opus 5.5 --- .../navigation/nav3/Nav3Performance.kt | 23 ++++++++ .../nav3/Nav3PerformanceControls.kt | 59 ++++++++++++++++++- 2 files changed, 81 insertions(+), 1 deletion(-) 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 c69a54d169e..b43dcb6af69 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( @@ -163,6 +166,10 @@ internal suspend fun runNav3Performance( ) { return } + state.stopCollectingMeasurements() + if (!flushSentryAndMeasureHeap(state)) { + return + } state.finishPerformanceRun() } catch (e: CancellationException) { state.cancelPerformanceRun() @@ -222,6 +229,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 +285,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_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 6724b96c83a..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 @@ -103,6 +108,9 @@ internal class Nav3PerformanceState( 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 @@ -133,6 +141,9 @@ internal class Nav3PerformanceState( sentryNavEffectStartedAtNanos = null liveHeapBeforeRunBytes = null liveHeapAfterRunBytes = null + liveHeapAfterFlushBytes = null + queueOverflowDropsAtRunStart = null + queueOverflowDropsDuringRun = null comparisonResult = null displayRevision++ } @@ -293,6 +304,8 @@ internal class Nav3PerformanceState( 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) @@ -334,7 +347,9 @@ internal class Nav3PerformanceState( fun performanceSummary(label: String): String = "$label: first draw ${mutationToFirstDrawDurations.compactSummary()}, " + "SentryNavEffect ${sentryNavEffectDurations.compactSummary()}, " + - "live heap ${formatBytes(liveHeapBeforeRunBytes)} -> ${formatBytes(liveHeapAfterRunBytes)}" + "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") @@ -357,6 +372,8 @@ internal class Nav3PerformanceState( 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") } } @@ -410,10 +427,18 @@ internal class Nav3PerformanceState( 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() @@ -1300,6 +1325,38 @@ private fun measureLiveHeapBytes(): Long { 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)) From 8eb750f9b51da696e883638aee56884810c870ef Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 12:28:39 +0100 Subject: [PATCH 5/6] fix(samples): Don't start an adb-requested Nav3 run after its preset is cancelled Leaving the Performance tab while an adb-requested preset warms up cancels the preset, but the launch code still started the run, on whichever scenario was open. prepareNav3PerformancePreset now returns whether it finished, and the launch code stops if it didn't. Co-Authored-By: Claude Opus 5.5 --- .../android/navigation/nav3/Nav3Activity.kt | 19 ++++++++++++------- .../navigation/nav3/Nav3Performance.kt | 6 ++++-- 2 files changed, 16 insertions(+), 9 deletions(-) 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 f12d380ac0e..f356ff42809 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 @@ -367,13 +367,18 @@ private fun Nav3SampleApp( LaunchedEffect(Unit) { selectScenario(Nav3Scenario.PERFORMANCE) awaitNav3PerformanceFrames() - performanceLaunch.preset?.let { preset -> - prepareNav3PerformancePreset( - preset = preset, - state = performanceState, - backStack = backStack, - onMaxCapturedBackStackEntriesChange = { maxCapturedBackStackEntries = it }, - ) + 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) 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 b43dcb6af69..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 @@ -87,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 @@ -110,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 From 66226a03023cad040758254fb416cab745061267 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 12:32:14 +0100 Subject: [PATCH 6/6] fix(samples): Stop a Nav3 performance run when its tab is selected again Selecting the Performance tab during a run reset its back stack and counters but let the run continue, so the run finished with partial measurements. Stop the run whenever a scenario is selected, as other tabs already did. Co-Authored-By: Claude Opus 5.5 --- .../io/sentry/samples/android/navigation/nav3/Nav3Activity.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 f356ff42809..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 @@ -351,7 +351,8 @@ private fun Nav3SampleApp( } val selectScenario: (Nav3Scenario) -> Unit = { scenario -> - if (scenario != Nav3Scenario.PERFORMANCE && performanceState.performanceRunActive) { + // Selecting a scenario resets its back stack and counters, so stop any run first. + if (performanceState.performanceRunActive) { performanceState.cancelPerformanceRun() } selectedScenario = scenario