From 9ab696874444868805234713f97f361c134e7adc Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 27 Nov 2026 16:07:36 +0100 Subject: [PATCH 1/2] test(nav3): Verify the SerialName mapper under R8 Add nav3-built-in-back-stack-mappers-r8-check, an app that maps representative back stack keys with BackStackEntryMapper.SerialName in an R8-minified release build and reports whether each name and unknown entry reason is right, and scripts/test-nav3-built-in-back-stack-mappers-r8.sh, which builds it and runs it on a booted emulator or device. Besides names, the app checks that R8 renamed classes, and, through a logger that records the mapper's messages, that the compatibility probe was conclusive. The Nav3 R8 workflow runs the check on API 23 in R8 full mode against the kotlinx.serialization floor and its latest stable release, and in compat mode against the floor, and runs the module's unit tests against the latest stable release. It only runs when files that can affect the check change. --- .../workflows/integration-tests-nav3-r8.yml | 135 +++++++++++++++ ...est-nav3-built-in-back-stack-mappers-r8.sh | 123 +++++++++++++ .../README.md | 36 ++++ .../build.gradle.kts | 78 +++++++++ .../proguard-rules.pro | 20 +++ .../src/main/AndroidManifest.xml | 13 ++ .../r8/BuiltInBackStackMappersActivity.kt | 112 ++++++++++++ .../io/sentry/tests/nav3/r8/ProbeLogChecks.kt | 93 ++++++++++ .../sentry/tests/nav3/r8/SerializableKeys.kt | 161 ++++++++++++++++++ .../tests/nav3/r8/UnknownEntryReasonLogs.kt | 34 ++++ .../settings.gradle.kts | 2 + 11 files changed, 807 insertions(+) create mode 100644 .github/workflows/integration-tests-nav3-r8.yml create mode 100755 scripts/test-nav3-built-in-back-stack-mappers-r8.sh create mode 100644 sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md create mode 100644 sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts create mode 100644 sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/proguard-rules.pro create mode 100644 sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/AndroidManifest.xml create mode 100644 sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt create mode 100644 sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt create mode 100644 sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt create mode 100644 sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/UnknownEntryReasonLogs.kt diff --git a/.github/workflows/integration-tests-nav3-r8.yml b/.github/workflows/integration-tests-nav3-r8.yml new file mode 100644 index 00000000000..9271eaa18f6 --- /dev/null +++ b/.github/workflows/integration-tests-nav3-r8.yml @@ -0,0 +1,135 @@ +name: Nav3 Built-in Back Stack Mappers R8 Check + +# Verifies behavior of BackStackEntryMapper.SerialName from sentry-android-navigation3 in +# R8-minified builds on an emulator. Runs tests in: +# +# - R8 full mode against the compile floor of kotlinx-serialization-core and its latest stable +# release; and +# - R8 compat mode against the compile floor. +# +# Also runs all the module's unit tests against the latest stable release. See +# sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md. + +# Only runs for the paths below. Not a required check, so skipped runs don't block PRs. Catalog +# filters match whole files, including changes to unrelated dependencies. +on: + push: + branches: + - main + paths: &nav3-r8-paths + - 'sentry-android-navigation3/**' + - 'sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/**' + # The settings, build script, and properties of the build that produces the check's APKs. + - 'sentry-android-integration-tests/*.gradle.kts' + - 'sentry-android-integration-tests/*.properties' + - 'scripts/test-nav3-built-in-back-stack-mappers-r8.sh' + - '.github/workflows/integration-tests-nav3-r8.yml' + # Build settings, R8 flags, build logic, the Gradle version, and the version catalogs + # (Kotlin, AGP and its R8, Compose, Nav3, and the kotlinx.serialization matrix). + - 'gradle.properties' + - 'settings.gradle.kts' + - 'build.gradle.kts' + - 'gradle/wrapper/**' + - 'gradle/libs.versions.toml' + - 'gradle/dependency-matrix.versions.toml' + - 'buildSrc/**' + - 'build-logic/**' + # Utilities the mapper uses to handle exceptions. + - 'sentry/src/main/java/io/sentry/util/**' + pull_request: + paths: *nav3-r8-paths + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + APK_DIR: "nav3-r8-check-apks" + APK_ARTIFACT_NAME: "nav3-r8-check-apks" + +jobs: + # Runs separately from the APK builds, so a unit test failure doesn't hide the R8 check's results. + unit-tests: + name: Unit tests + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '21' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + + # Apps may ship a newer kotlinx.serialization than sentry-android-navigation3 compiles + # against. The Build workflow runs the unit tests against the floor. + - name: Run unit tests against the latest stable kotlinx.serialization + run: ./gradlew :sentry-android-navigation3:testReleaseUnitTest -Pnav3TestKotlinx=latestStable + + build: + name: Build + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '21' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + + - name: Build APKs + run: ./scripts/test-nav3-built-in-back-stack-mappers-r8.sh build "${{ env.APK_DIR }}" + + - name: Upload APK artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: ${{ env.APK_ARTIFACT_NAME }} + path: ${{ env.APK_DIR }} + retention-days: 1 + + # Run on API 23, Nav3's minSdk, to verify that the minified app and its dependencies work on the + # oldest supported runtime. + run: + name: Run on API Level 23 + needs: build + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Enable KVM + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + - name: Download APK artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: ${{ env.APK_ARTIFACT_NAME }} + path: ${{ env.APK_DIR }} + + - name: Run check + uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # pin@v2.38.0 + with: + api-level: 23 + target: google_apis + arch: x86_64 + disable-animations: true + disable-spellchecker: true + emulator-options: -memory 4096 -no-window -gpu auto -noaudio -no-boot-anim -camera-back none -no-snapshot-save + script: ./scripts/test-nav3-built-in-back-stack-mappers-r8.sh run "${{ env.APK_DIR }}" diff --git a/scripts/test-nav3-built-in-back-stack-mappers-r8.sh b/scripts/test-nav3-built-in-back-stack-mappers-r8.sh new file mode 100755 index 00000000000..98c7cf43113 --- /dev/null +++ b/scripts/test-nav3-built-in-back-stack-mappers-r8.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# Verifies BackStackEntryMapper.SerialName in R8-minified builds on a booted emulator or device. +# See sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md. +# +# Usage: +# test-nav3-built-in-back-stack-mappers-r8.sh Build all APKs, then run them. +# test-nav3-built-in-back-stack-mappers-r8.sh build DIR Build all APKs into DIR. +# test-nav3-built-in-back-stack-mappers-r8.sh run DIR Install and run every APK built into DIR. +set -euo pipefail + +module="nav3-built-in-back-stack-mappers-r8-check" +moduleDir="sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check" +appId="io.sentry.tests.nav3.r8" +tag="NAV3_R8_CHECK" + +copyApk() { + cp "${moduleDir}/build/outputs/apk/release/nav3-built-in-back-stack-mappers-r8-check-release.apk" "$1" +} + +# Prints the subdirectory of DIR $1 that holds this script's APKs. +apkDirIn() { + echo "$1/${module}" +} + +build() { + local outDir + outDir="$(apkDirIn "$1")" + mkdir -p "$outDir" + # Otherwise run() would also run APKs for versions no longer tested. + rm -f "$outDir"/*.apk + for mode in full compat; do + local fullMode=true + [[ "$mode" == "compat" ]] && fullMode=false + echo "Building R8 $mode mode APK (kotlinx floor)..." + ./gradlew -p sentry-android-integration-tests ":${module}:assembleRelease" "-Pandroid.enableR8.fullMode=${fullMode}" + copyApk "${outDir}/${mode}.apk" + + # Compat mode keeps more than full mode, so it's only tested with the floor, where it changes + # the outcome for named companion objects (kotlinx.serialization's own R8 rules only cover them + # from 1.10.0 on). + [[ "$mode" == "compat" ]] && continue + + echo "Building R8 $mode mode APK (kotlinx latestStable)..." + ./gradlew -p sentry-android-integration-tests ":${module}:assembleRelease" \ + "-Pandroid.enableR8.fullMode=${fullMode}" "-Pnav3CheckKotlinx=latestStable" + copyApk "${outDir}/${mode}-kotlinx-latestStable.apk" + done +} + +# Installs and launches APK $1, prints its check's output, and fails unless the check passed. +runApk() { + local apk="$1" + adb uninstall "$appId" > /dev/null 2>&1 || true + adb install "$apk" > /dev/null || return 1 + # Reads only this launch's lines, so the previous APK's RESULT=PASS can't hide a failure. The + # timestamp has second precision, hence the sleep. + local since + sleep 1 + since="$(adb shell "date +'%m-%d %H:%M:%S.000'" | tr -d '\r')" || return 1 + adb shell am start -W -n "${appId}/.BuiltInBackStackMappersActivity" > /dev/null || return 1 + + local output="" + for _ in $(seq 1 60); do + output="$(adb logcat -d -T "$since" -s "${tag}:I" | grep "${tag}" || true)" + if grep -q "RESULT=" <<< "$output"; then + break + fi + if adb logcat -d -T "$since" -b crash | grep -q "$appId"; then + break + fi + sleep 1 + done + + if [[ -n "$output" ]]; then + sed -E "s/^.*${tag}: //" <<< "$output" + fi + if ! grep -q "RESULT=PASS" <<< "$output"; then + adb logcat -d -T "$since" -b crash | grep -A 20 "$appId" || true + return 1 + fi +} + +run() { + local apkDir + apkDir="$(apkDirIn "$1")" + local failed=0 + shopt -s nullglob + local apks=("$apkDir"/*.apk) + if [[ ${#apks[@]} -eq 0 ]]; then + echo "No APKs found in $apkDir" + exit 1 + fi + + for apk in "${apks[@]}"; do + local name + name="$(basename "$apk" .apk)" + echo "=== $name" + if ! runApk "$apk"; then + echo "FAILED: $name" + failed=1 + fi + done + + if [[ $failed -ne 0 ]]; then + echo "Nav3 Built-in Back Stack Mappers R8 check failed." + exit 1 + fi + echo "Nav3 Built-in Back Stack Mappers R8 check passed." +} + +case "${1:-}" in + build) build "${2:?Usage: $0 build DIR}" ;; + run) run "${2:?Usage: $0 run DIR}" ;; + "") + apkDir="${moduleDir}/build/r8-check-apks" + build "$apkDir" + run "$apkDir" + ;; + *) + echo "Usage: $0 [build DIR | run DIR]" + exit 1 + ;; +esac diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md new file mode 100644 index 00000000000..53cfad4fc8c --- /dev/null +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md @@ -0,0 +1,36 @@ +# nav3-built-in-back-stack-mappers-r8-check + +Checks that `BackStackEntryMapper.SerialName` works after R8 obfuscation: + +- Serial names, `/unknown` results, and warning reasons match expectations. +- The compatibility probe succeeds conclusively. +- R8 actually obfuscates a representative class. + +The app uses kotlinx.serialization's consumer rules and its own `proguard-rules.pro`; the SDK supplies no keep rules for app serialization +classes. + +## Run + +Boot an emulator or device, then run: + +```bash +./scripts/test-nav3-built-in-back-stack-mappers-r8.sh +``` + +Versions come from `gradle/dependency-matrix.versions.toml`. Both floor and latestStable run in R8 full mode; floor also runs in compat mode +to cover older named-companion rules. Each APK must report `RESULT=PASS`. + +CI also runs the module's unit tests against latestStable. + +## Handle a failing update + +Dependabot updates `kotlinxSerialization-latestStable` after a three-day cooldown. + +**Compilation failure:** if the release requires newer Kotlin, leave the PR open, file a linked Kotlin upgrade issue, and merge after the +upgrade and passing checks. Closing the PR tells Dependabot to ignore that version. The release remains untested here; apps with newer +compilers may still work. + +**Test failure:** investigate changes to serializer lookup, serial descriptors, or R8 rules. Fix incorrect names or unexpected `/unknown` +results, then merge the fix with the update. + +Preserve support for the floor in either case; see "Version floor" in the `kotlinx` package README. diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts new file mode 100644 index 00000000000..ce470e117d0 --- /dev/null +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts @@ -0,0 +1,78 @@ +// Checks BackStackEntryMapper.SerialName in R8-minified release builds. See README.md. +plugins { + id("com.android.application") + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.serialization) + id("io.sentry.spotless") + id("io.sentry.jdk-target") +} + +val sentryVersion = libs.versions.sentry.get() + +// Defaults to the oldest supported version, which has the fewest R8 rules. The test script also +// runs with -Pnav3CheckKotlinx=latestStable. +val kotlinxVersion = + when (val role = providers.gradleProperty("nav3CheckKotlinx").getOrElse("floor")) { + "floor" -> matrixLibs.versions.kotlinxSerialization.floor.get() + "latestStable" -> matrixLibs.versions.kotlinxSerialization.latestStable.get() + else -> error("nav3CheckKotlinx must be floor or latestStable, but was $role.") + } + +// kotlinx.serialization 1.10.0+ supplies R8 rules for named companions, so naming must succeed +// without app keep rules. Older releases may return the name or /unknown, depending on R8. +val namedCompanionAlwaysNamed = + kotlinxVersion.split('.', '-').let { parts -> + val major = parts[0].toInt() + val minor = parts.getOrNull(1)?.toIntOrNull() ?: 0 + major > 1 || (major == 1 && minor >= 10) + } + +android { + namespace = "io.sentry.tests.nav3.r8" + compileSdk = libs.versions.compileSdk.get().toInt() + compileSdkMinor = libs.versions.compileSdkMinor.get().toInt() + + defaultConfig { + applicationId = "io.sentry.tests.nav3.r8" + minSdk = libs.versions.minSdk.get().toInt() + targetSdk = libs.versions.targetSdk.get().toInt() + versionCode = 1 + versionName = "1.0" + buildConfigField("boolean", "NAMED_COMPANION_ALWAYS_NAMED", "$namedCompanionAlwaysNamed") + } + + signingConfigs { + getByName("debug") { + storeFile = file("../../debug.keystore") + storePassword = "android" + keyAlias = "androiddebugkey" + keyPassword = "android" + } + } + + buildTypes { + release { + isMinifyEnabled = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro", + ) + signingConfig = signingConfigs.getByName("debug") + } + } + + buildFeatures { buildConfig = true } + + androidComponents.beforeVariants { it.enable = it.buildType == "release" } +} + +dependencies { + implementation("io.sentry:sentry-android-navigation3:$sentryVersion") + // Lets the check initialize Sentry with a logger that records the mapper's messages. + implementation("io.sentry:sentry-android-core:$sentryVersion") + // compileOnly in sentry-android-navigation3; always available for apps that use Nav3. + implementation(libs.androidx.compose.runtime) + + // Strict, so that no other dependency can raise the version the check runs against. + implementation(matrixLibs.kotlinxSerialization.core) { version { strictly(kotlinxVersion) } } +} diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/proguard-rules.pro b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/proguard-rules.pro new file mode 100644 index 00000000000..b941e916c18 --- /dev/null +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/proguard-rules.pro @@ -0,0 +1,20 @@ +# kotlinx.serialization's named-companion rules for R8 full mode, which also work in compat mode. +# Needed for the serialization floor (1.7.3); kotlinx.serialization 1.10.0+ supplies its own. +# See https://docs.sentry.io/platforms/android/integrations/navigation/#troubleshooting-kotlinxserialization-mappers +# https://github.com/Kotlin/kotlinx.serialization#android +-keepattributes InnerClasses + +-if @kotlinx.serialization.Serializable class +io.sentry.tests.nav3.r8.NamedCompanionKeyWithRules +{ + static **$* *; +} +-keepnames class <1>$$serializer { + static <1>$$serializer INSTANCE; +} + +-keepclasseswithmembers, allowshrinking, allowobfuscation, allowaccessmodification class +io.sentry.tests.nav3.r8.NamedCompanionKeyWithRules +{ + *; +} diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/AndroidManifest.xml b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..2861bd0926a --- /dev/null +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt new file mode 100644 index 00000000000..85f807569b8 --- /dev/null +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt @@ -0,0 +1,112 @@ +package io.sentry.tests.nav3.r8 + +import android.app.Activity +import android.os.Bundle +import android.util.Log +import android.widget.ScrollView +import android.widget.TextView +import io.sentry.compose.navigation3.BackStackEntryMapper + +/** + * Maps every [Expectation] with `BackStackEntryMapper.SerialName`, and reports the results. + * + * An exception crashes the Activity, which the runner script reports as a failure. + */ +class BuiltInBackStackMappersActivity : Activity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + // Before the mapper's first map() call, which runs its compatibility probe. + val logger = RecordingLogger() + initSentry(this, logger) + + val nameMapper = BackStackEntryMapper.SerialName + val expectations = + listOf( + Expectation("string", "home", null, setOf(ENTRY_NOT_ANNOTATED)), + Expectation( + "non-serializable class", + NotSerializable("1"), + null, + setOf(ENTRY_NOT_ANNOTATED), + ), + Expectation("unannotated enum", UnannotatedEnum.A, null, setOf(ENTRY_NOT_ANNOTATED)), + ) + serializableExpectations() + + val lines = mutableListOf() + var failures = 0 + + for (expectation in expectations) { + val named = nameMapper.map(expectation.key) + val reason = if (named == null) loggedUnknownEntryReason(logger, expectation.key) else null + val unnamedAsExpected = named == null && reason in expectation.unknownEntryReasons + val passed = + if (expectation.expected == null) { + unnamedAsExpected + } else { + (named?.name == expectation.expected && named?.arguments == null) || unnamedAsExpected + } + val fellBack = expectation.expected != null && unnamedAsExpected + + if (!passed) failures++ + + lines += + "${if (passed) "PASS" else "FAIL"} ${expectation.label} " + + "(runtime class ${expectation.key.javaClass.name}): " + + "expected=${expectation.expected ?: "/unknown"} actual=${named?.name ?: "/unknown"}" + + (named?.arguments?.let { " arguments=$it" } ?: "") + + (if (named == null) " reason=$reason (expected ${expectation.unknownEntryReasons})" + else "") + + if (fellBack) " (INFO: fell back to /unknown, also accepted)" else "" + } + + for (check in minificationChecks() + probeLogChecks(logger)) { + if (!check.passed) failures++ + lines += "${if (check.passed) "PASS" else "FAIL"} ${check.description}" + } + + lines += "RESULT=${if (failures == 0) "PASS" else "FAIL ($failures)"}" + + lines.forEach { Log.i(TAG, it) } + setContentView( + ScrollView(this).apply { + addView(TextView(context).apply { text = lines.joinToString(separator = "\n") }) + }, + ) + } + + private companion object { + const val TAG = "NAV3_R8_CHECK" + } +} + +/** A check of the build or the SDK's state, besides an [Expectation]. */ +class Check(val description: String, val passed: Boolean) + +/** + * A back stack key and the name [BackStackEntryMapper.SerialName] should produce for it, or `null` + * if it should be unnamed, with one of [unknownEntryReasons]. + * + * A key with an [expected] name may also have [unknownEntryReasons], if neither + * kotlinx.serialization nor R8 guarantees whether it can be named. The mapper may then instead + * return `null` for it, with one of those reasons. + */ +class Expectation( + val label: String, + val key: Any, + val expected: String?, + val unknownEntryReasons: Set = emptySet(), +) { + init { + require(expected != null || unknownEntryReasons.isNotEmpty()) { + "$label: an unnamed key must have the reasons it may be unnamed with." + } + } +} + +data class NotSerializable(val id: String) + +enum class UnannotatedEnum { + A, +} diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt new file mode 100644 index 00000000000..d58dcb5d89b --- /dev/null +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt @@ -0,0 +1,93 @@ +package io.sentry.tests.nav3.r8 + +import android.content.Context +import io.sentry.ILogger +import io.sentry.SentryLevel +import io.sentry.android.core.SentryAndroid +import java.util.Collections + +/** + * Records the messages the SDK logs, so the check can tell whether the mapper's compatibility probe + * ran conclusively under R8. + */ +class RecordingLogger : ILogger { + + val messages: MutableList = Collections.synchronizedList(mutableListOf()) + + override fun log(level: SentryLevel, message: String, vararg args: Any?) { + messages += format(message, args) + } + + override fun log(level: SentryLevel, message: String, throwable: Throwable?) { + messages += withError(message, throwable) + } + + override fun log( + level: SentryLevel, + throwable: Throwable?, + message: String, + vararg args: Any?, + ) { + messages += withError(format(message, args), throwable) + } + + override fun isEnabled(level: SentryLevel?): Boolean = true + + private fun format(message: String, args: Array): String = + if (args.isEmpty()) message else String.format(message, *args) + + /** Appends [throwable] and its causes, so a failed check shows why the probe failed. */ + private fun withError(message: String, throwable: Throwable?): String = + if (throwable == null) message + else message + generateSequence(throwable) { it.cause }.take(5).joinToString { " | $it" } +} + +/** + * Initializes Sentry with [logger] and `debug` enabled, so the mapper's logs reach it. The DSN + * points nowhere reachable; the check captures no events. + */ +fun initSentry(context: Context, logger: ILogger) { + SentryAndroid.init(context) { options -> + options.dsn = "https://key@localhost/0" + options.isDebug = true + options.setLogger(logger) + } +} + +/** + * Checks that the compatibility probe completed conclusively under R8. + * + * Names alone aren't enough: an inconclusive probe can produce correct names through per-type + * fallback while failing to detect an incompatible kotlinx.serialization version. + * + * Inspects [logger]'s messages after mapping every [Expectation]. The [NotSerializable] warning + * confirms logging works; probe detection relies on fixed message prefixes. + */ +fun probeLogChecks(logger: RecordingLogger): List { + val messages = logger.messages.toList() + return listOf( + Check( + "the mapper's warnings reach the logger (one names ${NotSerializable::class.java.name})", + messages.any { NotSerializable::class.java.name in it }, + ), + ) + + PROBE_MESSAGE_PREFIXES.map { prefix -> + val logged = messages.firstOrNull { it.startsWith(prefix) } + Check( + "nothing logged \"$prefix…\"" + if (logged != null) " (logged: $logged)" else "", + logged == null, + ) + } +} + +/** + * The prefixes of the messages the mapper logs when its compatibility probe is inconclusive or + * fails, or a built-in mapper can't be created. + * + * See `KotlinxMapperDiagnostics` and `BuiltInBackStackEntryMappers` in sentry-android-navigation3. + */ +private val PROBE_MESSAGE_PREFIXES = + listOf( + "Nav3 couldn't verify kotlinx.serialization support", + "Nav3 built-in mapper creation failed", + ) diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt new file mode 100644 index 00000000000..3d77cfa5b93 --- /dev/null +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt @@ -0,0 +1,161 @@ +package io.sentry.tests.nav3.r8 + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +@Serializable data object PublicObject + +@Serializable @SerialName("Named") data class NamedClass(val id: String) + +@Serializable data class DefaultNamedClass(val id: String) + +@Serializable +sealed interface Sealed { + @Serializable data object Child : Sealed + + @Serializable data class Leaf(val id: String) : Sealed +} + +@Serializable +enum class SerializableEnum { + A, +} + +@Serializable data class Generic(val value: T) + +@Serializable private data object PrivateTopLevelObject + +@Serializable private data class PrivateTopLevelClass(val id: String) + +/** Named by its custom serializer, which the plugin's companion `serializer()` returns. */ +@Serializable(with = SlugSerializer::class) class Slug(val value: String) + +object SlugSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("slug", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Slug) = encoder.encodeString(value.value) + + override fun deserialize(decoder: Decoder): Slug = Slug(decoder.decodeString()) +} + +/** + * An enum whose constant has a body, so the constant is an instance of an anonymous subclass that + * isn't `@Serializable` itself. The mapper looks up the declaring enum instead. + */ +@Serializable +enum class TabWithBody { + HOME { + override fun icon(): String = "house" + }; + + abstract fun icon(): String +} + +/** A value class used as a back stack key itself, which is boxed when passed as `Any`. */ +@Serializable @JvmInline value class TabId(val id: String) + +/** + * Has a named companion and no app keep rules for it. kotlinx.serialization 1.10.0+ supplies the + * rules needed for serializer lookup, so the mapper must return its name. Older releases may return + * the name or `/unknown`; `/unknown` must report `serializer_not_found`. See + * `NAMED_COMPANION_ALWAYS_NAMED` in `build.gradle.kts`. + */ +@Serializable +data class NamedCompanionKey(val id: String) { + companion object Factory { + fun of(id: String): NamedCompanionKey = NamedCompanionKey(id) + } +} + +/** + * Like [NamedCompanionKey], but covered by kotlinx.serialization's named-companion R8 rules + * (`proguard-rules.pro`), as the + * [troubleshooting docs](https://docs.sentry.io/platforms/android/integrations/navigation/#troubleshooting-kotlinxserialization-mappers) + * tell apps to add. + */ +@Serializable +data class NamedCompanionKeyWithRules(val id: String) { + companion object Factory { + fun of(id: String): NamedCompanionKeyWithRules = NamedCompanionKeyWithRules(id) + } +} + +class Holder { + @Serializable private data object PrivateNestedObject + + @Serializable private data class PrivateNestedClass(val id: String) + + companion object { + fun keys(): List = + listOf( + Expectation( + "private nested object", + PrivateNestedObject, + "io.sentry.tests.nav3.r8.Holder.PrivateNestedObject", + ), + Expectation( + "private nested class", + PrivateNestedClass("1"), + "io.sentry.tests.nav3.r8.Holder.PrivateNestedClass", + ), + ) + } +} + +private const val PKG = "io.sentry.tests.nav3.r8" + +fun serializableExpectations(): List = + listOf( + Expectation("public data object", PublicObject, "$PKG.PublicObject"), + Expectation("data class with @SerialName", NamedClass("1"), "Named"), + Expectation("data class", DefaultNamedClass("1"), "$PKG.DefaultNamedClass"), + Expectation("sealed child object", Sealed.Child, "$PKG.Sealed.Child"), + Expectation("sealed leaf class", Sealed.Leaf("1"), "$PKG.Sealed.Leaf"), + Expectation( + "serializable enum", + SerializableEnum.A, + "$PKG.SerializableEnum", + ), + // In R8 full mode too, as AGP's default ProGuard files keep Signature and + // kotlinx.serialization's rules keep @Serializable classes. + Expectation("generic class", Generic("x"), null, setOf(GENERIC_ENTRY_TYPE)), + Expectation("private top-level object", PrivateTopLevelObject, "$PKG.PrivateTopLevelObject"), + Expectation( + "private top-level class", + PrivateTopLevelClass("1"), + "$PKG.PrivateTopLevelClass", + ), + Expectation("class with a custom serializer", Slug("shoes"), "slug"), + Expectation( + "enum constant with a body", + TabWithBody.HOME, + "$PKG.TabWithBody", + ), + Expectation("value class", TabId("feed"), "$PKG.TabId"), + Expectation( + "named companion without rules", + NamedCompanionKey.of("1"), + "$PKG.NamedCompanionKey", + if (BuildConfig.NAMED_COMPANION_ALWAYS_NAMED) emptySet() else setOf(SERIALIZER_NOT_FOUND), + ), + Expectation( + "named companion with rules", + NamedCompanionKeyWithRules.of("1"), + "$PKG.NamedCompanionKeyWithRules", + ), + ) + Holder.keys() + +fun minificationChecks(): List = + listOf( + Check( + "PublicObject was renamed (runtime class ${PublicObject::class.java.name})", + PublicObject::class.java.name != "$PKG.PublicObject", + ), + ) diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/UnknownEntryReasonLogs.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/UnknownEntryReasonLogs.kt new file mode 100644 index 00000000000..ec38644dc27 --- /dev/null +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/UnknownEntryReasonLogs.kt @@ -0,0 +1,34 @@ +package io.sentry.tests.nav3.r8 + +/** + * The `unknown_entry_reason` values this check expects, as `UnknownEntryReason` serializes them. + */ +const val ENTRY_NOT_ANNOTATED = "entry_not_annotated" +const val GENERIC_ENTRY_TYPE = "generic_entry_type" +const val SERIALIZER_NOT_FOUND = "serializer_not_found" +const val SERIALIZER_ACCESS_THREW = "serializer_access_threw" + +/** + * Returns the reason from the mapper's warning for [key]'s type, or `null` if none was logged. + * + * The reason is internal to the SDK, so the app reads the warning emitted by the branch that + * selects it. Matches fixed fragments of `KotlinxMapperDiagnostics` messages; changes to those + * fragments cause the check to fail. + */ +fun loggedUnknownEntryReason(logger: RecordingLogger, key: Any): String? { + // The mapper looks up an enum constant's declaring class, as a constant with a body is an + // instance of an anonymous subclass. + val type = (key as? Enum<*>)?.declaringJavaClass ?: key.javaClass + val message = + logger.messages.toList().firstOrNull { "can't name entries of type ${type.name} because" in it } + ?: return null + return REASONS_BY_MESSAGE_FRAGMENT.entries.firstOrNull { it.key in message }?.value +} + +private val REASONS_BY_MESSAGE_FRAGMENT = + mapOf( + "because the type is not @Serializable" to ENTRY_NOT_ANNOTATED, + "because the type has type parameters" to GENERIC_ENTRY_TYPE, + "because no serializer was found" to SERIALIZER_NOT_FOUND, + "because reading its annotations, serializer, or descriptor failed" to SERIALIZER_ACCESS_THREW, + ) diff --git a/sentry-android-integration-tests/settings.gradle.kts b/sentry-android-integration-tests/settings.gradle.kts index 99bc456129f..3e788a42d03 100644 --- a/sentry-android-integration-tests/settings.gradle.kts +++ b/sentry-android-integration-tests/settings.gradle.kts @@ -51,6 +51,7 @@ dependencyResolutionManagement { // gradle.properties links to the SDK build's, so versionName is the SDK version. version("sentry", providers.gradleProperty("versionName").get()) } + create("matrixLibs") { from(files("../gradle/dependency-matrix.versions.toml")) } } } @@ -66,3 +67,4 @@ include("sentry-uitest-android") include("sentry-uitest-android-critical") include("sentry-uitest-android-macrobenchmark") include("test-app-size") +include("nav3-built-in-back-stack-mappers-r8-check") From be9abcb806e73ac5813e5d4d63fc1fd2840fc6db Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 27 Nov 2026 18:18:55 +0100 Subject: [PATCH 2/2] test(nav3): Read the R8 check's names and reasons from what SentryNavEffect records The check read each /unknown entry's reason from the warning the mapper logs, so it couldn't tell whether the reason reached the payload, and it broke whenever a warning was reworded. It now shows every key to SentryNavEffect as one back stack and reads names and reasons from the Navigation context of a captured event that beforeSend drops. Co-Authored-By: Claude Opus 5.5 --- .../README.md | 2 +- .../build.gradle.kts | 10 +- .../r8/BuiltInBackStackMappersActivity.kt | 114 ++++++++++++------ .../io/sentry/tests/nav3/r8/ProbeLogChecks.kt | 7 +- .../sentry/tests/nav3/r8/RecordedBackStack.kt | 67 ++++++++++ .../tests/nav3/r8/UnknownEntryReasonLogs.kt | 34 ------ .../kotlinx/KotlinxBackStackEntryMapper.kt | 4 +- 7 files changed, 160 insertions(+), 78 deletions(-) create mode 100644 sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/RecordedBackStack.kt delete mode 100644 sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/UnknownEntryReasonLogs.kt diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md index 53cfad4fc8c..3b268c3d4c9 100644 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/README.md @@ -2,7 +2,7 @@ Checks that `BackStackEntryMapper.SerialName` works after R8 obfuscation: -- Serial names, `/unknown` results, and warning reasons match expectations. +- The names and `unknown_entry_reason`s that `SentryNavEffect` records in the `Navigation` context match expectations. - The compatibility probe succeeds conclusively. - R8 actually obfuscates a representative class. diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts index ce470e117d0..8902055f5d4 100644 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/build.gradle.kts @@ -2,6 +2,7 @@ plugins { id("com.android.application") alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.compose) alias(libs.plugins.kotlin.serialization) id("io.sentry.spotless") id("io.sentry.jdk-target") @@ -61,7 +62,10 @@ android { } } - buildFeatures { buildConfig = true } + buildFeatures { + buildConfig = true + compose = true + } androidComponents.beforeVariants { it.enable = it.buildType == "release" } } @@ -72,6 +76,10 @@ dependencies { implementation("io.sentry:sentry-android-core:$sentryVersion") // compileOnly in sentry-android-navigation3; always available for apps that use Nav3. implementation(libs.androidx.compose.runtime) + // Hosts SentryNavEffect, so the check reads names and reasons from what the SDK records. Compose + // UI 1.7+ provides the LocalLifecycleOwner the effect reads, as it does in every Nav3 app. + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.compose.ui) // Strict, so that no other dependency can raise the version the check runs against. implementation(matrixLibs.kotlinxSerialization.core) { version { strictly(kotlinxVersion) } } diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt index 85f807569b8..c8dd1f9ef09 100644 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BuiltInBackStackMappersActivity.kt @@ -1,27 +1,32 @@ package io.sentry.tests.nav3.r8 -import android.app.Activity import android.os.Bundle import android.util.Log -import android.widget.ScrollView -import android.widget.TextView +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.runtime.LaunchedEffect +import io.sentry.Sentry import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.SentryNavEffect +import io.sentry.compose.navigation3.SentryNavOptions +import kotlinx.coroutines.delay /** - * Maps every [Expectation] with `BackStackEntryMapper.SerialName`, and reports the results. + * Shows every [Expectation]'s key as one back stack to `SentryNavEffect` with + * `BackStackEntryMapper.SerialName`, and reports the names and reasons it records. * * An exception crashes the Activity, which the runner script reports as a failure. */ -class BuiltInBackStackMappersActivity : Activity() { +class BuiltInBackStackMappersActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Before the mapper's first map() call, which runs its compatibility probe. val logger = RecordingLogger() - initSentry(this, logger) + val recorder = BackStackRecorder() + initSentry(this, logger, recorder) - val nameMapper = BackStackEntryMapper.SerialName val expectations = listOf( Expectation("string", "home", null, setOf(ENTRY_NOT_ANNOTATED)), @@ -33,32 +38,69 @@ class BuiltInBackStackMappersActivity : Activity() { ), Expectation("unannotated enum", UnannotatedEnum.A, null, setOf(ENTRY_NOT_ANNOTATED)), ) + serializableExpectations() + val backStack = expectations.map { it.key } + val options = SentryNavOptions { + enableNavigationTransactions = false + maxCapturedBackStackEntries = backStack.size + } - val lines = mutableListOf() - var failures = 0 + setContent { + SentryNavEffect(backStack, BackStackEntryMapper.SerialName, options) - for (expectation in expectations) { - val named = nameMapper.map(expectation.key) - val reason = if (named == null) loggedUnknownEntryReason(logger, expectation.key) else null - val unnamedAsExpected = named == null && reason in expectation.unknownEntryReasons - val passed = - if (expectation.expected == null) { - unnamedAsExpected - } else { - (named?.name == expectation.expected && named?.arguments == null) || unnamedAsExpected + LaunchedEffect(Unit) { + // The back stack reaches the scope once the effect holds the Activity's nav lease. + var recorded: List? = null + for (attempt in 1..RECORD_ATTEMPTS) { + recorded = recorder.recordedBackStack { Sentry.captureMessage(it) } + if (recorded != null) break + delay(RECORD_RETRY_MILLIS) } - val fellBack = expectation.expected != null && unnamedAsExpected + report(expectations, recorded?.reversed(), logger, recorder.lastEventSummary) + } + } + } - if (!passed) failures++ + private fun report( + expectations: List, + recorded: List?, + logger: RecordingLogger, + lastEventSummary: String, + ) { + val lines = mutableListOf() + var failures = 0 + if (recorded?.size != expectations.size) { + failures++ lines += - "${if (passed) "PASS" else "FAIL"} ${expectation.label} " + - "(runtime class ${expectation.key.javaClass.name}): " + - "expected=${expectation.expected ?: "/unknown"} actual=${named?.name ?: "/unknown"}" + - (named?.arguments?.let { " arguments=$it" } ?: "") + - (if (named == null) " reason=$reason (expected ${expectation.unknownEntryReasons})" - else "") + - if (fellBack) " (INFO: fell back to /unknown, also accepted)" else "" + "FAIL SentryNavEffect recorded ${recorded?.size ?: "no"} back stack entries " + + "(expected ${expectations.size}; $lastEventSummary)" + } else { + expectations.zip(recorded).forEach { (expectation, entry) -> + val unnamed = entry.name == UNKNOWN + val unnamedAsExpected = + unnamed && entry.unknownEntryReason in expectation.unknownEntryReasons + val passed = + if (expectation.expected == null) { + unnamedAsExpected + } else { + (entry.name == "/${expectation.expected}" && !entry.hasArguments) || unnamedAsExpected + } + val fellBack = expectation.expected != null && unnamedAsExpected + + if (!passed) failures++ + + lines += + "${if (passed) "PASS" else "FAIL"} ${expectation.label} " + + "(runtime class ${expectation.key.javaClass.name}): " + + "expected=${expectation.expected?.let { "/$it" } ?: UNKNOWN} actual=${entry.name}" + + (if (entry.hasArguments) " (has arguments)" else "") + + (if (unnamed) { + " reason=${entry.unknownEntryReason} (expected ${expectation.unknownEntryReasons})" + } else { + "" + }) + + if (fellBack) " (INFO: fell back to $UNKNOWN, also accepted)" else "" + } } for (check in minificationChecks() + probeLogChecks(logger)) { @@ -67,17 +109,14 @@ class BuiltInBackStackMappersActivity : Activity() { } lines += "RESULT=${if (failures == 0) "PASS" else "FAIL ($failures)"}" - lines.forEach { Log.i(TAG, it) } - setContentView( - ScrollView(this).apply { - addView(TextView(context).apply { text = lines.joinToString(separator = "\n") }) - }, - ) } private companion object { const val TAG = "NAV3_R8_CHECK" + const val UNKNOWN = "/unknown" + const val RECORD_ATTEMPTS = 50 + const val RECORD_RETRY_MILLIS = 100L } } @@ -85,12 +124,13 @@ class BuiltInBackStackMappersActivity : Activity() { class Check(val description: String, val passed: Boolean) /** - * A back stack key and the name [BackStackEntryMapper.SerialName] should produce for it, or `null` - * if it should be unnamed, with one of [unknownEntryReasons]. + * A back stack key and the name `SentryNavEffect` should record for it with + * [BackStackEntryMapper.SerialName], or `null` if it should be unnamed, with one of + * [unknownEntryReasons]. * * A key with an [expected] name may also have [unknownEntryReasons], if neither - * kotlinx.serialization nor R8 guarantees whether it can be named. The mapper may then instead - * return `null` for it, with one of those reasons. + * kotlinx.serialization nor R8 guarantees whether it can be named. It may then instead be recorded + * as `/unknown`, with one of those reasons. */ class Expectation( val label: String, diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt index d58dcb5d89b..69322c9d7b3 100644 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt @@ -43,14 +43,15 @@ class RecordingLogger : ILogger { } /** - * Initializes Sentry with [logger] and `debug` enabled, so the mapper's logs reach it. The DSN - * points nowhere reachable; the check captures no events. + * Initializes Sentry with [logger] and `debug` enabled, so the mapper's logs reach it, and with + * [recorder] as `beforeSend`, which drops every event. The DSN points nowhere reachable. */ -fun initSentry(context: Context, logger: ILogger) { +fun initSentry(context: Context, logger: ILogger, recorder: BackStackRecorder) { SentryAndroid.init(context) { options -> options.dsn = "https://key@localhost/0" options.isDebug = true options.setLogger(logger) + options.beforeSend = recorder } } diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/RecordedBackStack.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/RecordedBackStack.kt new file mode 100644 index 00000000000..828cf4baeb2 --- /dev/null +++ b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/RecordedBackStack.kt @@ -0,0 +1,67 @@ +package io.sentry.tests.nav3.r8 + +import io.sentry.Hint +import io.sentry.SentryEvent +import io.sentry.SentryOptions +import java.util.Collections + +/** + * The `unknown_entry_reason` values this check expects, as `UnknownEntryReason` serializes them. + */ +const val ENTRY_NOT_ANNOTATED = "entry_not_annotated" +const val GENERIC_ENTRY_TYPE = "generic_entry_type" +const val SERIALIZER_NOT_FOUND = "serializer_not_found" +const val SERIALIZER_ACCESS_THREW = "serializer_access_threw" + +/** One back stack entry as SentryNavEffect records it in the `Navigation` context. */ +class RecordedEntry(val name: String?, val unknownEntryReason: String?, val hasArguments: Boolean) + +/** + * Captures the back stack SentryNavEffect records, by reading the `Navigation` context of an event + * that's dropped before it's sent. + */ +class BackStackRecorder : SentryOptions.BeforeSendCallback { + + @Volatile private var backStack: List? = null + + /** What the last check event carried, for failure messages. */ + @Volatile + var lastEventSummary: String = "no check event reached beforeSend" + private set + + override fun execute(event: SentryEvent, hint: Hint): SentryEvent? { + if (event.message?.formatted == CHECK_EVENT_MESSAGE) { + val context = event.contexts[NAVIGATION_CONTEXT] + lastEventSummary = + "last check event's contexts: ${Collections.list(event.contexts.keys())}, $NAVIGATION_CONTEXT: $context" + backStack = context?.let(::readBackStack) + } + return null + } + + /** + * Captures an event and returns the back stack recorded on it, top entry first, or `null` if none + * is recorded yet. + */ + fun recordedBackStack(capture: (String) -> Unit): List? { + backStack = null + capture(CHECK_EVENT_MESSAGE) + return backStack + } + + private fun readBackStack(context: Any): List? = + ((context as? Map<*, *>)?.get(BACK_STACK) as? List<*>)?.map { entry -> + val fields = entry as Map<*, *> + RecordedEntry( + name = fields["entry"] as String?, + unknownEntryReason = fields["unknown_entry_reason"] as String?, + hasArguments = "entry_arguments" in fields, + ) + } + + private companion object { + const val CHECK_EVENT_MESSAGE = "nav3-r8-check" + const val NAVIGATION_CONTEXT = "Navigation" + const val BACK_STACK = "Back Stack" + } +} diff --git a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/UnknownEntryReasonLogs.kt b/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/UnknownEntryReasonLogs.kt deleted file mode 100644 index ec38644dc27..00000000000 --- a/sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/UnknownEntryReasonLogs.kt +++ /dev/null @@ -1,34 +0,0 @@ -package io.sentry.tests.nav3.r8 - -/** - * The `unknown_entry_reason` values this check expects, as `UnknownEntryReason` serializes them. - */ -const val ENTRY_NOT_ANNOTATED = "entry_not_annotated" -const val GENERIC_ENTRY_TYPE = "generic_entry_type" -const val SERIALIZER_NOT_FOUND = "serializer_not_found" -const val SERIALIZER_ACCESS_THREW = "serializer_access_threw" - -/** - * Returns the reason from the mapper's warning for [key]'s type, or `null` if none was logged. - * - * The reason is internal to the SDK, so the app reads the warning emitted by the branch that - * selects it. Matches fixed fragments of `KotlinxMapperDiagnostics` messages; changes to those - * fragments cause the check to fail. - */ -fun loggedUnknownEntryReason(logger: RecordingLogger, key: Any): String? { - // The mapper looks up an enum constant's declaring class, as a constant with a body is an - // instance of an anonymous subclass. - val type = (key as? Enum<*>)?.declaringJavaClass ?: key.javaClass - val message = - logger.messages.toList().firstOrNull { "can't name entries of type ${type.name} because" in it } - ?: return null - return REASONS_BY_MESSAGE_FRAGMENT.entries.firstOrNull { it.key in message }?.value -} - -private val REASONS_BY_MESSAGE_FRAGMENT = - mapOf( - "because the type is not @Serializable" to ENTRY_NOT_ANNOTATED, - "because the type has type parameters" to GENERIC_ENTRY_TYPE, - "because no serializer was found" to SERIALIZER_NOT_FOUND, - "because reading its annotations, serializer, or descriptor failed" to SERIALIZER_ACCESS_THREW, - ) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt index 5bc90e41323..0a852bf11ba 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt @@ -215,8 +215,8 @@ internal class KotlinxBackStackEntryMapper( * * Only decides what's logged. Whether a type is looked up again is up to the mapper. * - * The R8 check reads each unnamed type's reason from these messages, so rewording one requires - * updating the fragments in its `UnknownEntryReasonLogs.kt` + * The R8 check matches the start of [inconclusiveProbe]'s message, so rewording it requires + * updating `ProbeLogChecks.kt` * (`sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check`). */ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) {