跪拜 Guibai
← All articles
Artificial Intelligence · Android · Performance Optimization

After Deleting LeakCanary, I Built My Own with Trae: The Hard Part Isn't Analyzing the Heap, It's Deciding When to Dump

By 疯华整猫 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Privacy compliance can invalidate a popular debugging tool overnight, and the fix is not to find a shinier analyzer but to design the trigger and the data-flow carefully. This account shows how to build a minimal, auditable leak detector that respects data boundaries, and how to turn a one-off AI-assisted project into a repeatable, CI-checked workflow.

Summary

When a security audit revealed that LeakCanary's debug-mode heap dumps contained plaintext ID card numbers, patient names, and an unexpired token, the only responsible move was to delete the dependency. But the app immediately started OOM-crashing without any leak notifications. The answer wasn't a better heap analyzer; it was building a custom detector that understands the real problem: knowing when to dump, not how to analyze the dump.

The resulting system, developed in twelve interaction rounds with Trae, mirrors LeakCanary's architecture but strips it to the minimum: a `KeyedWeakReference` probe watching for weakly-reachable objects, a trigger that waits five seconds, forces GC, and counts only objects still alive after a second queue poll, and a dump that runs on a background thread with primitive-array zeroing before the file ever leaves the device. A 400-line Python script performs the BFS to find the shortest reference path from GC roots, with three-state leak annotation and array-index normalization.

The process itself is as instructive as the code. The author documents how the trigger was the missing insight all along, why weakly-reachable beats `finalize()` and direct weak references, how the hprof binary format hides pitfalls in its un-length-bounded sub-records, and how the entire 12-round prompt-and-verify workflow was codified into a Trae Skill with its own acceptance gates, privacy red lines, and adversarial review checklist.

Takeaways
— LeakCanary's `Debug.dumpHprofData()` captures the entire Java heap, including plaintext personal data in `String` objects, which a privacy audit can flag as a data-exfiltration risk.
— The core of LeakCanary isn't heap analysis; it's the trigger that decides when a dump is worth taking, born from Square's 2015 `ActivityMemoryDiaper` and refined through three detection revisions to the weakly-reachable probe.
— The detection principle is to watch weak reachability, not actual reclamation: a ref entering the `ReferenceQueue` happens before GC reclaims the object, which is earlier and cleaner than `finalize()`.
— The confirmation order is non-negotiable: wait 5 seconds, clear the queue, force GC, clear the queue again, and only count as a leak if the key is still in the table.
— Square's first usage of the trigger cut OOM crash rate by 94% by ensuring evidence was tied to the last user action.
— The hprof binary format contains sub-records with no length fields; each tag requires manual cursor advancement, and unknown tags must throw rather than be guessed.
— Zeroing `PRIMITIVE_ARRAY_DUMP` content removes string literals and image pixels without breaking reference chains, which are built from object IDs and field names only.
— The final metrics: false positive rate dropped from 62% (handwritten first version) to 9% on Pixel 6 and 11% on Redmi Note 11; true positive recall reached 8/8; dump freeze P90 dropped from 1180ms to 640ms by moving dumps to a `HandlerThread`.
— The twelve-round process with Trae was codified into a reusable Skill containing acceptance gates, a privacy red line, and a three-identity adversarial review, with CI gates checking unit tests, stripping regression, and release cleanliness.
— A release build keeps only a thin `retainedObjectCount` read-out; no dump, no file, no network, and no third-party class, verified by a script that searches the release dex.
Conclusions

The single most transferable idea is treating the trigger as the product: decide when to capture evidence before deciding how to analyze it, and the analysis becomes tractable.

Privacy compliance is now a first-class engineering constraint on debugging tools, not an afterthought: the same dump that helps you find a leak can expose user data, so the tool must be designed with schema-aware redaction built in.

Building a minimal replacement for a mature library forces deeper understanding of the problem than using the library ever did; the author's rewrite of LeakCanary's core in a few hundred lines clarifies what the original tool's real value is.

AI-assisted development changes the nature of debugging: the hard work is specifying the contract (when to dump, what to strip, which line to change) and verifying the output, not writing the parsing code.

A measurable boundary—like an explicit error on unknown hprof tags or a script that fails when stripping is bypassed—is worth more than a hundred lines of defensive logic, because it prevents silent wrong answers.

The author's honest reporting of unresolved numbers (the 11% false-positive rate on the low-memory device) shows that a tool's validation is only as trustworthy as its refusal to tune the metric into passing.

Concepts & terms
weakly reachable
An object that has only weak references pointing to it is weakly reachable just before GC reclaims it. The GC enqueues the `WeakReference` object into its bound `ReferenceQueue` at that moment, earlier than `finalize()` runs, so checking the queue for a ref is a clean early detection of imminent leak, without touching the target object.
heap dump trigger
The decision logic that determines when to call `Debug.dumpHprofData()`. Rather than dumping at random times, the trigger waits a fixed delay (e.g., 5 seconds), clears the reference queue, forces a GC, clears again, and only if the object's key is still alive does it count as a potential leak and dump.
KeyedWeakReference
A `WeakReference` subclass that adds a UUID key, a description string, and a watch timestamp. The key lets the same object be traced through the reference queue, the hprof file, the leak trace, and the group signature, allowing the tool to identify individual instances across multiple stages of analysis.
dominator tree
A graph structure used in heap analysis to compute retained size: if every path from a GC root to object B passes through object A, then A dominates B, meaning B is retained as long as A alive. This answers how much memory a leak occupies, separate from who holds it; the article's minimal parser omits it by design.
hprof (HPROF binary)
The file format written by `Debug.dumpHprofData()`, defined by the JVM TI Agent. It consists of a version header, identifier size, and a series of tagged records, including heap dumps that contain sub-records for class dumps, instance dumps, object arrays, primitive arrays, and GC roots. Sub-records have no length fields, so parsers must advance byte-by-byte by tag structure.
group signature
A SHA-1 hash computed from the concatenation of suspicious references on a leak path. It groups distinct instances of the same bug into one report entry, independent of the object's UUID key, so the same leak with different array indices appears as one item, not dozens.
Trae Skill
A packaging format for AI assistant workflows, consisting of a `SKILL.md` with trigger-word frontmatter, reference documents, templates, scripts, and checklist files. It lets a complex, multi-stage process be invoked by a single phrase and enforced by self-check scripts that verify actual outputs against acceptance criteria.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗