skip to content

As Android lead, what LeakCanary policy should decide where leak detection runs, which leaks fail CI, and how known leaks are muted?

level: principalimportance: should knowfreq 20%

answer

  1. debug, CI and release are three choices
  2. application leaks versus library leaks
  3. a rule on the suites that matter
  4. every mute carries an issue and an owner
  5. group uploaded leaks by signature

basics

~20 s

Run LeakCanary in debug builds for developers and in CI instrumentation tests, fail CI only on application leaks, mute known library leaks with matchers tied to an issue, and upload results grouped by leak signature.

solid answer

~40 s

I set the policy in layers. Debug builds keep `leakcanary-android` for developers, but CI is the gate: `leakcanary-android-instrumentation` with the `DetectLeaksAfterTestSuccess` rule in a shared test base, on pull requests for the most-changed screens and on the full UI suite nightly, because each heap dump costs time. The default reporter fails a test only on **application leaks**, and library leaks are logged, which matches what the team can fix. Known leaks in Android or a vendor SDK become reference matchers on top of `AndroidReferenceMatchers.appDefaults`, and a flaky test gets `@SkipLeakDetection` with an issue link. Each mute has an owner and is reviewed when its dependency changes. A custom `HeapAnalysisReporter` uploads results grouped by leak signature. `leakcanary-android-release` stays an experiment, not a default.

code

kotlin · 25 lines
kotlin
import leakcanary.AndroidDetectLeaksAssert
import leakcanary.DetectLeaksAfterTestSuccess
import leakcanary.DetectLeaksAssert
import leakcanary.HeapAnalysisReporter
import leakcanary.NoLeakAssertionFailedError
import org.junit.Rule
import shark.HeapAnalysis

// Installed once by the team's test runner or a shared base class.
fun installLeakPolicy(upload: (HeapAnalysis) -> Unit) {
    val failOnAppLeaks = NoLeakAssertionFailedError.throwOnApplicationLeaks()
    DetectLeaksAssert.update(
        AndroidDetectLeaksAssert(
            heapAnalysisReporter = HeapAnalysisReporter { analysis ->
                upload(analysis) // dashboard groups leaks by signature
                failOnAppLeaks.reportHeapAnalysis(analysis) // library leaks only logged
            },
        ),
    )
}

abstract class LeakCheckedTest {
    @get:Rule
    val leakRule = DetectLeaksAfterTestSuccess()
}

go deeper

for a junior

Know that LeakCanary goes in debug builds and reports leaked activities, and that teams can also check for leaks in automated tests.

for a middle

Explain how the instrumentation artifact fails a test on a leak, and the difference between an application leak and a library leak.

for a senior

Show you can wire the rule into a suite, place it correctly in a RuleChain, mute a known library leak with a matcher and quarantine a flaky test.

for a principal

Own the policy: which builds and suites check for leaks and how often, what blocks a merge, how mutes are tracked and reviewed, and where results are aggregated.

## The decision Installing LeakCanary is one line. Deciding what the team does with what it finds is a policy, and without one the usual outcome is a debug notification that every developer learns to swipe away. The lead owns four answers: **where** leak detection runs, **what fails** a build, **how known leaks are muted** without being forgotten, and **where the results go**. None has a single right answer. Each trades CI time and noise against how early a leak is caught. ## Where detection runs | Where | Artifact | What happens on a leak | Cost | |---|---|---|---| | Debug builds on developer devices | `leakcanary-android` (`debugImplementation`) | a heap dump after a retained object, then a notification | the app freezes during each dump | | Instrumentation tests in CI | `leakcanary-android-instrumentation` (`androidTestImplementation`) | `LeakAssertions.assertNoLeaks()` dumps, analyses, and can fail the test | a heap dump and analysis per assertion that finds retained objects | | Release builds | `leakcanary-android-release` | heap analysis in production through its own APIs | experimental, so its artifact and APIs may change | Most teams start with the first two: - **The debug artifact turns itself off in tests.** It disables itself when it finds JUnit on the classpath, so CI relies on the instrumentation artifact, not on notifications. - **The `DetectLeaksAfterTestSuccess` rule** calls `assertNoLeaks()` after every test that passed. It is the cheapest way to cover a whole UI suite. - **Release analysis is an opt-in experiment** for an app with a real out-of-memory problem in production. It is not a default. ## What fails a build The default reporter, `NoLeakAssertionFailedError.throwOnApplicationLeaks()`, throws only for **application leaks**. Library leaks, matched by LeakCanary's known patterns, are logged and the test keeps going. That default is a sound policy: a team can fix its own leaks, but not Android's or a vendor's. The lead then decides: 1. **Which suites carry the rule.** Running it on the full UI suite catches the most, but every assertion that finds retained objects dumps and analyses the heap, which slows CI. A team can run it on every pull request for the screens it changes most, and on the full suite nightly. 2. **What happens on a new failure.** A new application leak blocks the merge like a failing test. A flaky one is quarantined with `@SkipLeakDetection("reason")`, never by deleting the rule. 3. **Where the rule sits in a `RuleChain`.** That decides whether activity leaks, fragment leaks or both are seen, so set it once in a shared base and stop each test deciding it. ## Muting known leaks without forgetting them - **A leak inside a third-party SDK** becomes a known library leak. Add a matcher such as `AndroidReferenceMatchers.staticFieldLeak(...)` to `LeakCanary.config.referenceMatchers`, on top of `AndroidReferenceMatchers.appDefaults`, with a description that names the vendor issue. - **A skipped test** carries the tracking issue in its `@SkipLeakDetection` message, and the issue carries the date to revisit it. - **Every mute has an owner.** A matcher list that only grows hides real regressions in a dependency upgrade, so the list is reviewed when that dependency changes. ## Where results go Failures in CI are useful only if someone can compare them over time. - **In CI**, `DetectLeaksAssert.update(AndroidDetectLeaksAssert(heapAnalysisReporter = ...))` installs a reporter that uploads each analysis before delegating to the throwing one. - **On debug devices**, an `EventListener` added to `LeakCanary.config.eventListeners` does the same with `HeapAnalysisSucceeded` events. - **Group by signature.** Each leak carries a `signature`, a hash of the suspect part of its trace, so a dashboard counts one leak once however many tests hit it. Teams without their own backend can upload leak traces to a crash-reporting tool that groups by a custom hash. ## Writing it down The policy fits on one page. Name the artifacts and where each runs, the suites and schedule for the rule, that application leaks fail and library leaks are logged, the template for a mute (issue link, owner, review trigger) and the dashboard to look at. Memory budgets and which leak classes matter to the product are a separate design decision. This page only says how LeakCanary enforces them.

  • Why not fail CI on library leaks too?
    Because the team cannot fix them. A library leak is matched to a known pattern in Android or a vendor's code, so failing on it blocks merges for a bug nobody on the team can change. The default reporter logs it and the test keeps going. The lead's job is to make sure each known leak has an issue with the vendor and is re-checked when that dependency is upgraded.
  • The UI suite got slower after the leak rule was added everywhere. What do you change?
    The cost is the heap dump and analysis each time an assertion finds retained objects. I would keep the rule on pull requests only for the suites covering the screens changed most often, and run the full suite with the rule nightly. A leak is then caught within a day instead of within the PR, a trade I would write into the policy.
  • When would you try leakcanary-android-release?
    When production shows an out-of-memory or ANR problem that debug builds and CI do not reproduce, and the team can handle heap analysis on user devices. It is documented as experimental, with an artifact and APIs that may change, so it runs as a time-boxed investigation with its own owner, not as a default.

  • LeakCanary's debug notifications are enough; CI does not need leak checks.
  • Every leak LeakCanary reports should fail the build, library leaks included.
  • A flaky leak test is fixed by removing DetectLeaksAfterTestSuccess from it.
  • Known library leaks can be muted without an issue or an owner.
  • LeakCanary for releases is a safe default for every production app.

Assumes LeakCanary 2.14. The instrumentation APIs named here (LeakAssertions, DetectLeaksAfterTestSuccess, @SkipLeakDetection) replaced FailTestOnLeakRunListener in 2.8; leakcanary-android-release dates from 2.6 and is still marked experimental.