From d79f2a86b358cdaddf0c9ae8d724dbd3edb9c027 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 27 Nov 2026 16:07:36 +0100 Subject: [PATCH 1/3] 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 ++++ .../nav3/Nav3PerformanceControls.kt | 12 +- .../settings.gradle.kts | 2 + sentry-android-navigation3/proguard-rules.pro | 9 + .../navigation3/BackStackEntryMapper.kt | 40 +--- .../internal/backstack/BackStackConverter.kt | 2 +- .../backstack/BuiltInBackStackEntryMappers.kt | 6 +- .../kotlinx/KotlinxBackStackEntryMapper.kt | 92 +++++---- .../kotlinx/KotlinxCompatibilityCheck.kt | 24 --- .../kotlinx/KotlinxCompatibilityProbe.kt | 134 ++++++++++++++ .../kotlinx/KotlinxSerializerLookup.kt | 27 ++- .../internal/backstack/kotlinx/README.md | 2 +- .../navigation3/internal/common/README.md | 9 - .../common/SerializationCompatibility.kt | 15 -- .../common/UnknownEntryReasonReporter.kt | 49 ----- .../navigation3/internal/contract/README.md | 8 - .../contract/UnknownEntryReasonReporter.kt | 41 +++++ .../navigation3/PackageBoundariesTest.kt | 24 --- .../backstack/BackStackConverterTest.kt | 2 +- .../BuiltInBackStackEntryMappersTest.kt | 4 +- .../UnavailableBackStackEntryMapperTest.kt | 2 +- .../KotlinxBackStackEntryMapperTest.kt | 174 +++--------------- .../kotlinx/KotlinxCompatibilityCheckTest.kt | 63 ------- .../kotlinx/KotlinxCompatibilityProbeTest.kt | 172 +++++++++++++++++ .../kotlinx/KotlinxMapperDiagnosticsTest.kt | 35 +++- .../kotlinx/KotlinxSerializerLookupTest.kt | 47 ++--- .../backstack/kotlinx/KotlinxTestEntries.kt | 21 +++ .../UnknownEntryReasonReporterTest.kt | 5 +- 37 files changed, 1337 insertions(+), 489 deletions(-) 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 delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt delete mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt rename sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/{common => contract}/UnknownEntryReasonReporterTest.kt (95%) 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/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 b5f432009bd..e10cce8bf96 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 @@ -53,8 +53,6 @@ internal class Nav3PerformanceState( var extractorMode by mutableStateOf(Nav3PerformanceExtractorMode.NORMAL) var argumentMode by mutableStateOf(Nav3PerformanceArgumentMode.FLAT) var mapperMode by mutableStateOf(Nav3PerformanceMapperMode.CUSTOM) - private set - var integrationMode by mutableStateOf(Nav3PerformanceIntegrationMode.FULL_STACK) private set @@ -181,14 +179,6 @@ internal class Nav3PerformanceState( suppressNextDestinationChange = true } - /** Resets the counters on a change, as each mapper records different measurements. */ - fun updateMapperMode(mode: Nav3PerformanceMapperMode) { - if (mapperMode != mode) { - mapperMode = mode - resetCounters() - } - } - fun updateIntegrationMode(mode: Nav3PerformanceIntegrationMode) { if (integrationMode != mode) { discardNextSentryNavEffectMeasurement = true @@ -906,7 +896,7 @@ internal fun Nav3PerformancePanel( enabled = !state.performanceRunActive, options = Nav3PerformanceMapperMode.entries.map { mode -> - mode.label to { state.updateMapperMode(mode) } + mode.label to { state.mapperMode = mode } }, ) 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") diff --git a/sentry-android-navigation3/proguard-rules.pro b/sentry-android-navigation3/proguard-rules.pro index b34c23cc870..d9de2ff242b 100644 --- a/sentry-android-navigation3/proguard-rules.pro +++ b/sentry-android-navigation3/proguard-rules.pro @@ -8,6 +8,15 @@ ##---------------Begin: proguard configuration for kotlinx.serialization ---------- +# The kotlinx.serialization compatibility probe looks up this SDK-owned fixture's serializer via reflection, as the built-in mappers look +# up those of apps' back stack entries. kotlinx.serialization's R8 rules before 1.8.0 keep an object's serializer() only while its INSTANCE +# field is kept, and R8 full mode removes INSTANCE here, as the SDK only refers to the object's class. The probe would then be inconclusive +# for object lookups. +-keepclassmembers class io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe$ProbeObject { + public static ** INSTANCE; + kotlinx.serialization.KSerializer serializer(...); +} + # Serial names survive R8 minification because Kotlin's serialization compiler plugin fixes them at compile time. Our built-in mapper # fallback for private `@Serializable` objects relies on members preserved by kotlinx.serialization's own consumer rules. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt index c24ed39db13..3c6b0ac1357 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt @@ -6,7 +6,8 @@ import org.jetbrains.annotations.ApiStatus /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * See [SerialName] for an out-of-the-box mapper, or else provide your own. + * See [SerialName] for an out-of-the-box mapper, or else provide your own. (Custom implementations + * can optionally fall back to `SerialName` for any entries that don't have to be special-cased.) * * **Privacy / PII** * @@ -30,13 +31,12 @@ import org.jetbrains.annotations.ApiStatus * **Names fall back to "/unknown"** * * If [map] throws, returns `null`, or returns a blank [name][SentryBackStackEntry.name], Sentry - * records the destination as "/unknown". (The sole exception is if [map] throws a fatal error, as - * fatal errors like [OutOfMemoryError] or [LinkageError] are propagated rather than being caught.) + * records the destination as "/unknown". Doing so signals that name extraction needs to be fixed + * while avoiding misleading gaps in nav state. * - * An "/unknown" entry signals that name extraction needs to be fixed while avoiding misleading gaps - * in nav state. For instance, if a user navigates from /home -> /detail -> /settings, but the - * mapper for /detail throws, the back stack record will be /home -> /unknown -> /settings rather - * than /home -> /settings. + * For instance, if a user navigates from /home -> /detail -> /settings, but the mapper for /detail + * throws, the back stack record will be /home -> /unknown -> /settings rather than /home -> + * /settings. * * Each "/unknown" entry records why it has no name under `unknown_entry_reason` (e.g., * `"mapping_failed"` if [map] threw). @@ -78,32 +78,6 @@ import org.jetbrains.annotations.ApiStatus * * In that case, it records why under `dropped_by_sentry` in the entry's arguments (e.g., * `"max_argument_count_exceeded"`). - * - * **Delegating to built-in mappers** - * - * Custom `BackStackEntryMapper`s may delegate to built-in mappers for entries the host app doesn't - * need to special-case: - * ```kotlin - * val mapper = BackStackEntryMapper { entry -> - * when (entry) { - * // Special-case any entries with sensitive info. - * is Cart -> SentryBackStackEntry( - * name = Cart.serializer().descriptor.serialName, - * arguments = mapOf("cartId" to entry.cartId), - * ) - * - * // Consider falling back to a built-in mapper for the rest. - * else -> BackStackEntryMapper.SerialName.map(entry) - * } - * } - * ``` - * - * Note: If a custom mapper calls a built-in mapper that returns `null`, and then the custom mapper - * returns `null` itself, the built-in mapper's `unknown_entry_reason` will be recorded. - * - * Be sure to invoke built-in mappers on the same thread that calls the custom mapper's [map] - * method, or else the original `unknown_entry_reason` may be lost and recorded as `"unmapped"` - * instead. */ @ApiStatus.Experimental public fun interface BackStackEntryMapper { diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt index 9285537508e..90c65bc3f41 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt @@ -5,7 +5,6 @@ import io.sentry.ILogger import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES @@ -17,6 +16,7 @@ import io.sentry.compose.navigation3.internal.contract.TRANSACTION_ARGUMENTS_KEY import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason.Companion.UNKNOWN_ENTRY_REASON_KEY +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.util.ExceptionUtils import java.util.IdentityHashMap diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt index 3fd1247a200..85a17ca3f1d 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt @@ -8,10 +8,10 @@ import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper -import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.util.Collections import java.util.concurrent.ConcurrentHashMap @@ -51,6 +51,8 @@ internal object BuiltInBackStackEntryMappers { logger() .log( WARNING, + // Note: The compiler inlines INCOMPATIBLE_KOTLINX_ADVICE, and its use here doesn't access + // any kotlinx.serialization code. "Nav3 built-in mapper creation failed. Using $UNKNOWN_ENTRY_NAME for all entries. See " + "the attached error. $INCOMPATIBLE_KOTLINX_ADVICE", e, 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 07cd2ffc47d..5bc90e41323 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 @@ -5,10 +5,9 @@ import io.sentry.SentryLevel.DEBUG import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.util.ExceptionUtils import java.lang.reflect.GenericSignatureFormatError import java.lang.reflect.InvocationTargetException @@ -24,7 +23,9 @@ internal class KotlinxBackStackEntryMapper( * Returns the serializer of a back stack entry's `@Serializable` class, or `null` if there's none * (e.g. for a generic class). Only called for classes marked `@Serializable`. * - * May throw, as the lookup can run the app's serializer code for the first time. + * May throw, as the lookup can run the app's serializer code for the first time. Must rethrow a + * fatal error unwrapped if reflection wrapped it in an [InvocationTargetException], as + * [reflectiveSerializerOrNull] does, since the mapper treats every wrapped error as non-fatal. */ private val lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, /** @@ -33,8 +34,9 @@ internal class KotlinxBackStackEntryMapper( * May throw, as reading the class's annotations can fail. */ private val isAnnotatedSerializable: (Class<*>) -> Boolean = serializableAnnotationCheck(), - /** Throws a [LinkageError] if the app's kotlinx.serialization version is incompatible. */ - checkCompatibility: () -> Unit = { checkKotlinxCompatibility() }, + probe: CompatibilityProbe = { onInconclusive -> + KotlinxCompatibilityProbe.nameLookupLinkageError(onInconclusive = onInconclusive) + }, logger: () -> ILogger, ) : BackStackEntryMapper { @@ -45,18 +47,9 @@ internal class KotlinxBackStackEntryMapper( private val diagnostics = KotlinxMapperDiagnostics(logger) init { - // A LinkageError fails creation, so every back stack entry is recorded as "/unknown" with - // kotlinx_serialization_version. - try { - checkCompatibility() - } catch (e: IllegalArgumentException) { - // kotlinx.serialization reports lookup failures as SerializationException, an - // IllegalArgumentException. Neither it nor an IllegalStateException means the version is - // incompatible, so we name entries and handle any failure per type. - diagnostics.compatibilityCheckFailed(e) - } catch (e: IllegalStateException) { - diagnostics.compatibilityCheckFailed(e) - } + // Throws if the host app uses an incompatible kotlinx-serialization-core version. Causes + // creation to fail and every back stack entry to be recorded as "/unknown". + probe { error -> diagnostics.inconclusiveProbe(error) }?.let { throw it } } override fun map(backStackEntry: Any): SentryBackStackEntry? { @@ -75,20 +68,10 @@ internal class KotlinxBackStackEntryMapper( return SentryBackStackEntry(cached.name) } - private fun cachedType(type: Class<*>): CachedType { - types[type]?.let { - return it - } - - // Threads that race on a type's first entry may each look it up and log a failure, but only - // one result is ever cached. - val result = lookUp(type) - // A lookup that failed on an interrupted thread may succeed later, so we don't cache it. - if (result is CachedType.Unresolved && Thread.currentThread().isInterrupted) { - return result - } - return types.putIfAbsent(type, result) ?: result - } + private fun cachedType(type: Class<*>): CachedType = + // getOrPut may look up a type more than once if threads race on its first entry. That can cause + // a failed lookup to be logged more than once, but only one result will ever be cached. + types.getOrPut(type) { lookUp(type) } /** * Looks up [type]'s serializer and serial name. Logs if the serializer isn't available or the @@ -112,14 +95,8 @@ internal class KotlinxBackStackEntryMapper( CachedType.Resolved(serializer.descriptor.serialName) } } catch (e: InvocationTargetException) { - // The type's serializer() or descriptor threw through reflection, e.g., a custom serializer's - // ExceptionInInitializerError. A wrapped LinkageError fails only this type, so it isn't - // rethrown as fatal. - val cause = e.cause - if (cause != null && cause !is LinkageError) { - ExceptionUtils.rethrowIfFatal(cause) - } - unresolved(type, cause ?: e) + // The type's serializer() threw, e.g., a custom serializer's ExceptionInInitializerError. + unresolved(type, e.cause ?: e) } catch (e: LinkageError) { // Construction checks the library itself, so this likely comes from the type's serializer, // e.g., one compiled against another kotlinx.serialization version. It fails only this type. @@ -238,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 matches the start of [compatibilityCheckFailed]'s message, so rewording it requires - * updating `CompatibilityLogChecks.kt` + * The R8 check reads each unnamed type's reason from these messages, so rewording one requires + * updating the fragments in its `UnknownEntryReasonLogs.kt` * (`sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check`). */ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { @@ -267,17 +244,18 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { } /** - * Logs that the compatibility check threw [error], which doesn't mean kotlinx.serialization is - * incompatible. The mapper handles subsequent failures per type. + * Logs that the probe couldn't verify support for name lookups, due to [error] or a missing probe + * serializer if the error is `null`. The mapper handles subsequent failures per type. */ - fun compatibilityCheckFailed(error: RuntimeException) { - // DEBUG b/c a failed check doesn't affect what's recorded. + fun inconclusiveProbe(error: Throwable?) { + // DEBUG b/c an inconclusive probe doesn't affect what's recorded. logger() .log( DEBUG, error, - "Nav3 couldn't verify kotlinx.serialization compatibility (see the attached error). " + + "Nav3 couldn't verify kotlinx.serialization support for name lookups because %s. " + "Handling failures per entry type.", + if (error != null) PROBE_THREW else PROBE_SERIALIZER_NOT_FOUND, ) } @@ -293,8 +271,7 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { val advice = // An ExceptionInInitializerError only means the app's own initializer threw an exception. if (error is LinkageError && error !is ExceptionInInitializerError) { - // E.g., an app serializer compiled against a newer kotlinx.serialization than the app - // ships. + // The probe can miss an incompatible version, which then fails every type one at a time. "See the attached error. If all types fail, kotlinx.serialization may be incompatible. " + INCOMPATIBLE_KOTLINX_ADVICE } else if (error != null) { @@ -314,9 +291,28 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { companion object { + /** + * The oldest kotlinx.serialization version [KotlinxBackStackEntryMapper] supports. + * + * Must match `kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml`. + */ + const val MIN_KOTLINX_SERIALIZATION_VERSION: String = "1.7.3" + + const val INCOMPATIBLE_KOTLINX_ADVICE: String = + "Requires kotlinx.serialization $MIN_KOTLINX_SERIALIZATION_VERSION or later. " + + "Upgrade kotlinx.serialization or the Sentry SDK. If both are current, report this at " + + "https://github.com/getsentry/sentry-java/issues/new/choose. Use a custom " + + "BackStackEntryMapper as a workaround." + /** Why a type can't be named, if reading its annotations, serializer, or descriptor threw. */ const val LOOK_UP_FAILED: String = "reading its annotations, serializer, or descriptor failed" + /** Why the compatibility probe was inconclusive, if it threw. */ + const val PROBE_THREW: String = "the compatibility probe threw (see the attached error)" + + /** Why the compatibility probe was inconclusive, if a probe type's serializer wasn't found. */ + const val PROBE_SERIALIZER_NOT_FOUND: String = "a probe serializer wasn't found" + /** Why a type can't be named, if its serializer lookup found none without throwing. */ const val SERIALIZER_NOT_FOUND: String = "no serializer was found (the type may be generic or require R8 keep rules)" diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt deleted file mode 100644 index ed5ac25d540..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt +++ /dev/null @@ -1,24 +0,0 @@ -@file:OptIn(ExperimentalSerializationApi::class) - -package io.sentry.compose.navigation3.internal.backstack.kotlinx - -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.KSerializer - -/** - * Verifies that the host app's `kotlinx-serialization-core` version is compatible with the APIs - * used by our built-in `BackStackEntryMapper`s. - * - * Does so by calling each kotlinx.serialization API that [KotlinxBackStackEntryMapper] calls, looks - * up the built-in `String` serializer, and reads its serial name. - * - * Throws a [LinkageError] if the app's `kotlinx-serialization-core` version is incompatible. A - * `LinkageError` thrown here is conclusive: unlike looking up an app type's serializer, the check - * runs no app code and no serializer generated by a compiler plugin, either of which could throw - * one for reasons that affect only its own type. - */ -internal fun checkKotlinxCompatibility( - lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, -) { - lookUpSerializer(String::class.java)?.descriptor?.serialName -} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt new file mode 100644 index 00000000000..65af42b4f6f --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt @@ -0,0 +1,134 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.util.ExceptionUtils +import java.lang.reflect.InvocationTargetException +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable + +/** + * Checks whether the app's `kotlinx-serialization-core` version successfully links against the APIs + * used by [KotlinxBackStackEntryMapper]. It does so via two built-in probe types ([ProbeClass] and + * [ProbeObject]). + * + * **Disambiguating serializer errors from library incompatibility** + * + * Without a check like this, `KotlinxBackStackEntryMapper` would have to infer an incompatible + * `kotlinx-serialization-core` version from [LinkageError]s thrown while handling the host app's + * own back stack entry types. But such errors can also come from the host app's serializer code, + * and should therefore only fail for the entry types that can't be deserialized. `ProbeClass` and + * `ProbeObject` don't execute any host app code, so a `LinkageError` while handling them means the + * app's `kotlinx-serialization-core` version is incompatible. + * + * Note: Only a `LinkageError` is conclusive, including one that reflection wrapped in an + * [InvocationTargetException] because a probe type's serializer threw it. Any other failure, or a + * probe type whose serializer can't be found, is ambiguous: it's reported to the caller's + * `onInconclusive` and otherwise ignored, as a real type that hits the same failure is handled and + * logged on its own. + */ +internal object KotlinxCompatibilityProbe { + + /** + * Checks `kotlinx-serialization-core` compatibility by retrieving serializers for [ProbeClass] + * and [ProbeObject] through [lookUpSerializer] and reading their serial names. + * + * Confines itself to methods used by our built-in [BackStackEntryMapper]s to avoid being disabled + * by incompatibilities from irrelevant APIs. + * + * Returns a [LinkageError] upon incompatibility, or `null` upon success or an inconclusive + * result. Additionally reports inconclusive results through [onInconclusive], passing the cause + * or `null` if a serializer is unavailable. + */ + fun nameLookupLinkageError( + lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, + onInconclusive: (Throwable?) -> Unit, + ): LinkageError? { + var isSerializerMissing = false + + val error = + probe(onInconclusive) { + for (type in listOf(ProbeClass::class.java, ProbeObject::class.java)) { + val descriptor = lookUpSerializer(type)?.descriptor + if (descriptor == null) { + isSerializerMissing = true + } else { + descriptor.serialName + } + } + } + + // Call outside probe() so an exception from onInconclusive isn't caught and reported back to + // the same callback. If a serializer is missing, the remaining lookup steps cannot be checked + // for that type. + if (isSerializerMissing) { + onInconclusive(null) + } + return error + } + + /** + * Runs [check], returning any [LinkageError] and rethrowing fatal errors. Returns `null` if the + * check succeeds or is inconclusive. + * + * Reports other errors to [onInconclusive], passing the cause. + */ + private inline fun probe( + onInconclusive: (Throwable) -> Unit, + check: () -> Unit, + ): LinkageError? = + try { + check() + null + } catch (e: LinkageError) { + e + } catch (e: InvocationTargetException) { + // A probe type's serializer runs only SDK and kotlinx.serialization code, so a LinkageError + // it throws means the library is incompatible. (The lookup keeps such errors wrapped, as an + // app type's serializer could throw them for unrelated reasons.) + val cause = e.cause + if (cause is LinkageError) { + cause + } else { + val error = cause ?: e + ExceptionUtils.rethrowIfFatal(error) + onInconclusive(error) + null + } + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad because the app's kotlinx.serialization version may throw anything. Only + // LinkageError confirms incompatibility. Other non-fatal failures are inconclusive. + // Failures for actual back stack types are handled and logged per type. + ExceptionUtils.rethrowIfFatal(t) + onInconclusive(t) + null + } + + /** + * A known serializable type used to test whether the app's kotlinx.serialization version supports + * serializer lookup, without running host app code. + * + * Internal visibility lets the probe look up its serializer the same way + * [KotlinxBackStackEntryMapper] looks up serializers for the host app's public back stack entry + * types. + */ + @Serializable internal data class ProbeClass(val name: String = "probe") + + /** + * A known serializable object used to test serializer lookup for the host app's object-based back + * stack entries. This lookup reads the object's singleton instance. + */ + @Serializable internal object ProbeObject +} + +/** + * Checks whether the app's `kotlinx-serialization-core` version supports retrieving serializers and + * reading their serial names. Returns a [LinkageError] for incompatibility, or `null` for success + * or an inconclusive check. + * + * Reports inconclusive results through `onInconclusive`, passing the error or `null` if a + * serializer couldn't be found. + */ +internal typealias CompatibilityProbe = (onInconclusive: (Throwable?) -> Unit) -> LinkageError? diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt index 919c915535c..310007c04e5 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt @@ -1,5 +1,6 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx +import io.sentry.util.ExceptionUtils import java.lang.reflect.InvocationTargetException import kotlinx.serialization.KSerializer import kotlinx.serialization.serializerOrNull @@ -9,24 +10,32 @@ import kotlinx.serialization.serializerOrNull * Extends [serializerOrNull] to support private `@Serializable` objects. Also supports built-in * types and unannotated enums. * - * May execute serializer code and throw. What that code throws through reflection, including fatal - * errors such as [OutOfMemoryError], arrives wrapped in an [InvocationTargetException]. + * May execute serializer code and throw. Unwraps fatal causes such as [OutOfMemoryError] from + * [InvocationTargetException] so that fatal-error checks can recognize them. Keeps [LinkageError] + * causes wrapped because they affect only this type. */ @Suppress("SwallowedException") internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = try { - serializerOrNull(type) - } catch (_: IllegalAccessException) { - // kotlinx.serialization reads a serializable object's INSTANCE field without making it - // accessible, which will fail for private objects. - privateObjectSerializerOrNull(type) + try { + serializerOrNull(type) + } catch (_: IllegalAccessException) { + // kotlinx.serialization reads a serializable object's INSTANCE field without making it + // accessible, which will fail for private objects. + privateObjectSerializerOrNull(type) + } + } catch (e: InvocationTargetException) { + val cause = e.cause + if (cause != null && cause !is LinkageError) { + ExceptionUtils.rethrowIfFatal(cause) + } + throw e } /** * Uses reflection to look up the serializer of a private `@Serializable object` through the members * the serialization compiler plugin generates for it. (kotlinx.serialization's consumer R8 rules - * keep both members.) kotlinx.serialization's own object lookup reads the same two members, so this - * fallback can break only if that lookup breaks too. + * keep both members.) * * Propagates any exception thrown by the reflective lookup. */ diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md index ba524b283c2..ddadd318837 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md @@ -42,7 +42,7 @@ Recommended rules for raising the floor: - Raise it in a reviewed change of its own, with a CHANGELOG entry and a corresponding update to the [Sentry Nav3 docs](https://docs.sentry.io/platforms/android/integrations/navigation/#navigation-3). -- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `internal/common/KotlinxSerializationSupport.kt` to match. A unit test will fail if the two differ. +- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `KotlinxBackStackEntryMapper.kt` to match. A unit test will fail if the two differ. ## Minification diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md deleted file mode 100644 index b1eb7e8c1db..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# `io.sentry.compose.navigation3.internal.common` - -Package contains internal code that more than one `io.sentry.compose.navigation3` package needs, but that isn't part of what the Sentry UI -shows (see the `contract` package). - -## Dependencies - -This package may depend only on the `contract` package among `io.sentry.compose.navigation3` packages. As `backstack.kotlinx` depends on it, -it may ***not*** depend on Android, AndroidX, or kotlinx.serialization. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt deleted file mode 100644 index 9326a8a9ff4..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt +++ /dev/null @@ -1,15 +0,0 @@ -package io.sentry.compose.navigation3.internal.common - -/** - * The oldest kotlinx.serialization version the built-in mappers support. - * - * Must match `kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml`. - */ -internal const val MIN_KOTLINX_SERIALIZATION_VERSION = "1.7.3" - -/** Advice logged when the app's kotlinx.serialization version may be incompatible. */ -internal const val INCOMPATIBLE_KOTLINX_ADVICE = - "Requires kotlinx.serialization $MIN_KOTLINX_SERIALIZATION_VERSION or later. " + - "Upgrade kotlinx.serialization or the Sentry SDK. If both are current, report this at " + - "https://github.com/getsentry/sentry-java/issues/new/choose. Use a custom " + - "BackStackEntryMapper as a workaround." diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt deleted file mode 100644 index d2e97d6f209..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt +++ /dev/null @@ -1,49 +0,0 @@ -package io.sentry.compose.navigation3.internal.common - -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason - -/** - * A side channel for built-in `BackStackEntryMapper`s to report [UnknownEntryReason]s for - * "/unknown" entries. - * - * Needed because mappers report failures only by returning `null`, and the - * `BackStackEntryMapper.map()`'s return type is a public API. - * - * **Custom `BackStackEntryMapper`s inherit reasons from any built-in mappers they delegate to** - * - * Built-in mappers [report] reasons before returning `null`. The converter [collect]s the last - * reason reported while the app's mapper runs, and records the reason only if the app's mapper - * returns `null`. As a result, a custom mapper that returns `null` after any built-in mapper - * returned `null` will record the built-in mapper's reason. - * - * Reasons are maintained per thread, so the converter collects only reasons reported on its own - * thread, where it runs the host app's mapper. If a custom mapper calls a built-in mapper on - * another thread, the reason will be lost and the entry will record `unmapped`. - */ -internal object UnknownEntryReasonReporter { - - private val reports = ThreadLocal() - - /** Reports why the built-in mapper that's about to return `null` can't name its entry. */ - fun report(reason: UnknownEntryReason) { - reports.set(reason) - } - - /** - * Runs [map] and returns its result with the last reason reported while it ran, or `null` if none - * was. Clears the report before and after, even if [map] throws, so a reason can't carry over to - * another entry. - */ - fun collect(map: () -> R): Collected { - reports.remove() - try { - val result = map() - return Collected(result, reports.get()) - } finally { - reports.remove() - } - } - - /** What [collect] returns: the mapper's [result] and the [reason] reported while it ran. */ - data class Collected(val result: R, val reason: UnknownEntryReason?) -} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md deleted file mode 100644 index 94d7d9d55cc..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# `io.sentry.compose.navigation3.internal.contract` - -Package contains internal values that are effectively part of our public contract because the Sentry UI displays them or they define -observable behavior. - -## Dependencies - -This package may ***not*** depend on any other `io.sentry.compose.navigation3` package, so that every other package can depend on it. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt new file mode 100644 index 00000000000..f7954b95866 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt @@ -0,0 +1,41 @@ +package io.sentry.compose.navigation3.internal.contract + +/** + * Passes the [UnknownEntryReason] a built-in mapper knows to the back stack converter, as the + * mapper reports a failure by returning `null`, which is public API. + * + * A built-in mapper [report]s the reason right before returning `null`, and the converter + * [collect]s it around each call to the app's mapper. So a custom mapper that forwards a built-in + * mapper's `null` forwards its reason too, while one that returns `null` itself reports nothing, + * and one that returns a name has its reason ignored. If a custom mapper calls built-in mappers + * several times for one entry, the last reason reported is kept. + * + * Kept per thread, as mappers run on the converter's thread. + */ +internal object UnknownEntryReasonReporter { + + private val reports = ThreadLocal() + + /** Reports why the built-in mapper that's about to return `null` can't name its entry. */ + fun report(reason: UnknownEntryReason) { + reports.set(reason) + } + + /** + * Runs [map] and returns its result with the last reason reported while it ran, or `null` if none + * was. Clears the report before and after, even if [map] throws, so a reason can't carry over to + * another entry. + */ + fun collect(map: () -> R): Collected { + reports.remove() + try { + val result = map() + return Collected(result, reports.get()) + } finally { + reports.remove() + } + } + + /** What [collect] returns: the mapper's [result] and the [reason] reported while it ran. */ + data class Collected(val result: R, val reason: UnknownEntryReason?) +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt index ba5553ac51a..f83a32a9eca 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt @@ -102,29 +102,6 @@ class PackageBoundariesTest { assertThat(violations).isEmpty() } - @Test - fun `the common package imports only the contract package from other Sentry navigation3 packages`() { - val commonSources = sources.filter { it.packageName.isIn(COMMON) } - - val violations = commonSources.importsMatching { - it.isIn(ROOT) && !it.isIn(COMMON) && !it.isIn(CONTRACT) - } - - assertThat(commonSources).isNotEmpty() - assertThat(violations).isEmpty() - } - - @Test - fun `the common package has no imports from Android or AndroidX`() { - // The kotlinx package, which may not import them, depends on the common package. - val commonSources = sources.filter { it.packageName.isIn(COMMON) } - - val violations = commonSources.importsMatching { it.isIn("android") || it.isIn("androidx") } - - assertThat(commonSources).isNotEmpty() - assertThat(violations).isEmpty() - } - // Check that the import reader finds the declarations the rules inspect. @Test @@ -191,7 +168,6 @@ class PackageBoundariesTest { const val KOTLINX = "$BACKSTACK.kotlinx" const val LIFECYCLE = "$ROOT.internal.lifecycle" const val CONTRACT = "$ROOT.internal.contract" - const val COMMON = "$ROOT.internal.common" const val MAPPER_FACTORY_PATH = "$SOURCE_ROOT/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt" diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt index 6e2e5f7854e..75dc883540a 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt @@ -10,10 +10,10 @@ import io.sentry.SentryOptions import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.io.StringWriter import kotlin.test.assertFailsWith import org.junit.Test diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt index 92a433e38d6..758ce9c864b 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt @@ -7,9 +7,9 @@ import io.sentry.SentryLevel import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper -import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.test.initForTest import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt index 0e2d510e024..c2be6bf0f59 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt @@ -3,8 +3,8 @@ package io.sentry.compose.navigation3.internal.backstack import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.eq diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt index 7a71d52b043..3cad4011b7b 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt @@ -4,10 +4,12 @@ import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.kotlinx.FakeCompatibilityProbe.Inconclusive import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_THREW import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.lang.annotation.AnnotationFormatError import java.lang.reflect.InvocationTargetException import kotlin.test.assertFailsWith @@ -61,64 +63,55 @@ class KotlinxBackStackEntryMapperTest { // Construction @Test - fun `logs nothing when created and the compatibility check passes`() { + fun `logs nothing when created and the compatibility probe finds kotlinx serialization compatible`() { val logger = mock() - KotlinxBackStackEntryMapper(logger = { logger }) + KotlinxBackStackEntryMapper(probe = FakeCompatibilityProbe(), logger = { logger }) verifyNoInteractions(logger) } @Test - fun `fails creation with the LinkageError the compatibility check throws`() { + fun `fails creation with the LinkageError the compatibility probe returns`() { val error = NoSuchMethodError("serializerOrNull") + val probe = FakeCompatibilityProbe(linkageError = error) val thrown = assertFailsWith { - KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { mock() }) + KotlinxBackStackEntryMapper(probe = probe, logger = { mock() }) } assertThat(thrown).isSameInstanceAs(error) } @Test - fun `logs nothing when the compatibility check throws a LinkageError`() { + fun `logs nothing when the compatibility probe returns a LinkageError`() { // BuiltInBackStackEntryMappers logs the error it catches, so the mapper doesn't log it too. val logger = mock() + val probe = FakeCompatibilityProbe(linkageError = NoSuchMethodError()) assertFailsWith { - KotlinxBackStackEntryMapper( - checkCompatibility = { throw NoSuchMethodError() }, - logger = { logger }, - ) + KotlinxBackStackEntryMapper(probe = probe, logger = { logger }) } verifyNoInteractions(logger) } @Test - fun `logs an IllegalArgumentException the compatibility check throws at debug level`() { - val error = IllegalArgumentException("lookup failed") - val logger = mock() - - KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { logger }) - - verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any()) - } - - @Test - fun `logs an IllegalStateException the compatibility check throws at debug level`() { - val error = IllegalStateException("lookup failed") + fun `logs the compatibility probe's error at debug level when the probe is inconclusive`() { + val error = IllegalStateException("probe failed") val logger = mock() + val probe = FakeCompatibilityProbe(inconclusive = Inconclusive(error)) - KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { logger }) + KotlinxBackStackEntryMapper(probe = probe, logger = { logger }) - verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any()) + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any(), eq(PROBE_THREW)) } @Test - fun `names entries when the compatibility check throws an IllegalStateException`() { - val fixture = Fixture.create(checkLinkage = { throw IllegalStateException() }) + fun `names entries when the compatibility probe is inconclusive`() { + val probe = FakeCompatibilityProbe(inconclusive = Inconclusive(IllegalStateException())) + val fixture = Fixture.create(probe = probe) val mapper = fixture.mapper val mapped = mapper.map(Detail("1")) @@ -126,18 +119,6 @@ class KotlinxBackStackEntryMapperTest { assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) } - @Test - fun `fails creation with another exception the compatibility check throws`() { - val error = UnsupportedOperationException() - - val thrown = - assertFailsWith { - KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { mock() }) - } - - assertThat(thrown).isSameInstanceAs(error) - } - // Naming @Test @@ -354,8 +335,8 @@ class KotlinxBackStackEntryMapperTest { } @Test - fun `returns null and logs the cause when the serializer lookup throws a wrapped LinkageError`() { - val cause = NoSuchMethodError("serializer() failed to link") + fun `returns null and logs the cause when the serializer lookup throws a wrapped fatal error`() { + val cause = OutOfMemoryError("serializer() failed fatally") val fixture = Fixture.create(lookUpSerializer = { throw InvocationTargetException(cause) }) val mapper = fixture.mapper @@ -365,49 +346,6 @@ class KotlinxBackStackEntryMapperTest { verifyLookUpFailureLogged(fixture.logger, cause) } - @Test - fun `propagates a wrapped fatal error the serializer lookup throws, unwrapped`() { - val cause = OutOfMemoryError("serializer() failed fatally") - val fixture = Fixture.create(lookUpSerializer = { throw InvocationTargetException(cause) }) - val mapper = fixture.mapper - - val thrown = assertFailsWith { mapper.map(Detail("1")) } - - assertThat(thrown).isSameInstanceAs(cause) - } - - @Test - fun `propagates a wrapped fatal error the serializer's descriptor throws, unwrapped`() { - val cause = OutOfMemoryError("descriptor failed fatally") - val serializer = - object : NamingOnlySerializer() { - override val descriptor: SerialDescriptor - get() = throw InvocationTargetException(cause) - } - val fixture = Fixture.create(lookUpSerializer = { serializer }) - val mapper = fixture.mapper - - val thrown = assertFailsWith { mapper.map(Detail("1")) } - - assertThat(thrown).isSameInstanceAs(cause) - } - - @Test - fun `restores the interrupt flag when the serializer lookup throws a wrapped InterruptedException`() { - val fixture = - Fixture.create(lookUpSerializer = { throw InvocationTargetException(InterruptedException()) }) - val mapper = fixture.mapper - - try { - val mapped = mapper.map(Detail("1")) - - assertThat(mapped).isNull() - assertThat(Thread.currentThread().isInterrupted).isTrue() - } finally { - Thread.interrupted() - } - } - @Test fun `returns null and logs the InvocationTargetException when the serializer lookup throws one without a cause`() { val error = InvocationTargetException(null) @@ -558,57 +496,6 @@ class KotlinxBackStackEntryMapperTest { assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) } - @Test - fun `looks up a type's serializer again after the serializer lookup is interrupted`() { - var hasThrown = false - val fixture = - Fixture.create( - lookUpSerializer = { - if (!hasThrown) { - hasThrown = true - throw InvocationTargetException(InterruptedException()) - } - Detail.serializer() - }, - ) - val mapper = fixture.mapper - try { - assertThat(mapper.map(Detail("1"))).isNull() - } finally { - Thread.interrupted() - } - - val mapped = mapper.map(Detail("2")) - - assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) - assertThat(fixture.lookedUpTypes).containsExactly(Detail::class.java, Detail::class.java) - } - - @Test - fun `checks a type's annotation again after the annotation check is interrupted`() { - var hasThrown = false - val fixture = - Fixture.create( - isAnnotatedSerializable = { - if (!hasThrown) { - hasThrown = true - throw InterruptedException() - } - true - }, - ) - val mapper = fixture.mapper - try { - assertThat(mapper.map(Detail("1"))).isNull() - } finally { - Thread.interrupted() - } - - val mapped = mapper.map(Detail("2")) - - assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) - } - @Test fun `logs each type that isn't annotated @Serializable once`() { val fixture = Fixture.create() @@ -846,7 +733,7 @@ class KotlinxBackStackEntryMapperTest { private constructor( lookUpSerializer: (Class<*>) -> KSerializer<*>?, isAnnotatedSerializable: ((Class<*>) -> Boolean)?, - checkLinkage: () -> Unit, + probe: CompatibilityProbe, ) { val logger = mock() val lookedUpTypes = mutableListOf>() @@ -859,18 +746,9 @@ class KotlinxBackStackEntryMapperTest { } mapper = if (isAnnotatedSerializable == null) { - KotlinxBackStackEntryMapper( - recordingLookUp, - checkCompatibility = checkLinkage, - logger = { logger }, - ) + KotlinxBackStackEntryMapper(recordingLookUp, probe = probe, logger = { logger }) } else { - KotlinxBackStackEntryMapper( - recordingLookUp, - isAnnotatedSerializable, - checkLinkage, - { logger }, - ) + KotlinxBackStackEntryMapper(recordingLookUp, isAnnotatedSerializable, probe, { logger }) } } @@ -878,8 +756,8 @@ class KotlinxBackStackEntryMapperTest { fun create( lookUpSerializer: (Class<*>) -> KSerializer<*>? = { SERIALIZERS[it] }, isAnnotatedSerializable: ((Class<*>) -> Boolean)? = null, - checkLinkage: () -> Unit = {}, - ) = Fixture(lookUpSerializer, isAnnotatedSerializable, checkLinkage) + probe: CompatibilityProbe = FakeCompatibilityProbe(), + ) = Fixture(lookUpSerializer, isAnnotatedSerializable, probe) } } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt deleted file mode 100644 index 5e64aeefd3b..00000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt +++ /dev/null @@ -1,63 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack.kotlinx - -import com.google.common.truth.Truth.assertThat -import kotlin.test.assertFailsWith -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.builtins.serializer -import kotlinx.serialization.descriptors.SerialDescriptor -import org.junit.Test -import org.mockito.kotlin.doThrow -import org.mockito.kotlin.mock - -/** - * Runs the default check against the kotlinx.serialization version on the test classpath, which CI - * also sets to the latest stable release with `-Pnav3TestKotlinx=latestStable`. - */ -class KotlinxCompatibilityCheckTest { - - @Test - fun `checkKotlinxCompatibility() - succeeds for the kotlinx serialization version on the classpath`() { - checkKotlinxCompatibility() - } - - @Test - fun `checkKotlinxCompatibility() - looks up only the built-in String serializer`() { - val lookedUpTypes = mutableListOf>() - - checkKotlinxCompatibility { type -> - lookedUpTypes += type - String.serializer() - } - - assertThat(lookedUpTypes).containsExactly(String::class.java) - } - - @Test - fun `checkKotlinxCompatibility() - throws the LinkageError the serializer lookup throws`() { - val error = NoSuchMethodError("serializerOrNull") - - val thrown = assertFailsWith { checkKotlinxCompatibility { throw error } } - - assertThat(thrown).isSameInstanceAs(error) - } - - @OptIn(ExperimentalSerializationApi::class) - @Test - fun `checkKotlinxCompatibility() - throws the LinkageError reading the serial name throws`() { - val error = NoSuchMethodError("getSerialName") - val descriptor = mock { on { serialName } doThrow error } - val serializer = - object : NamingOnlySerializer() { - override val descriptor = descriptor - } - - val thrown = assertFailsWith { checkKotlinxCompatibility { serializer } } - - assertThat(thrown).isSameInstanceAs(error) - } - - @Test - fun `checkKotlinxCompatibility() - succeeds without reading a serial name when no serializer is found`() { - checkKotlinxCompatibility { null } - } -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt new file mode 100644 index 00000000000..53e3e06f837 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt @@ -0,0 +1,172 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.ProbeClass +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.ProbeObject +import java.lang.reflect.InvocationTargetException +import kotlin.test.assertFailsWith +import org.junit.Test + +/** + * Runs the default probe against the kotlinx.serialization version on the test classpath, which CI + * also sets to the latest stable release with `-Pnav3TestKotlinx=latestStable`. + */ +class KotlinxCompatibilityProbeTest { + + // nameLookupLinkageError() + + @Test + fun `nameLookupLinkageError() - returns null without an inconclusive result for a compatible version`() { + val inconclusive = mutableListOf() + + val error = KotlinxCompatibilityProbe.nameLookupLinkageError { inconclusive += it } + + assertThat(error).isNull() + assertThat(inconclusive).isEmpty() + } + + @Test + fun `nameLookupLinkageError() - returns the LinkageError a probe type's serializer lookup throws`() { + val error = NoSuchMethodError("serializerOrNull") + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) { inconclusive += it } + + assertThat(returned).isSameInstanceAs(error) + assertThat(inconclusive).isEmpty() + } + + @Test + fun `nameLookupLinkageError() - returns the LinkageError a probe type's serializer throws through reflection`() { + val error = NoSuchMethodError("PluginGeneratedSerialDescriptor") + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw InvocationTargetException(error) }) { + inconclusive += it + } + + assertThat(returned).isSameInstanceAs(error) + assertThat(inconclusive).isEmpty() + } + + @Test + fun `nameLookupLinkageError() - reports another error a probe serializer throws via reflection as inconclusive`() { + val error = IllegalStateException("serializer failed") + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw InvocationTargetException(error) }) { + inconclusive += it + } + + assertThat(returned).isNull() + assertThat(inconclusive).containsExactly(error) + } + + @Test + fun `nameLookupLinkageError() - propagates a fatal error a probe type's serializer throws through reflection`() { + val error = OutOfMemoryError() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError( + { + throw InvocationTargetException(error) + }, + ) {} + } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `nameLookupLinkageError() - reports a non-fatal exception as inconclusive and returns null`() { + val error = IllegalStateException("lookup failed") + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) { inconclusive += it } + + assertThat(returned).isNull() + assertThat(inconclusive).containsExactly(error) + } + + @Test + fun `nameLookupLinkageError() - propagates a fatal error that isn't a LinkageError`() { + val error = OutOfMemoryError() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) {} + } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `nameLookupLinkageError() - reports a missing probe serializer as inconclusive without an error`() { + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError( + { type -> if (type == ProbeObject::class.java) null else reflectiveSerializerOrNull(type) }, + ) { + inconclusive += it + } + + assertThat(returned).isNull() + assertThat(inconclusive).containsExactly(null) + } + + @Test + fun `nameLookupLinkageError() - doesn't re-report onInconclusive's exception for a missing probe serializer`() { + val error = IllegalStateException("callback failed") + val inconclusive = mutableListOf() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError({ null }) { + inconclusive += it + throw error + } + } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(inconclusive).containsExactly(null) + } + + @Test + fun `nameLookupLinkageError() - doesn't re-report onInconclusive's exception for a lookup exception`() { + val lookupError = IllegalStateException("lookup failed") + val callbackError = IllegalArgumentException("callback failed") + val inconclusive = mutableListOf() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw lookupError }) { + inconclusive += it + throw callbackError + } + } + + assertThat(thrown).isSameInstanceAs(callbackError) + assertThat(inconclusive).containsExactly(lookupError) + } + + // Probe types + + @Test + fun `the serializer lookup names the probe's types`() { + // A probe type the lookup couldn't find would make the check pass without looking up a name. + val names = + listOf(ProbeClass::class.java, ProbeObject::class.java).map { + reflectiveSerializerOrNull(it)?.descriptor?.serialName + } + + assertThat(names) + .containsExactly(ProbeClass::class.qualifiedName, ProbeObject::class.qualifiedName) + .inOrder() + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt index b500c609c3c..a72868dd03f 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt @@ -3,13 +3,16 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.MIN_KOTLINX_SERIALIZATION_VERSION +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_SERIALIZER_NOT_FOUND +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_THREW import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND -import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE -import io.sentry.compose.navigation3.internal.common.MIN_KOTLINX_SERIALIZATION_VERSION import org.junit.Test import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -44,18 +47,34 @@ class KotlinxMapperDiagnosticsTest { assertThat(message.firstValue).contains("Use a custom BackStackEntryMapper") } - // compatibilityCheckFailed() + // inconclusiveProbe() @Test - fun `compatibilityCheckFailed() - logs the error at debug level`() { - val error = IllegalStateException("lookup failed") + fun `inconclusiveProbe() - logs the error at debug level with the reason that the probe threw`() { + val error = IllegalStateException("probe failed") + + diagnostics.inconclusiveProbe(error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), message.capture(), eq(PROBE_THREW)) + assertThat(message.firstValue) + .startsWith("Nav3 couldn't verify kotlinx.serialization support for name lookups") + } - diagnostics.compatibilityCheckFailed(error) + @Test + fun `inconclusiveProbe() - logs at debug level that no probe serializer was found when there's no error`() { + diagnostics.inconclusiveProbe(null) val message = argumentCaptor() - verify(logger).log(eq(SentryLevel.DEBUG), eq(error), message.capture()) + verify(logger) + .log( + eq(SentryLevel.DEBUG), + isNull(), + message.capture(), + eq(PROBE_SERIALIZER_NOT_FOUND), + ) assertThat(message.firstValue) - .startsWith("Nav3 couldn't verify kotlinx.serialization compatibility") + .startsWith("Nav3 couldn't verify kotlinx.serialization support for name lookups") } // unresolved() diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt index a2c998a76cd..bb3b036ed79 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt @@ -8,7 +8,6 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor -import kotlinx.serialization.serializerOrNull import org.junit.Test class KotlinxSerializerLookupTest { @@ -215,16 +214,6 @@ class KotlinxSerializerLookupTest { assertThat(serializer?.descriptor?.serialName).isEqualTo("PrivateObject") } - /** - * Fails once a kotlinx.serialization release can look up a private object's serializer itself, - * e.g., when CI runs the latest stable release. The private object fallback can then be removed - * once `kotlinxSerialization-floor` reaches that release. - */ - @Test - fun `kotlinx serialization's own lookup still throws IllegalAccessException for a private object`() { - assertFailsWith { serializerOrNull(PrivateObject::class.java) } - } - @Test fun `returns the serializer of a private @Serializable class`() { val serializer = reflectiveSerializerOrNull(PrivateClass::class.java) @@ -336,38 +325,38 @@ class KotlinxSerializerLookupTest { } @Test - fun `throws an interruption of a class's serializer construction wrapped in an InvocationTargetException`() { - val thrown = - assertFailsWith { - reflectiveSerializerOrNull(InterruptedConstruction::class.java) - } - - assertThat(thrown).hasCauseThat().isInstanceOf(InterruptedException::class.java) + fun `restores the interrupt flag when a class's serializer construction is interrupted`() { + try { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(InterruptedConstruction::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(InterruptedException::class.java) + assertThat(Thread.currentThread().isInterrupted).isTrue() + } finally { + Thread.interrupted() + } } @Test - fun `throws a class's fatal serializer initializer error wrapped in an InvocationTargetException`() { + fun `propagates a class's fatal serializer initializer error unwrapped`() { val thrown = - assertFailsWith { + assertFailsWith { reflectiveSerializerOrNull(FatallyUninitializable::class.java) } - assertThat(thrown).hasCauseThat().isInstanceOf(OutOfMemoryError::class.java) - assertThat(thrown) - .hasCauseThat() - .hasMessageThat() - .isEqualTo("class serializer init failed fatally") + assertThat(thrown).hasMessageThat().isEqualTo("class serializer init failed fatally") } @Test - fun `throws a private object's fatal serializer initializer error wrapped in an InvocationTargetException`() { + fun `propagates a private object's fatal serializer initializer error unwrapped`() { val thrown = - assertFailsWith { + assertFailsWith { reflectiveSerializerOrNull(PrivateFatal::class.java) } - assertThat(thrown).hasCauseThat().isInstanceOf(OutOfMemoryError::class.java) - assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer init failed fatally") + assertThat(thrown).hasMessageThat().isEqualTo("serializer init failed fatally") } // Private object lookups that find no serializer diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt index d06ebe92abb..1a1339a038c 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -20,3 +20,24 @@ internal abstract class NamingOnlySerializer : KSerializer { override fun deserialize(decoder: Decoder): T = throw UnsupportedOperationException() } + +/** + * A compatibility probe that finds kotlinx.serialization compatible by default. Set [linkageError] + * to report an incompatible version, or [inconclusive] to report an inconclusive result. + */ +internal class FakeCompatibilityProbe( + private val linkageError: LinkageError? = null, + private val inconclusive: Inconclusive? = null, +) : CompatibilityProbe { + + override fun invoke(onInconclusive: (Throwable?) -> Unit): LinkageError? { + linkageError?.let { + return it + } + inconclusive?.let { onInconclusive(it.error) } + return null + } + + /** Why the probe is inconclusive: [error], or `null` if a probe serializer wasn't found. */ + class Inconclusive(val error: Throwable?) +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt similarity index 95% rename from sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt rename to sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt index 7c19e9e70c9..eea71458579 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt @@ -1,8 +1,7 @@ -package io.sentry.compose.navigation3.internal.common +package io.sentry.compose.navigation3.internal.contract import com.google.common.truth.Truth.assertThat -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter.Collected -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter.Collected import kotlin.concurrent.thread import kotlin.test.assertFailsWith import org.junit.Test From ae14145a6480d395cda378c866da4200cdf30ac0 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 27 Nov 2026 18:18:55 +0100 Subject: [PATCH 2/3] 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) { From 001bcd0d38f4f7729bb44e76ad42be6981132a5c Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 11:01:58 +0100 Subject: [PATCH 3/3] test(nav3): Tighten the R8 check and match it to the compatibility check - Reject a named entry that has an unknown_entry_reason, and any entry that has arguments. - Rename ProbeLogChecks to CompatibilityLogChecks and match the compatibility check's messages. - Drop the README's Dependabot cooldown claim, as dependabot.yml sets no cooldown. Co-Authored-By: Claude Opus 5.5 --- .../README.md | 4 +- .../r8/BuiltInBackStackMappersActivity.kt | 18 +- ...LogChecks.kt => CompatibilityLogChecks.kt} | 26 +-- .../nav3/Nav3PerformanceControls.kt | 12 +- sentry-android-navigation3/proguard-rules.pro | 9 - .../navigation3/BackStackEntryMapper.kt | 40 +++- .../internal/backstack/BackStackConverter.kt | 2 +- .../backstack/BuiltInBackStackEntryMappers.kt | 6 +- .../kotlinx/KotlinxBackStackEntryMapper.kt | 92 ++++----- .../kotlinx/KotlinxCompatibilityCheck.kt | 24 +++ .../kotlinx/KotlinxCompatibilityProbe.kt | 134 -------------- .../kotlinx/KotlinxSerializerLookup.kt | 27 +-- .../internal/backstack/kotlinx/README.md | 2 +- .../navigation3/internal/common/README.md | 9 + .../common/SerializationCompatibility.kt | 15 ++ .../common/UnknownEntryReasonReporter.kt | 49 +++++ .../navigation3/internal/contract/README.md | 8 + .../contract/UnknownEntryReasonReporter.kt | 41 ----- .../navigation3/PackageBoundariesTest.kt | 24 +++ .../backstack/BackStackConverterTest.kt | 2 +- .../BuiltInBackStackEntryMappersTest.kt | 4 +- .../UnavailableBackStackEntryMapperTest.kt | 2 +- .../KotlinxBackStackEntryMapperTest.kt | 174 +++++++++++++++--- .../kotlinx/KotlinxCompatibilityCheckTest.kt | 63 +++++++ .../kotlinx/KotlinxCompatibilityProbeTest.kt | 172 ----------------- .../kotlinx/KotlinxMapperDiagnosticsTest.kt | 35 +--- .../kotlinx/KotlinxSerializerLookupTest.kt | 47 +++-- .../backstack/kotlinx/KotlinxTestEntries.kt | 21 --- .../UnknownEntryReasonReporterTest.kt | 5 +- 29 files changed, 514 insertions(+), 553 deletions(-) rename sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/{ProbeLogChecks.kt => CompatibilityLogChecks.kt} (78%) create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt delete mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt rename sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/{contract => common}/UnknownEntryReasonReporterTest.kt (95%) 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 3b268c3d4c9..70d3a616ec5 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 @@ -3,7 +3,7 @@ Checks that `BackStackEntryMapper.SerialName` works after R8 obfuscation: - The names and `unknown_entry_reason`s that `SentryNavEffect` records in the `Navigation` context match expectations. -- The compatibility probe succeeds conclusively. +- The mapper's kotlinx.serialization compatibility check passes. - 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 @@ -24,7 +24,7 @@ CI also runs the module's unit tests against latestStable. ## Handle a failing update -Dependabot updates `kotlinxSerialization-latestStable` after a three-day cooldown. +Dependabot updates `kotlinxSerialization-latestStable`. **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 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 c8dd1f9ef09..c201a87059e 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 @@ -22,7 +22,7 @@ class BuiltInBackStackMappersActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - // Before the mapper's first map() call, which runs its compatibility probe. + // Before the mapper's first map() call, which runs its compatibility check. val logger = RecordingLogger() val recorder = BackStackRecorder() initSentry(this, logger, recorder) @@ -77,14 +77,14 @@ class BuiltInBackStackMappersActivity : ComponentActivity() { } else { expectations.zip(recorded).forEach { (expectation, entry) -> val unnamed = entry.name == UNKNOWN + val namedAsExpected = + expectation.expected != null && + entry.name == "/${expectation.expected}" && + entry.unknownEntryReason == null val unnamedAsExpected = unnamed && entry.unknownEntryReason in expectation.unknownEntryReasons - val passed = - if (expectation.expected == null) { - unnamedAsExpected - } else { - (entry.name == "/${expectation.expected}" && !entry.hasArguments) || unnamedAsExpected - } + // SerialName never returns arguments, so no entry it maps may have any. + val passed = !entry.hasArguments && (namedAsExpected || unnamedAsExpected) val fellBack = expectation.expected != null && unnamedAsExpected if (!passed) failures++ @@ -96,6 +96,8 @@ class BuiltInBackStackMappersActivity : ComponentActivity() { (if (entry.hasArguments) " (has arguments)" else "") + (if (unnamed) { " reason=${entry.unknownEntryReason} (expected ${expectation.unknownEntryReasons})" + } else if (entry.unknownEntryReason != null) { + " reason=${entry.unknownEntryReason} (expected none)" } else { "" }) + @@ -103,7 +105,7 @@ class BuiltInBackStackMappersActivity : ComponentActivity() { } } - for (check in minificationChecks() + probeLogChecks(logger)) { + for (check in minificationChecks() + compatibilityLogChecks(logger)) { if (!check.passed) failures++ lines += "${if (check.passed) "PASS" else "FAIL"} ${check.description}" } 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/CompatibilityLogChecks.kt similarity index 78% rename from sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt rename to sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/CompatibilityLogChecks.kt index 69322c9d7b3..5a7c86951b6 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/CompatibilityLogChecks.kt @@ -7,8 +7,8 @@ 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. + * Records the messages the SDK logs, so the check can tell whether the mapper's compatibility check + * passed under R8. */ class RecordingLogger : ILogger { @@ -36,7 +36,7 @@ class RecordingLogger : ILogger { 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. */ + /** Appends [throwable] and its causes, so a failed check shows why the SDK's check failed. */ private fun withError(message: String, throwable: Throwable?): String = if (throwable == null) message else message + generateSequence(throwable) { it.cause }.take(5).joinToString { " | $it" } @@ -56,15 +56,15 @@ fun initSentry(context: Context, logger: ILogger, recorder: BackStackRecorder) { } /** - * Checks that the compatibility probe completed conclusively under R8. + * Checks that the mapper's compatibility check passed 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. + * Names alone aren't enough: if the check fails without a LinkageError, the mapper still names + * entries, but it would no longer 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. + * confirms logging works; detecting a failed check relies on fixed message prefixes. */ -fun probeLogChecks(logger: RecordingLogger): List { +fun compatibilityLogChecks(logger: RecordingLogger): List { val messages = logger.messages.toList() return listOf( Check( @@ -72,7 +72,7 @@ fun probeLogChecks(logger: RecordingLogger): List { messages.any { NotSerializable::class.java.name in it }, ), ) + - PROBE_MESSAGE_PREFIXES.map { prefix -> + COMPATIBILITY_MESSAGE_PREFIXES.map { prefix -> val logged = messages.firstOrNull { it.startsWith(prefix) } Check( "nothing logged \"$prefix…\"" + if (logged != null) " (logged: $logged)" else "", @@ -82,13 +82,13 @@ fun probeLogChecks(logger: RecordingLogger): List { } /** - * 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. + * The prefixes of the messages the mapper logs when its compatibility check fails, or a built-in + * mapper can't be created. * * See `KotlinxMapperDiagnostics` and `BuiltInBackStackEntryMappers` in sentry-android-navigation3. */ -private val PROBE_MESSAGE_PREFIXES = +private val COMPATIBILITY_MESSAGE_PREFIXES = listOf( - "Nav3 couldn't verify kotlinx.serialization support", + "Nav3 couldn't verify kotlinx.serialization compatibility", "Nav3 built-in mapper creation failed", ) 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 e10cce8bf96..b5f432009bd 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 @@ -53,6 +53,8 @@ internal class Nav3PerformanceState( var extractorMode by mutableStateOf(Nav3PerformanceExtractorMode.NORMAL) var argumentMode by mutableStateOf(Nav3PerformanceArgumentMode.FLAT) var mapperMode by mutableStateOf(Nav3PerformanceMapperMode.CUSTOM) + private set + var integrationMode by mutableStateOf(Nav3PerformanceIntegrationMode.FULL_STACK) private set @@ -179,6 +181,14 @@ internal class Nav3PerformanceState( suppressNextDestinationChange = true } + /** Resets the counters on a change, as each mapper records different measurements. */ + fun updateMapperMode(mode: Nav3PerformanceMapperMode) { + if (mapperMode != mode) { + mapperMode = mode + resetCounters() + } + } + fun updateIntegrationMode(mode: Nav3PerformanceIntegrationMode) { if (integrationMode != mode) { discardNextSentryNavEffectMeasurement = true @@ -896,7 +906,7 @@ internal fun Nav3PerformancePanel( enabled = !state.performanceRunActive, options = Nav3PerformanceMapperMode.entries.map { mode -> - mode.label to { state.mapperMode = mode } + mode.label to { state.updateMapperMode(mode) } }, ) diff --git a/sentry-android-navigation3/proguard-rules.pro b/sentry-android-navigation3/proguard-rules.pro index d9de2ff242b..b34c23cc870 100644 --- a/sentry-android-navigation3/proguard-rules.pro +++ b/sentry-android-navigation3/proguard-rules.pro @@ -8,15 +8,6 @@ ##---------------Begin: proguard configuration for kotlinx.serialization ---------- -# The kotlinx.serialization compatibility probe looks up this SDK-owned fixture's serializer via reflection, as the built-in mappers look -# up those of apps' back stack entries. kotlinx.serialization's R8 rules before 1.8.0 keep an object's serializer() only while its INSTANCE -# field is kept, and R8 full mode removes INSTANCE here, as the SDK only refers to the object's class. The probe would then be inconclusive -# for object lookups. --keepclassmembers class io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe$ProbeObject { - public static ** INSTANCE; - kotlinx.serialization.KSerializer serializer(...); -} - # Serial names survive R8 minification because Kotlin's serialization compiler plugin fixes them at compile time. Our built-in mapper # fallback for private `@Serializable` objects relies on members preserved by kotlinx.serialization's own consumer rules. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt index 3c6b0ac1357..c24ed39db13 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt @@ -6,8 +6,7 @@ import org.jetbrains.annotations.ApiStatus /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * See [SerialName] for an out-of-the-box mapper, or else provide your own. (Custom implementations - * can optionally fall back to `SerialName` for any entries that don't have to be special-cased.) + * See [SerialName] for an out-of-the-box mapper, or else provide your own. * * **Privacy / PII** * @@ -31,12 +30,13 @@ import org.jetbrains.annotations.ApiStatus * **Names fall back to "/unknown"** * * If [map] throws, returns `null`, or returns a blank [name][SentryBackStackEntry.name], Sentry - * records the destination as "/unknown". Doing so signals that name extraction needs to be fixed - * while avoiding misleading gaps in nav state. + * records the destination as "/unknown". (The sole exception is if [map] throws a fatal error, as + * fatal errors like [OutOfMemoryError] or [LinkageError] are propagated rather than being caught.) * - * For instance, if a user navigates from /home -> /detail -> /settings, but the mapper for /detail - * throws, the back stack record will be /home -> /unknown -> /settings rather than /home -> - * /settings. + * An "/unknown" entry signals that name extraction needs to be fixed while avoiding misleading gaps + * in nav state. For instance, if a user navigates from /home -> /detail -> /settings, but the + * mapper for /detail throws, the back stack record will be /home -> /unknown -> /settings rather + * than /home -> /settings. * * Each "/unknown" entry records why it has no name under `unknown_entry_reason` (e.g., * `"mapping_failed"` if [map] threw). @@ -78,6 +78,32 @@ import org.jetbrains.annotations.ApiStatus * * In that case, it records why under `dropped_by_sentry` in the entry's arguments (e.g., * `"max_argument_count_exceeded"`). + * + * **Delegating to built-in mappers** + * + * Custom `BackStackEntryMapper`s may delegate to built-in mappers for entries the host app doesn't + * need to special-case: + * ```kotlin + * val mapper = BackStackEntryMapper { entry -> + * when (entry) { + * // Special-case any entries with sensitive info. + * is Cart -> SentryBackStackEntry( + * name = Cart.serializer().descriptor.serialName, + * arguments = mapOf("cartId" to entry.cartId), + * ) + * + * // Consider falling back to a built-in mapper for the rest. + * else -> BackStackEntryMapper.SerialName.map(entry) + * } + * } + * ``` + * + * Note: If a custom mapper calls a built-in mapper that returns `null`, and then the custom mapper + * returns `null` itself, the built-in mapper's `unknown_entry_reason` will be recorded. + * + * Be sure to invoke built-in mappers on the same thread that calls the custom mapper's [map] + * method, or else the original `unknown_entry_reason` may be lost and recorded as `"unmapped"` + * instead. */ @ApiStatus.Experimental public fun interface BackStackEntryMapper { diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt index 90c65bc3f41..9285537508e 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt @@ -5,6 +5,7 @@ import io.sentry.ILogger import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES @@ -16,7 +17,6 @@ import io.sentry.compose.navigation3.internal.contract.TRANSACTION_ARGUMENTS_KEY import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason.Companion.UNKNOWN_ENTRY_REASON_KEY -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.util.ExceptionUtils import java.util.IdentityHashMap diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt index 85a17ca3f1d..3fd1247a200 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt @@ -8,10 +8,10 @@ import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.util.Collections import java.util.concurrent.ConcurrentHashMap @@ -51,8 +51,6 @@ internal object BuiltInBackStackEntryMappers { logger() .log( WARNING, - // Note: The compiler inlines INCOMPATIBLE_KOTLINX_ADVICE, and its use here doesn't access - // any kotlinx.serialization code. "Nav3 built-in mapper creation failed. Using $UNKNOWN_ENTRY_NAME for all entries. See " + "the attached error. $INCOMPATIBLE_KOTLINX_ADVICE", e, 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 0a852bf11ba..07cd2ffc47d 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 @@ -5,9 +5,10 @@ import io.sentry.SentryLevel.DEBUG import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.util.ExceptionUtils import java.lang.reflect.GenericSignatureFormatError import java.lang.reflect.InvocationTargetException @@ -23,9 +24,7 @@ internal class KotlinxBackStackEntryMapper( * Returns the serializer of a back stack entry's `@Serializable` class, or `null` if there's none * (e.g. for a generic class). Only called for classes marked `@Serializable`. * - * May throw, as the lookup can run the app's serializer code for the first time. Must rethrow a - * fatal error unwrapped if reflection wrapped it in an [InvocationTargetException], as - * [reflectiveSerializerOrNull] does, since the mapper treats every wrapped error as non-fatal. + * May throw, as the lookup can run the app's serializer code for the first time. */ private val lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, /** @@ -34,9 +33,8 @@ internal class KotlinxBackStackEntryMapper( * May throw, as reading the class's annotations can fail. */ private val isAnnotatedSerializable: (Class<*>) -> Boolean = serializableAnnotationCheck(), - probe: CompatibilityProbe = { onInconclusive -> - KotlinxCompatibilityProbe.nameLookupLinkageError(onInconclusive = onInconclusive) - }, + /** Throws a [LinkageError] if the app's kotlinx.serialization version is incompatible. */ + checkCompatibility: () -> Unit = { checkKotlinxCompatibility() }, logger: () -> ILogger, ) : BackStackEntryMapper { @@ -47,9 +45,18 @@ internal class KotlinxBackStackEntryMapper( private val diagnostics = KotlinxMapperDiagnostics(logger) init { - // Throws if the host app uses an incompatible kotlinx-serialization-core version. Causes - // creation to fail and every back stack entry to be recorded as "/unknown". - probe { error -> diagnostics.inconclusiveProbe(error) }?.let { throw it } + // A LinkageError fails creation, so every back stack entry is recorded as "/unknown" with + // kotlinx_serialization_version. + try { + checkCompatibility() + } catch (e: IllegalArgumentException) { + // kotlinx.serialization reports lookup failures as SerializationException, an + // IllegalArgumentException. Neither it nor an IllegalStateException means the version is + // incompatible, so we name entries and handle any failure per type. + diagnostics.compatibilityCheckFailed(e) + } catch (e: IllegalStateException) { + diagnostics.compatibilityCheckFailed(e) + } } override fun map(backStackEntry: Any): SentryBackStackEntry? { @@ -68,10 +75,20 @@ internal class KotlinxBackStackEntryMapper( return SentryBackStackEntry(cached.name) } - private fun cachedType(type: Class<*>): CachedType = - // getOrPut may look up a type more than once if threads race on its first entry. That can cause - // a failed lookup to be logged more than once, but only one result will ever be cached. - types.getOrPut(type) { lookUp(type) } + private fun cachedType(type: Class<*>): CachedType { + types[type]?.let { + return it + } + + // Threads that race on a type's first entry may each look it up and log a failure, but only + // one result is ever cached. + val result = lookUp(type) + // A lookup that failed on an interrupted thread may succeed later, so we don't cache it. + if (result is CachedType.Unresolved && Thread.currentThread().isInterrupted) { + return result + } + return types.putIfAbsent(type, result) ?: result + } /** * Looks up [type]'s serializer and serial name. Logs if the serializer isn't available or the @@ -95,8 +112,14 @@ internal class KotlinxBackStackEntryMapper( CachedType.Resolved(serializer.descriptor.serialName) } } catch (e: InvocationTargetException) { - // The type's serializer() threw, e.g., a custom serializer's ExceptionInInitializerError. - unresolved(type, e.cause ?: e) + // The type's serializer() or descriptor threw through reflection, e.g., a custom serializer's + // ExceptionInInitializerError. A wrapped LinkageError fails only this type, so it isn't + // rethrown as fatal. + val cause = e.cause + if (cause != null && cause !is LinkageError) { + ExceptionUtils.rethrowIfFatal(cause) + } + unresolved(type, cause ?: e) } catch (e: LinkageError) { // Construction checks the library itself, so this likely comes from the type's serializer, // e.g., one compiled against another kotlinx.serialization version. It fails only this type. @@ -215,8 +238,8 @@ internal class KotlinxBackStackEntryMapper( * * Only decides what's logged. Whether a type is looked up again is up to the mapper. * - * The R8 check matches the start of [inconclusiveProbe]'s message, so rewording it requires - * updating `ProbeLogChecks.kt` + * The R8 check matches the start of [compatibilityCheckFailed]'s message, so rewording it requires + * updating `CompatibilityLogChecks.kt` * (`sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check`). */ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { @@ -244,18 +267,17 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { } /** - * Logs that the probe couldn't verify support for name lookups, due to [error] or a missing probe - * serializer if the error is `null`. The mapper handles subsequent failures per type. + * Logs that the compatibility check threw [error], which doesn't mean kotlinx.serialization is + * incompatible. The mapper handles subsequent failures per type. */ - fun inconclusiveProbe(error: Throwable?) { - // DEBUG b/c an inconclusive probe doesn't affect what's recorded. + fun compatibilityCheckFailed(error: RuntimeException) { + // DEBUG b/c a failed check doesn't affect what's recorded. logger() .log( DEBUG, error, - "Nav3 couldn't verify kotlinx.serialization support for name lookups because %s. " + + "Nav3 couldn't verify kotlinx.serialization compatibility (see the attached error). " + "Handling failures per entry type.", - if (error != null) PROBE_THREW else PROBE_SERIALIZER_NOT_FOUND, ) } @@ -271,7 +293,8 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { val advice = // An ExceptionInInitializerError only means the app's own initializer threw an exception. if (error is LinkageError && error !is ExceptionInInitializerError) { - // The probe can miss an incompatible version, which then fails every type one at a time. + // E.g., an app serializer compiled against a newer kotlinx.serialization than the app + // ships. "See the attached error. If all types fail, kotlinx.serialization may be incompatible. " + INCOMPATIBLE_KOTLINX_ADVICE } else if (error != null) { @@ -291,28 +314,9 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { companion object { - /** - * The oldest kotlinx.serialization version [KotlinxBackStackEntryMapper] supports. - * - * Must match `kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml`. - */ - const val MIN_KOTLINX_SERIALIZATION_VERSION: String = "1.7.3" - - const val INCOMPATIBLE_KOTLINX_ADVICE: String = - "Requires kotlinx.serialization $MIN_KOTLINX_SERIALIZATION_VERSION or later. " + - "Upgrade kotlinx.serialization or the Sentry SDK. If both are current, report this at " + - "https://github.com/getsentry/sentry-java/issues/new/choose. Use a custom " + - "BackStackEntryMapper as a workaround." - /** Why a type can't be named, if reading its annotations, serializer, or descriptor threw. */ const val LOOK_UP_FAILED: String = "reading its annotations, serializer, or descriptor failed" - /** Why the compatibility probe was inconclusive, if it threw. */ - const val PROBE_THREW: String = "the compatibility probe threw (see the attached error)" - - /** Why the compatibility probe was inconclusive, if a probe type's serializer wasn't found. */ - const val PROBE_SERIALIZER_NOT_FOUND: String = "a probe serializer wasn't found" - /** Why a type can't be named, if its serializer lookup found none without throwing. */ const val SERIALIZER_NOT_FOUND: String = "no serializer was found (the type may be generic or require R8 keep rules)" diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt new file mode 100644 index 00000000000..ed5ac25d540 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt @@ -0,0 +1,24 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer + +/** + * Verifies that the host app's `kotlinx-serialization-core` version is compatible with the APIs + * used by our built-in `BackStackEntryMapper`s. + * + * Does so by calling each kotlinx.serialization API that [KotlinxBackStackEntryMapper] calls, looks + * up the built-in `String` serializer, and reads its serial name. + * + * Throws a [LinkageError] if the app's `kotlinx-serialization-core` version is incompatible. A + * `LinkageError` thrown here is conclusive: unlike looking up an app type's serializer, the check + * runs no app code and no serializer generated by a compiler plugin, either of which could throw + * one for reasons that affect only its own type. + */ +internal fun checkKotlinxCompatibility( + lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, +) { + lookUpSerializer(String::class.java)?.descriptor?.serialName +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt deleted file mode 100644 index 65af42b4f6f..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt +++ /dev/null @@ -1,134 +0,0 @@ -@file:OptIn(ExperimentalSerializationApi::class) - -package io.sentry.compose.navigation3.internal.backstack.kotlinx - -import io.sentry.compose.navigation3.BackStackEntryMapper -import io.sentry.util.ExceptionUtils -import java.lang.reflect.InvocationTargetException -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializable - -/** - * Checks whether the app's `kotlinx-serialization-core` version successfully links against the APIs - * used by [KotlinxBackStackEntryMapper]. It does so via two built-in probe types ([ProbeClass] and - * [ProbeObject]). - * - * **Disambiguating serializer errors from library incompatibility** - * - * Without a check like this, `KotlinxBackStackEntryMapper` would have to infer an incompatible - * `kotlinx-serialization-core` version from [LinkageError]s thrown while handling the host app's - * own back stack entry types. But such errors can also come from the host app's serializer code, - * and should therefore only fail for the entry types that can't be deserialized. `ProbeClass` and - * `ProbeObject` don't execute any host app code, so a `LinkageError` while handling them means the - * app's `kotlinx-serialization-core` version is incompatible. - * - * Note: Only a `LinkageError` is conclusive, including one that reflection wrapped in an - * [InvocationTargetException] because a probe type's serializer threw it. Any other failure, or a - * probe type whose serializer can't be found, is ambiguous: it's reported to the caller's - * `onInconclusive` and otherwise ignored, as a real type that hits the same failure is handled and - * logged on its own. - */ -internal object KotlinxCompatibilityProbe { - - /** - * Checks `kotlinx-serialization-core` compatibility by retrieving serializers for [ProbeClass] - * and [ProbeObject] through [lookUpSerializer] and reading their serial names. - * - * Confines itself to methods used by our built-in [BackStackEntryMapper]s to avoid being disabled - * by incompatibilities from irrelevant APIs. - * - * Returns a [LinkageError] upon incompatibility, or `null` upon success or an inconclusive - * result. Additionally reports inconclusive results through [onInconclusive], passing the cause - * or `null` if a serializer is unavailable. - */ - fun nameLookupLinkageError( - lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, - onInconclusive: (Throwable?) -> Unit, - ): LinkageError? { - var isSerializerMissing = false - - val error = - probe(onInconclusive) { - for (type in listOf(ProbeClass::class.java, ProbeObject::class.java)) { - val descriptor = lookUpSerializer(type)?.descriptor - if (descriptor == null) { - isSerializerMissing = true - } else { - descriptor.serialName - } - } - } - - // Call outside probe() so an exception from onInconclusive isn't caught and reported back to - // the same callback. If a serializer is missing, the remaining lookup steps cannot be checked - // for that type. - if (isSerializerMissing) { - onInconclusive(null) - } - return error - } - - /** - * Runs [check], returning any [LinkageError] and rethrowing fatal errors. Returns `null` if the - * check succeeds or is inconclusive. - * - * Reports other errors to [onInconclusive], passing the cause. - */ - private inline fun probe( - onInconclusive: (Throwable) -> Unit, - check: () -> Unit, - ): LinkageError? = - try { - check() - null - } catch (e: LinkageError) { - e - } catch (e: InvocationTargetException) { - // A probe type's serializer runs only SDK and kotlinx.serialization code, so a LinkageError - // it throws means the library is incompatible. (The lookup keeps such errors wrapped, as an - // app type's serializer could throw them for unrelated reasons.) - val cause = e.cause - if (cause is LinkageError) { - cause - } else { - val error = cause ?: e - ExceptionUtils.rethrowIfFatal(error) - onInconclusive(error) - null - } - } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { - // Broad because the app's kotlinx.serialization version may throw anything. Only - // LinkageError confirms incompatibility. Other non-fatal failures are inconclusive. - // Failures for actual back stack types are handled and logged per type. - ExceptionUtils.rethrowIfFatal(t) - onInconclusive(t) - null - } - - /** - * A known serializable type used to test whether the app's kotlinx.serialization version supports - * serializer lookup, without running host app code. - * - * Internal visibility lets the probe look up its serializer the same way - * [KotlinxBackStackEntryMapper] looks up serializers for the host app's public back stack entry - * types. - */ - @Serializable internal data class ProbeClass(val name: String = "probe") - - /** - * A known serializable object used to test serializer lookup for the host app's object-based back - * stack entries. This lookup reads the object's singleton instance. - */ - @Serializable internal object ProbeObject -} - -/** - * Checks whether the app's `kotlinx-serialization-core` version supports retrieving serializers and - * reading their serial names. Returns a [LinkageError] for incompatibility, or `null` for success - * or an inconclusive check. - * - * Reports inconclusive results through `onInconclusive`, passing the error or `null` if a - * serializer couldn't be found. - */ -internal typealias CompatibilityProbe = (onInconclusive: (Throwable?) -> Unit) -> LinkageError? diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt index 310007c04e5..919c915535c 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt @@ -1,6 +1,5 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx -import io.sentry.util.ExceptionUtils import java.lang.reflect.InvocationTargetException import kotlinx.serialization.KSerializer import kotlinx.serialization.serializerOrNull @@ -10,32 +9,24 @@ import kotlinx.serialization.serializerOrNull * Extends [serializerOrNull] to support private `@Serializable` objects. Also supports built-in * types and unannotated enums. * - * May execute serializer code and throw. Unwraps fatal causes such as [OutOfMemoryError] from - * [InvocationTargetException] so that fatal-error checks can recognize them. Keeps [LinkageError] - * causes wrapped because they affect only this type. + * May execute serializer code and throw. What that code throws through reflection, including fatal + * errors such as [OutOfMemoryError], arrives wrapped in an [InvocationTargetException]. */ @Suppress("SwallowedException") internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = try { - try { - serializerOrNull(type) - } catch (_: IllegalAccessException) { - // kotlinx.serialization reads a serializable object's INSTANCE field without making it - // accessible, which will fail for private objects. - privateObjectSerializerOrNull(type) - } - } catch (e: InvocationTargetException) { - val cause = e.cause - if (cause != null && cause !is LinkageError) { - ExceptionUtils.rethrowIfFatal(cause) - } - throw e + serializerOrNull(type) + } catch (_: IllegalAccessException) { + // kotlinx.serialization reads a serializable object's INSTANCE field without making it + // accessible, which will fail for private objects. + privateObjectSerializerOrNull(type) } /** * Uses reflection to look up the serializer of a private `@Serializable object` through the members * the serialization compiler plugin generates for it. (kotlinx.serialization's consumer R8 rules - * keep both members.) + * keep both members.) kotlinx.serialization's own object lookup reads the same two members, so this + * fallback can break only if that lookup breaks too. * * Propagates any exception thrown by the reflective lookup. */ diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md index ddadd318837..ba524b283c2 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md @@ -42,7 +42,7 @@ Recommended rules for raising the floor: - Raise it in a reviewed change of its own, with a CHANGELOG entry and a corresponding update to the [Sentry Nav3 docs](https://docs.sentry.io/platforms/android/integrations/navigation/#navigation-3). -- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `KotlinxBackStackEntryMapper.kt` to match. A unit test will fail if the two differ. +- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `internal/common/KotlinxSerializationSupport.kt` to match. A unit test will fail if the two differ. ## Minification diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md new file mode 100644 index 00000000000..b1eb7e8c1db --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md @@ -0,0 +1,9 @@ +# `io.sentry.compose.navigation3.internal.common` + +Package contains internal code that more than one `io.sentry.compose.navigation3` package needs, but that isn't part of what the Sentry UI +shows (see the `contract` package). + +## Dependencies + +This package may depend only on the `contract` package among `io.sentry.compose.navigation3` packages. As `backstack.kotlinx` depends on it, +it may ***not*** depend on Android, AndroidX, or kotlinx.serialization. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt new file mode 100644 index 00000000000..9326a8a9ff4 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt @@ -0,0 +1,15 @@ +package io.sentry.compose.navigation3.internal.common + +/** + * The oldest kotlinx.serialization version the built-in mappers support. + * + * Must match `kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml`. + */ +internal const val MIN_KOTLINX_SERIALIZATION_VERSION = "1.7.3" + +/** Advice logged when the app's kotlinx.serialization version may be incompatible. */ +internal const val INCOMPATIBLE_KOTLINX_ADVICE = + "Requires kotlinx.serialization $MIN_KOTLINX_SERIALIZATION_VERSION or later. " + + "Upgrade kotlinx.serialization or the Sentry SDK. If both are current, report this at " + + "https://github.com/getsentry/sentry-java/issues/new/choose. Use a custom " + + "BackStackEntryMapper as a workaround." diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt new file mode 100644 index 00000000000..d2e97d6f209 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt @@ -0,0 +1,49 @@ +package io.sentry.compose.navigation3.internal.common + +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason + +/** + * A side channel for built-in `BackStackEntryMapper`s to report [UnknownEntryReason]s for + * "/unknown" entries. + * + * Needed because mappers report failures only by returning `null`, and the + * `BackStackEntryMapper.map()`'s return type is a public API. + * + * **Custom `BackStackEntryMapper`s inherit reasons from any built-in mappers they delegate to** + * + * Built-in mappers [report] reasons before returning `null`. The converter [collect]s the last + * reason reported while the app's mapper runs, and records the reason only if the app's mapper + * returns `null`. As a result, a custom mapper that returns `null` after any built-in mapper + * returned `null` will record the built-in mapper's reason. + * + * Reasons are maintained per thread, so the converter collects only reasons reported on its own + * thread, where it runs the host app's mapper. If a custom mapper calls a built-in mapper on + * another thread, the reason will be lost and the entry will record `unmapped`. + */ +internal object UnknownEntryReasonReporter { + + private val reports = ThreadLocal() + + /** Reports why the built-in mapper that's about to return `null` can't name its entry. */ + fun report(reason: UnknownEntryReason) { + reports.set(reason) + } + + /** + * Runs [map] and returns its result with the last reason reported while it ran, or `null` if none + * was. Clears the report before and after, even if [map] throws, so a reason can't carry over to + * another entry. + */ + fun collect(map: () -> R): Collected { + reports.remove() + try { + val result = map() + return Collected(result, reports.get()) + } finally { + reports.remove() + } + } + + /** What [collect] returns: the mapper's [result] and the [reason] reported while it ran. */ + data class Collected(val result: R, val reason: UnknownEntryReason?) +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md new file mode 100644 index 00000000000..94d7d9d55cc --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md @@ -0,0 +1,8 @@ +# `io.sentry.compose.navigation3.internal.contract` + +Package contains internal values that are effectively part of our public contract because the Sentry UI displays them or they define +observable behavior. + +## Dependencies + +This package may ***not*** depend on any other `io.sentry.compose.navigation3` package, so that every other package can depend on it. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt deleted file mode 100644 index f7954b95866..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt +++ /dev/null @@ -1,41 +0,0 @@ -package io.sentry.compose.navigation3.internal.contract - -/** - * Passes the [UnknownEntryReason] a built-in mapper knows to the back stack converter, as the - * mapper reports a failure by returning `null`, which is public API. - * - * A built-in mapper [report]s the reason right before returning `null`, and the converter - * [collect]s it around each call to the app's mapper. So a custom mapper that forwards a built-in - * mapper's `null` forwards its reason too, while one that returns `null` itself reports nothing, - * and one that returns a name has its reason ignored. If a custom mapper calls built-in mappers - * several times for one entry, the last reason reported is kept. - * - * Kept per thread, as mappers run on the converter's thread. - */ -internal object UnknownEntryReasonReporter { - - private val reports = ThreadLocal() - - /** Reports why the built-in mapper that's about to return `null` can't name its entry. */ - fun report(reason: UnknownEntryReason) { - reports.set(reason) - } - - /** - * Runs [map] and returns its result with the last reason reported while it ran, or `null` if none - * was. Clears the report before and after, even if [map] throws, so a reason can't carry over to - * another entry. - */ - fun collect(map: () -> R): Collected { - reports.remove() - try { - val result = map() - return Collected(result, reports.get()) - } finally { - reports.remove() - } - } - - /** What [collect] returns: the mapper's [result] and the [reason] reported while it ran. */ - data class Collected(val result: R, val reason: UnknownEntryReason?) -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt index f83a32a9eca..ba5553ac51a 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt @@ -102,6 +102,29 @@ class PackageBoundariesTest { assertThat(violations).isEmpty() } + @Test + fun `the common package imports only the contract package from other Sentry navigation3 packages`() { + val commonSources = sources.filter { it.packageName.isIn(COMMON) } + + val violations = commonSources.importsMatching { + it.isIn(ROOT) && !it.isIn(COMMON) && !it.isIn(CONTRACT) + } + + assertThat(commonSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `the common package has no imports from Android or AndroidX`() { + // The kotlinx package, which may not import them, depends on the common package. + val commonSources = sources.filter { it.packageName.isIn(COMMON) } + + val violations = commonSources.importsMatching { it.isIn("android") || it.isIn("androidx") } + + assertThat(commonSources).isNotEmpty() + assertThat(violations).isEmpty() + } + // Check that the import reader finds the declarations the rules inspect. @Test @@ -168,6 +191,7 @@ class PackageBoundariesTest { const val KOTLINX = "$BACKSTACK.kotlinx" const val LIFECYCLE = "$ROOT.internal.lifecycle" const val CONTRACT = "$ROOT.internal.contract" + const val COMMON = "$ROOT.internal.common" const val MAPPER_FACTORY_PATH = "$SOURCE_ROOT/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt" diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt index 75dc883540a..6e2e5f7854e 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt @@ -10,10 +10,10 @@ import io.sentry.SentryOptions import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.io.StringWriter import kotlin.test.assertFailsWith import org.junit.Test diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt index 758ce9c864b..92a433e38d6 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt @@ -7,9 +7,9 @@ import io.sentry.SentryLevel import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.test.initForTest import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt index c2be6bf0f59..0e2d510e024 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt @@ -3,8 +3,8 @@ package io.sentry.compose.navigation3.internal.backstack import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.eq diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt index 3cad4011b7b..7a71d52b043 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt @@ -4,12 +4,10 @@ import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.backstack.kotlinx.FakeCompatibilityProbe.Inconclusive import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_THREW import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.lang.annotation.AnnotationFormatError import java.lang.reflect.InvocationTargetException import kotlin.test.assertFailsWith @@ -63,55 +61,64 @@ class KotlinxBackStackEntryMapperTest { // Construction @Test - fun `logs nothing when created and the compatibility probe finds kotlinx serialization compatible`() { + fun `logs nothing when created and the compatibility check passes`() { val logger = mock() - KotlinxBackStackEntryMapper(probe = FakeCompatibilityProbe(), logger = { logger }) + KotlinxBackStackEntryMapper(logger = { logger }) verifyNoInteractions(logger) } @Test - fun `fails creation with the LinkageError the compatibility probe returns`() { + fun `fails creation with the LinkageError the compatibility check throws`() { val error = NoSuchMethodError("serializerOrNull") - val probe = FakeCompatibilityProbe(linkageError = error) val thrown = assertFailsWith { - KotlinxBackStackEntryMapper(probe = probe, logger = { mock() }) + KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { mock() }) } assertThat(thrown).isSameInstanceAs(error) } @Test - fun `logs nothing when the compatibility probe returns a LinkageError`() { + fun `logs nothing when the compatibility check throws a LinkageError`() { // BuiltInBackStackEntryMappers logs the error it catches, so the mapper doesn't log it too. val logger = mock() - val probe = FakeCompatibilityProbe(linkageError = NoSuchMethodError()) assertFailsWith { - KotlinxBackStackEntryMapper(probe = probe, logger = { logger }) + KotlinxBackStackEntryMapper( + checkCompatibility = { throw NoSuchMethodError() }, + logger = { logger }, + ) } verifyNoInteractions(logger) } @Test - fun `logs the compatibility probe's error at debug level when the probe is inconclusive`() { - val error = IllegalStateException("probe failed") + fun `logs an IllegalArgumentException the compatibility check throws at debug level`() { + val error = IllegalArgumentException("lookup failed") + val logger = mock() + + KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { logger }) + + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any()) + } + + @Test + fun `logs an IllegalStateException the compatibility check throws at debug level`() { + val error = IllegalStateException("lookup failed") val logger = mock() - val probe = FakeCompatibilityProbe(inconclusive = Inconclusive(error)) - KotlinxBackStackEntryMapper(probe = probe, logger = { logger }) + KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { logger }) - verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any(), eq(PROBE_THREW)) + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any()) } @Test - fun `names entries when the compatibility probe is inconclusive`() { - val probe = FakeCompatibilityProbe(inconclusive = Inconclusive(IllegalStateException())) - val fixture = Fixture.create(probe = probe) + fun `names entries when the compatibility check throws an IllegalStateException`() { + val fixture = Fixture.create(checkLinkage = { throw IllegalStateException() }) val mapper = fixture.mapper val mapped = mapper.map(Detail("1")) @@ -119,6 +126,18 @@ class KotlinxBackStackEntryMapperTest { assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) } + @Test + fun `fails creation with another exception the compatibility check throws`() { + val error = UnsupportedOperationException() + + val thrown = + assertFailsWith { + KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { mock() }) + } + + assertThat(thrown).isSameInstanceAs(error) + } + // Naming @Test @@ -335,8 +354,8 @@ class KotlinxBackStackEntryMapperTest { } @Test - fun `returns null and logs the cause when the serializer lookup throws a wrapped fatal error`() { - val cause = OutOfMemoryError("serializer() failed fatally") + fun `returns null and logs the cause when the serializer lookup throws a wrapped LinkageError`() { + val cause = NoSuchMethodError("serializer() failed to link") val fixture = Fixture.create(lookUpSerializer = { throw InvocationTargetException(cause) }) val mapper = fixture.mapper @@ -346,6 +365,49 @@ class KotlinxBackStackEntryMapperTest { verifyLookUpFailureLogged(fixture.logger, cause) } + @Test + fun `propagates a wrapped fatal error the serializer lookup throws, unwrapped`() { + val cause = OutOfMemoryError("serializer() failed fatally") + val fixture = Fixture.create(lookUpSerializer = { throw InvocationTargetException(cause) }) + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(cause) + } + + @Test + fun `propagates a wrapped fatal error the serializer's descriptor throws, unwrapped`() { + val cause = OutOfMemoryError("descriptor failed fatally") + val serializer = + object : NamingOnlySerializer() { + override val descriptor: SerialDescriptor + get() = throw InvocationTargetException(cause) + } + val fixture = Fixture.create(lookUpSerializer = { serializer }) + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(cause) + } + + @Test + fun `restores the interrupt flag when the serializer lookup throws a wrapped InterruptedException`() { + val fixture = + Fixture.create(lookUpSerializer = { throw InvocationTargetException(InterruptedException()) }) + val mapper = fixture.mapper + + try { + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + assertThat(Thread.currentThread().isInterrupted).isTrue() + } finally { + Thread.interrupted() + } + } + @Test fun `returns null and logs the InvocationTargetException when the serializer lookup throws one without a cause`() { val error = InvocationTargetException(null) @@ -496,6 +558,57 @@ class KotlinxBackStackEntryMapperTest { assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) } + @Test + fun `looks up a type's serializer again after the serializer lookup is interrupted`() { + var hasThrown = false + val fixture = + Fixture.create( + lookUpSerializer = { + if (!hasThrown) { + hasThrown = true + throw InvocationTargetException(InterruptedException()) + } + Detail.serializer() + }, + ) + val mapper = fixture.mapper + try { + assertThat(mapper.map(Detail("1"))).isNull() + } finally { + Thread.interrupted() + } + + val mapped = mapper.map(Detail("2")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(fixture.lookedUpTypes).containsExactly(Detail::class.java, Detail::class.java) + } + + @Test + fun `checks a type's annotation again after the annotation check is interrupted`() { + var hasThrown = false + val fixture = + Fixture.create( + isAnnotatedSerializable = { + if (!hasThrown) { + hasThrown = true + throw InterruptedException() + } + true + }, + ) + val mapper = fixture.mapper + try { + assertThat(mapper.map(Detail("1"))).isNull() + } finally { + Thread.interrupted() + } + + val mapped = mapper.map(Detail("2")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + } + @Test fun `logs each type that isn't annotated @Serializable once`() { val fixture = Fixture.create() @@ -733,7 +846,7 @@ class KotlinxBackStackEntryMapperTest { private constructor( lookUpSerializer: (Class<*>) -> KSerializer<*>?, isAnnotatedSerializable: ((Class<*>) -> Boolean)?, - probe: CompatibilityProbe, + checkLinkage: () -> Unit, ) { val logger = mock() val lookedUpTypes = mutableListOf>() @@ -746,9 +859,18 @@ class KotlinxBackStackEntryMapperTest { } mapper = if (isAnnotatedSerializable == null) { - KotlinxBackStackEntryMapper(recordingLookUp, probe = probe, logger = { logger }) + KotlinxBackStackEntryMapper( + recordingLookUp, + checkCompatibility = checkLinkage, + logger = { logger }, + ) } else { - KotlinxBackStackEntryMapper(recordingLookUp, isAnnotatedSerializable, probe, { logger }) + KotlinxBackStackEntryMapper( + recordingLookUp, + isAnnotatedSerializable, + checkLinkage, + { logger }, + ) } } @@ -756,8 +878,8 @@ class KotlinxBackStackEntryMapperTest { fun create( lookUpSerializer: (Class<*>) -> KSerializer<*>? = { SERIALIZERS[it] }, isAnnotatedSerializable: ((Class<*>) -> Boolean)? = null, - probe: CompatibilityProbe = FakeCompatibilityProbe(), - ) = Fixture(lookUpSerializer, isAnnotatedSerializable, probe) + checkLinkage: () -> Unit = {}, + ) = Fixture(lookUpSerializer, isAnnotatedSerializable, checkLinkage) } } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt new file mode 100644 index 00000000000..5e64aeefd3b --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt @@ -0,0 +1,63 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import kotlin.test.assertFailsWith +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.SerialDescriptor +import org.junit.Test +import org.mockito.kotlin.doThrow +import org.mockito.kotlin.mock + +/** + * Runs the default check against the kotlinx.serialization version on the test classpath, which CI + * also sets to the latest stable release with `-Pnav3TestKotlinx=latestStable`. + */ +class KotlinxCompatibilityCheckTest { + + @Test + fun `checkKotlinxCompatibility() - succeeds for the kotlinx serialization version on the classpath`() { + checkKotlinxCompatibility() + } + + @Test + fun `checkKotlinxCompatibility() - looks up only the built-in String serializer`() { + val lookedUpTypes = mutableListOf>() + + checkKotlinxCompatibility { type -> + lookedUpTypes += type + String.serializer() + } + + assertThat(lookedUpTypes).containsExactly(String::class.java) + } + + @Test + fun `checkKotlinxCompatibility() - throws the LinkageError the serializer lookup throws`() { + val error = NoSuchMethodError("serializerOrNull") + + val thrown = assertFailsWith { checkKotlinxCompatibility { throw error } } + + assertThat(thrown).isSameInstanceAs(error) + } + + @OptIn(ExperimentalSerializationApi::class) + @Test + fun `checkKotlinxCompatibility() - throws the LinkageError reading the serial name throws`() { + val error = NoSuchMethodError("getSerialName") + val descriptor = mock { on { serialName } doThrow error } + val serializer = + object : NamingOnlySerializer() { + override val descriptor = descriptor + } + + val thrown = assertFailsWith { checkKotlinxCompatibility { serializer } } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `checkKotlinxCompatibility() - succeeds without reading a serial name when no serializer is found`() { + checkKotlinxCompatibility { null } + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt deleted file mode 100644 index 53e3e06f837..00000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt +++ /dev/null @@ -1,172 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack.kotlinx - -import com.google.common.truth.Truth.assertThat -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.ProbeClass -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.ProbeObject -import java.lang.reflect.InvocationTargetException -import kotlin.test.assertFailsWith -import org.junit.Test - -/** - * Runs the default probe against the kotlinx.serialization version on the test classpath, which CI - * also sets to the latest stable release with `-Pnav3TestKotlinx=latestStable`. - */ -class KotlinxCompatibilityProbeTest { - - // nameLookupLinkageError() - - @Test - fun `nameLookupLinkageError() - returns null without an inconclusive result for a compatible version`() { - val inconclusive = mutableListOf() - - val error = KotlinxCompatibilityProbe.nameLookupLinkageError { inconclusive += it } - - assertThat(error).isNull() - assertThat(inconclusive).isEmpty() - } - - @Test - fun `nameLookupLinkageError() - returns the LinkageError a probe type's serializer lookup throws`() { - val error = NoSuchMethodError("serializerOrNull") - val inconclusive = mutableListOf() - - val returned = - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) { inconclusive += it } - - assertThat(returned).isSameInstanceAs(error) - assertThat(inconclusive).isEmpty() - } - - @Test - fun `nameLookupLinkageError() - returns the LinkageError a probe type's serializer throws through reflection`() { - val error = NoSuchMethodError("PluginGeneratedSerialDescriptor") - val inconclusive = mutableListOf() - - val returned = - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw InvocationTargetException(error) }) { - inconclusive += it - } - - assertThat(returned).isSameInstanceAs(error) - assertThat(inconclusive).isEmpty() - } - - @Test - fun `nameLookupLinkageError() - reports another error a probe serializer throws via reflection as inconclusive`() { - val error = IllegalStateException("serializer failed") - val inconclusive = mutableListOf() - - val returned = - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw InvocationTargetException(error) }) { - inconclusive += it - } - - assertThat(returned).isNull() - assertThat(inconclusive).containsExactly(error) - } - - @Test - fun `nameLookupLinkageError() - propagates a fatal error a probe type's serializer throws through reflection`() { - val error = OutOfMemoryError() - - val thrown = - assertFailsWith { - KotlinxCompatibilityProbe.nameLookupLinkageError( - { - throw InvocationTargetException(error) - }, - ) {} - } - - assertThat(thrown).isSameInstanceAs(error) - } - - @Test - fun `nameLookupLinkageError() - reports a non-fatal exception as inconclusive and returns null`() { - val error = IllegalStateException("lookup failed") - val inconclusive = mutableListOf() - - val returned = - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) { inconclusive += it } - - assertThat(returned).isNull() - assertThat(inconclusive).containsExactly(error) - } - - @Test - fun `nameLookupLinkageError() - propagates a fatal error that isn't a LinkageError`() { - val error = OutOfMemoryError() - - val thrown = - assertFailsWith { - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) {} - } - - assertThat(thrown).isSameInstanceAs(error) - } - - @Test - fun `nameLookupLinkageError() - reports a missing probe serializer as inconclusive without an error`() { - val inconclusive = mutableListOf() - - val returned = - KotlinxCompatibilityProbe.nameLookupLinkageError( - { type -> if (type == ProbeObject::class.java) null else reflectiveSerializerOrNull(type) }, - ) { - inconclusive += it - } - - assertThat(returned).isNull() - assertThat(inconclusive).containsExactly(null) - } - - @Test - fun `nameLookupLinkageError() - doesn't re-report onInconclusive's exception for a missing probe serializer`() { - val error = IllegalStateException("callback failed") - val inconclusive = mutableListOf() - - val thrown = - assertFailsWith { - KotlinxCompatibilityProbe.nameLookupLinkageError({ null }) { - inconclusive += it - throw error - } - } - - assertThat(thrown).isSameInstanceAs(error) - assertThat(inconclusive).containsExactly(null) - } - - @Test - fun `nameLookupLinkageError() - doesn't re-report onInconclusive's exception for a lookup exception`() { - val lookupError = IllegalStateException("lookup failed") - val callbackError = IllegalArgumentException("callback failed") - val inconclusive = mutableListOf() - - val thrown = - assertFailsWith { - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw lookupError }) { - inconclusive += it - throw callbackError - } - } - - assertThat(thrown).isSameInstanceAs(callbackError) - assertThat(inconclusive).containsExactly(lookupError) - } - - // Probe types - - @Test - fun `the serializer lookup names the probe's types`() { - // A probe type the lookup couldn't find would make the check pass without looking up a name. - val names = - listOf(ProbeClass::class.java, ProbeObject::class.java).map { - reflectiveSerializerOrNull(it)?.descriptor?.serialName - } - - assertThat(names) - .containsExactly(ProbeClass::class.qualifiedName, ProbeObject::class.qualifiedName) - .inOrder() - } -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt index a72868dd03f..b500c609c3c 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt @@ -3,16 +3,13 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.MIN_KOTLINX_SERIALIZATION_VERSION -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_SERIALIZER_NOT_FOUND -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_THREW import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND +import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.MIN_KOTLINX_SERIALIZATION_VERSION import org.junit.Test import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq -import org.mockito.kotlin.isNull import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -47,34 +44,18 @@ class KotlinxMapperDiagnosticsTest { assertThat(message.firstValue).contains("Use a custom BackStackEntryMapper") } - // inconclusiveProbe() + // compatibilityCheckFailed() @Test - fun `inconclusiveProbe() - logs the error at debug level with the reason that the probe threw`() { - val error = IllegalStateException("probe failed") - - diagnostics.inconclusiveProbe(error) - - val message = argumentCaptor() - verify(logger).log(eq(SentryLevel.DEBUG), eq(error), message.capture(), eq(PROBE_THREW)) - assertThat(message.firstValue) - .startsWith("Nav3 couldn't verify kotlinx.serialization support for name lookups") - } + fun `compatibilityCheckFailed() - logs the error at debug level`() { + val error = IllegalStateException("lookup failed") - @Test - fun `inconclusiveProbe() - logs at debug level that no probe serializer was found when there's no error`() { - diagnostics.inconclusiveProbe(null) + diagnostics.compatibilityCheckFailed(error) val message = argumentCaptor() - verify(logger) - .log( - eq(SentryLevel.DEBUG), - isNull(), - message.capture(), - eq(PROBE_SERIALIZER_NOT_FOUND), - ) + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), message.capture()) assertThat(message.firstValue) - .startsWith("Nav3 couldn't verify kotlinx.serialization support for name lookups") + .startsWith("Nav3 couldn't verify kotlinx.serialization compatibility") } // unresolved() diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt index bb3b036ed79..a2c998a76cd 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt @@ -8,6 +8,7 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.serializerOrNull import org.junit.Test class KotlinxSerializerLookupTest { @@ -214,6 +215,16 @@ class KotlinxSerializerLookupTest { assertThat(serializer?.descriptor?.serialName).isEqualTo("PrivateObject") } + /** + * Fails once a kotlinx.serialization release can look up a private object's serializer itself, + * e.g., when CI runs the latest stable release. The private object fallback can then be removed + * once `kotlinxSerialization-floor` reaches that release. + */ + @Test + fun `kotlinx serialization's own lookup still throws IllegalAccessException for a private object`() { + assertFailsWith { serializerOrNull(PrivateObject::class.java) } + } + @Test fun `returns the serializer of a private @Serializable class`() { val serializer = reflectiveSerializerOrNull(PrivateClass::class.java) @@ -325,38 +336,38 @@ class KotlinxSerializerLookupTest { } @Test - fun `restores the interrupt flag when a class's serializer construction is interrupted`() { - try { - val thrown = - assertFailsWith { - reflectiveSerializerOrNull(InterruptedConstruction::class.java) - } - - assertThat(thrown).hasCauseThat().isInstanceOf(InterruptedException::class.java) - assertThat(Thread.currentThread().isInterrupted).isTrue() - } finally { - Thread.interrupted() - } + fun `throws an interruption of a class's serializer construction wrapped in an InvocationTargetException`() { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(InterruptedConstruction::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(InterruptedException::class.java) } @Test - fun `propagates a class's fatal serializer initializer error unwrapped`() { + fun `throws a class's fatal serializer initializer error wrapped in an InvocationTargetException`() { val thrown = - assertFailsWith { + assertFailsWith { reflectiveSerializerOrNull(FatallyUninitializable::class.java) } - assertThat(thrown).hasMessageThat().isEqualTo("class serializer init failed fatally") + assertThat(thrown).hasCauseThat().isInstanceOf(OutOfMemoryError::class.java) + assertThat(thrown) + .hasCauseThat() + .hasMessageThat() + .isEqualTo("class serializer init failed fatally") } @Test - fun `propagates a private object's fatal serializer initializer error unwrapped`() { + fun `throws a private object's fatal serializer initializer error wrapped in an InvocationTargetException`() { val thrown = - assertFailsWith { + assertFailsWith { reflectiveSerializerOrNull(PrivateFatal::class.java) } - assertThat(thrown).hasMessageThat().isEqualTo("serializer init failed fatally") + assertThat(thrown).hasCauseThat().isInstanceOf(OutOfMemoryError::class.java) + assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer init failed fatally") } // Private object lookups that find no serializer diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt index 1a1339a038c..d06ebe92abb 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -20,24 +20,3 @@ internal abstract class NamingOnlySerializer : KSerializer { override fun deserialize(decoder: Decoder): T = throw UnsupportedOperationException() } - -/** - * A compatibility probe that finds kotlinx.serialization compatible by default. Set [linkageError] - * to report an incompatible version, or [inconclusive] to report an inconclusive result. - */ -internal class FakeCompatibilityProbe( - private val linkageError: LinkageError? = null, - private val inconclusive: Inconclusive? = null, -) : CompatibilityProbe { - - override fun invoke(onInconclusive: (Throwable?) -> Unit): LinkageError? { - linkageError?.let { - return it - } - inconclusive?.let { onInconclusive(it.error) } - return null - } - - /** Why the probe is inconclusive: [error], or `null` if a probe serializer wasn't found. */ - class Inconclusive(val error: Throwable?) -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt similarity index 95% rename from sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt rename to sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt index eea71458579..7c19e9e70c9 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt @@ -1,7 +1,8 @@ -package io.sentry.compose.navigation3.internal.contract +package io.sentry.compose.navigation3.internal.common import com.google.common.truth.Truth.assertThat -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter.Collected +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter.Collected +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason import kotlin.concurrent.thread import kotlin.test.assertFailsWith import org.junit.Test