The Ratchet and the Report: Hunting Dead Code in Android CI

2026-12-01来源 dev.toEnglish
The Ratchet and the Report: Hunting Dead Code in Android CI

Every long-lived Android codebase accumulates code that nobody calls and resources that nothing references. It starts innocently: an A/B test ends but its layouts stay, a feature flag is retired but its three fallback classes remain, and a design refresh leaves 40 orphaned drawables behind. None of it breaks the build, so none of it gets removed.

This post builds a CI setup that turns dead-code removal from a quarterly cleanup into a continuous, enforced property of the repository. We will combine three signals (Lint, R8 reports, and the resource shrinker), wire them into gates that can only tighten over time, and finish with an optional, carefully fenced AI step that drafts removal suggestions. Along the way we will look at the failure modes that bite in production, because dead-code tooling fails in ways that are quiet until a release build crashes.

The examples use a fictional grocery-delivery app called Harbor (com.harbor.shop).

dead-code-pipeline

Three detectors, three different questions

Before configuring anything, be clear about what each tool actually knows. They are not redundant. Each one answers a different question at a different layer.

tool-comparison

The practical consequence: Lint tells you what to delete from source, R8 tells you what the compiler already proved unreachable, and the resource shrinker tells you what ships in the APK but should not. A gate built on only one of them leaves a gap the others would have covered.

1. Lint baselines: adopt strictness without a rewrite

If you turn on UnusedResources in a five-year-old project, you will get hundreds of findings on day one. A baseline lets you accept that debt explicitly and fail only on new problems.

Configuration

// app/build.gradle.kts android { lint { baseline = file("lint-baseline.xml") // Analyze library modules together with :app so a resource used only // from :app is not reported as unused inside the library. checkDependencies = true abortOnError = true warningsAsErrors = false // keep unrelated warnings from blocking checkReleaseBuilds = false // CI runs lint explicitly; don't pay twice enable += setOf("UnusedResources", "UnusedIds") error += setOf("UnusedResources") // promote to build-breaking htmlReport = true xmlReport = true sarifReport = true // consumable by code-scanning UIs } } 

Create or refresh the baseline with:

./gradlew :app:updateLintBaseline 

Failure mode: the baseline becomes a graveyard

A baseline file is easy to regenerate, and that is the problem. The first time a PR goes red because of a new unused resource, someone runs updateLintBaseline, commits the result, and CI turns green. The finding has not been fixed, only hidden. Repeat this a few dozen times and the baseline grows instead of shrinking.

baseline-ratchet

The fix is a ratchet: CI compares the PR’s baseline to the one on the target branch and fails if the entry count increased.

// buildSrc or a convention plugin import org.gradle.api.DefaultTask import org.gradle.api.file.RegularFileProperty import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.Optional import org.gradle.api.tasks.TaskAction import java.io.File abstract class LintBaselineRatchet : DefaultTask() { @get:InputFile abstract val baseline: RegularFileProperty /** Baseline from the target branch. Absent on the very first run. */ @get:InputFile @get:Optional abstract val reference: RegularFileProperty @TaskAction fun verify() { val now = countEntries(baseline.get().asFile) val before = reference.orNull?.asFile?.let(::countEntries) ?: return check(now <= before) { "Lint baseline grew from $before to $now entries. " + "Fix the new findings instead of baselining them." } logger.lifecycle("Lint baseline entries: $before -> $now") } private fun countEntries(file: File): Int = Regex("<issue\\b").findAll(file.readText()).count() } 
// app/build.gradle.kts tasks.register<LintBaselineRatchet>("lintBaselineRatchet") { baseline.set(layout.projectDirectory.file("lint-baseline.xml")) reference.set(providers.gradleProperty("baselineRef").map { layout.projectDirectory.file(it) }) } 

More baseline gotchas

  • Renames resurrect findings. Lint matches baseline entries on issue ID, message, and file path rather than exact line numbers, so edits that shift lines are fine, but moving or renaming a file makes its old findings look new. Treat large package moves as a deliberate “regenerate baseline” PR, reviewed on its own, with the ratchet temporarily comparing against the new count.
  • Tool upgrades change the findings. An AGP or Lint upgrade can add checks or alter messages. Do the upgrade and the baseline refresh in one dedicated PR; never mix it with feature work.
  • Per-module baselines drift apart. If you run Lint per module, give each its own baseline and ratchet each one. A single shared baseline hides which module is decaying.

2. shrinkResources: let the build prove what is unused

Lint reasons about source. The resource shrinker works on the built app, so it can also see what R8 removed. Code that R8 drops no longer references its resources, which makes those resources removable.

// app/build.gradle.kts android { buildTypes { release { isMinifyEnabled = true // required: the shrinker depends on R8's result isShrinkResources = true proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro", ) } } } 

After a release build, look in app/build/outputs/mapping/release/. In recent AGP versions you will find usage.txt (code R8 removed) and resources.txt (what the resource shrinker kept or dropped) next to mapping.txt. Those files are your raw evidence. Confirm the exact set for your AGP version by listing the directory once; don't assume.

Failure mode: dynamic lookups that the shrinker cannot see

Harbor shows a promo banner whose drawable is chosen from a server-provided slot name:

// Fragile: the resource name is assembled at runtime @SuppressLint("DiscouragedApi") // lint warns about getIdentifier for exactly this reason fun promoBanner(context: Context, slot: String): Drawable? { val id = context.resources.getIdentifier("promo_$slot", "drawable", context.packageName) return if (id != 0) AppCompatResources.getDrawable(context, id) else null } 

Because this code calls getIdentifier, the shrinker's default (safe) mode treats string constants that look like resource names as possible references, so it conservatively keeps drawables starting with promo_. Nothing breaks, but those drawables are never shrunk. A well-meaning engineer then enables strict mode to claw back size, and now promo_summer.png is gone. The result is a null banner in production with no crash and nothing in your own logs, just a quietly empty slot.

Make the references visible instead:

// Robust: the compiler and shrinker both see every resource private val promoBanners: Map<String, Int> = mapOf( "summer" to R.drawable.promo_summer, "winter" to R.drawable.promo_winter, "launch" to R.drawable.promo_launch, ) fun promoBanner(context: Context, slot: String): Drawable? = promoBanners[slot]?.let { AppCompatResources.getDrawable(context, it) } 

An explicit map costs a few lines and makes the dependency greppable, lintable, and shrinkable. If a dynamic lookup is truly unavoidable, declare it:

<!-- res/raw/keep.xml --> <resources xmlns:tools="http://schemas.android.com/tools" tools:shrinkMode="strict" tools:keep="@drawable/promo_*" tools:discard="@layout/debug_overlay_*" /> 

Other resource-shrinking surprises

  • Library modules do not shrink resources. isShrinkResources is configured on the application build; dynamic features are shrunk as part of the base app's configuration rather than on their own. An unused drawable in :design-system will ship unless Lint's UnusedResources with checkDependencies = true catches it.
  • Placeholder versus removal. Depending on the AGP version and settings, unused resources may be replaced by tiny stubs so resource IDs stay stable, rather than deleted outright. Verify the real size effect in Android Studio’s APK Analyzer instead of trusting the build log.
  • Reflection-loaded layouts. Layouts inflated by name from a string (common in legacy plugin systems) need the same treatment as getIdentifier.

3. R8 reports: turn “removed code” into a metric

R8’s usage.txt lists classes and members it removed as unreachable. For a shipped release, that is a free dead-code inventory. Whole classes listed there are strong candidates for deletion from source, because nothing reaches them from any entry point.

Here is a small Gradle task that reads usage.txt, filters to Harbor's own packages, and fails if the number of fully removed classes exceeds a budget:

import org.gradle.api.DefaultTask import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction abstract class R8DeadClassReport : DefaultTask() { /** mapping.txt; its producer task is tracked, usage.txt sits beside it. */ @get:InputFile abstract val mappingFile: RegularFileProperty @get:Input abstract val ownPackages: ListProperty<String> @get:Input abstract val maxDeadClasses: Property<Int> @get:OutputFile abstract val report: RegularFileProperty @TaskAction fun run() { val prefixes = ownPackages.get() // usage.txt: unindented lines name classes. A trailing ':' means only // some members were removed; no colon means the whole class was dropped. val usage = mappingFile.get().asFile.resolveSibling("usage.txt") check(usage.exists()) { "usage.txt not found next to mapping.txt (${usage.parent}). Did R8 run for this variant?" } val classLines = usage.useLines { lines -> lines .filter { it.isNotEmpty() && !it.first().isWhitespace() } .filter { line -> prefixes.any { p -> line.startsWith(p) } } .toList() } val (partial, whole) = classLines.partition { it.endsWith(":") } val byPackage = whole .groupingBy { it.substringBeforeLast('.', missingDelimiterValue = "(default)") } .eachCount() .toList() .sortedByDescending { (_, count) -> count } report.get().asFile.apply { parentFile.mkdirs() writeText(buildString { appendLine("Fully removed classes: ${whole.size}") appendLine("Classes with removed members: ${partial.size}") appendLine() byPackage.forEach { (pkg, n) -> appendLine("%4d %s".format(n, pkg)) } }) } check(whole.size <= maxDeadClasses.get()) { "R8 removed ${whole.size} of our own classes (budget ${maxDeadClasses.get()}). " + "Delete the dead code or justify a keep rule." } } } 
// app/build.gradle.kts import com.android.build.api.artifact.SingleArtifact androidComponents { onVariants(selector().withBuildType("release")) { variant -> // Skip variants that are not minified: no R8 run means no usage.txt to read. if (!variant.isMinifyEnabled) return@onVariants // Declaring mapping.txt as the task input keeps the R8 producer task attached. // R8 writes usage.txt (and the shrinker resources.txt) beside it. val mapping = variant.artifacts.get(SingleArtifact.OBFUSCATION_MAPPING_FILE) val suffix = variant.name.replaceFirstChar { it.uppercase() } // "Release", "FreeRelease"... tasks.register<R8DeadClassReport>("r8DeadClassReport$suffix") { mappingFile.set(mapping) ownPackages.set(listOf("com.harbor.shop")) maxDeadClasses.set(providers.gradleProperty("deadClassBudget").map(String::toInt).orElse(25)) report.set(layout.buildDirectory.file("reports/dead-code/r8-dead-classes-$suffix.txt")) } // Gate 3 (see section 4) if (variant.shrinkResources) { tasks.register<UnusedResourceReport>("unusedResourceReport$suffix") { mappingFile.set(mapping) // Only orders tasks when both are requested, e.g. `assembleRelease unusedResourceReportRelease` mustRunAfter(tasks.matching { it.name == "assemble$suffix" }) maxUnused.set(providers.gradleProperty("unusedResourceBudget").map(String::toInt).orElse(60)) } } } } 

Registering through the Variant API (instead of dependsOn("minifyReleaseWithR8")) avoids hardcoding an internal task name, and it produces one task per release variant when you use flavors. variant.isMinifyEnabled needs AGP 7.4 or newer, and variant.shrinkResources is newer still (AGP 8.1 or later, as far as I can tell). On older AGP versions, delete the if (variant.shrinkResources) wrapper and rely on the task's own resources.txt existence check. Verify both properties against your AGP version, since I have not compiled this. Store deadClassBudget in gradle.properties and lower it each time a cleanup lands. This is the same ratchet idea as the Lint baseline: the number is allowed to fall, never rise.

Failure mode: one broad keep rule disables the whole signal

# Looks harmless. Silently turns off shrinking for the entire package tree. -keep class com.harbor.shop.** { *; } 

With this in place, usage.txt contains nothing from your own code, your dead-class count reads zero, and your gate passes forever. The signal has been switched off, not satisfied. Audit your rules the same way you audit the report:

  • Compare configuration.txt against the rules you think you wrote, because library consumer rules are merged in and can be broader than expected.
  • Narrow keeps to the smallest scope that works:
# Only the serialized fields, only in the DTO package -keepclassmembers class com.harbor.shop.api.dto.** { @com.google.gson.annotations.SerializedName <fields>; } 

Failure mode: the code R8 removes is code you reach by name

Harbor loads payment handlers through a string from remote config:

// Fragile: R8 cannot see this constructor call fun handlerFor(provider: String): PaymentHandler = Class.forName("com.harbor.shop.payments.${provider.replaceFirstChar(Char::titlecase)}Handler") .getDeclaredConstructor() .newInstance() as PaymentHandler 

R8 can follow Class.forName only when the argument is a compile-time constant. Here the name is assembled from runtime input, so R8 sees no static reference to UpiHandler, removes it, and the release build throws ClassNotFoundException the first time a user picks UPI. Debug builds never show it because they are not shrunk. This class of bug is the main reason teams distrust dead-code tooling, and it is why the report must be treated as evidence to review, not a to-do list to apply blindly.

The idiomatic repair is to make reachability explicit, which also makes the code easier to test:

private val handlers: Map<String, () -> PaymentHandler> = mapOf( "upi" to ::UpiHandler, "card" to ::CardHandler, "wallet" to ::WalletHandler, ) fun handlerFor(provider: String): PaymentHandler = handlers[provider]?.invoke() ?: error("Unknown payment provider: $provider") 

Constructor references are visible to R8, so these classes are kept when, and only when, the map is reachable.

Two more traps worth a test each:

  • Release-only code paths. Run your instrumented smoke tests against a minified build (a release-like variant with the debug signing key) so reflection failures show up before users see them.
  • Debug-only classes inflate the report. Classes used only in debug builds legitimately vanish from release. Exclude *.debug.* packages from ownPackages or the budget will be noisy and people will stop trusting it.

4. CI gates: cheapest first, tightest last

Individually, these checks are advice. A gate makes them policy. The order below runs Lint first, because it needs no minified build. Lint is not instant on a large multi-module project, so run lintDebug (the baseline file is shared across variants) rather than lintRelease, and add incremental or per-module runs if it gets slow. The two R8-derived gates need a minified build, so they come after.

ci-gates-flow

Gate 3 reads resources.txt and counts resources the shrinker judged unreachable:

abstract class UnusedResourceReport : DefaultTask() { @get:InputFile abstract val mappingFile: RegularFileProperty @get:Input abstract val maxUnused: Property<Int> @TaskAction fun run() { val file = mappingFile.get().asFile.resolveSibling("resources.txt") check(file.exists()) { "resources.txt not found at ${file.path}. Run assembleRelease first." } // Classic shrinker dump: one "@type/name : reachable=true|false" line per resource. // Other AGP versions or optimized resource shrinking may format this differently. var reachable = 0 var unused = 0 file.forEachLine { line -> when { "reachable=false" in line -> unused++ "reachable=true" in line -> reachable++ } } // Fail loudly if the format is not recognized, instead of passing with a count of zero. check(reachable + unused > 0) { "No reachable=true/false entries in ${file.name}; update the parser for your AGP version." } check(unused <= maxUnused.get()) { "Resource shrinker found $unused unreachable resources (budget ${m...

原文:https://www.a8q9.cn/en/article/the-ratchet-and-the-report-hunting-dead-code-in-android-ci-eb34fe.html

相关文章