Diagnosing and Fixing Android Memory Leaks with Perfetto, SQL, and AI Agents

Chain Perfetto collection, SQL aggregation, and AI agent filtering into a reusable Android memory leak investigation pipeline.
The article introduces a systematic approach to Android memory leak investigation by recombining three existing tools: Perfetto collects Java heap and native memory trajectories in a time series, SQL turns massive snapshots into queryable structures and narrows candidates via class-level growth ranking, and AI agents read reference chains and source context to judge which growths are genuinely suspicious lifecycle mismatches and draft fixes. The author positions Perfetto's value in multiple collections and observing growth curves that don't drop after GC, SQL as turning manual heap dump flipping into pattern-based queries, and AI agents as scope-narrowing assistants rather than final arbiters. This method complements tools like LeakCanary, though native leaks and system-level issues remain hard to fully cover.
Memory leaks have long been one of the trickiest problems in Android development: they don't surface immediately like crashes, but over time they slow down the app and increase the likelihood of OOM. Traditional approaches rely on point-by-point investigation with MAT or LeakCanary, but a more systematic approach is emerging—using Perfetto to capture system-level traces, SQL to batch-analyze heap data, and AI agents to assist with localization and fix recommendations.
Why Combine Perfetto, SQL, and AI Agents
According to a technical write-up on Hacker News, the workflow proposed by the author doesn't introduce new tools but rather recombines three existing ones. Perfetto captures Java heap and native memory timelines, SQL turns massive snapshots into queryable datasets, and AI agents take on the repetitive work of "narrowing down among a large set of candidate objects." Each step individually isn't novel, but chaining them together transforms debugging from "flipping through heap dumps by intuition" into "progressively converging based on query results."
The value of this combination lies in its clear division of labor: Perfetto answers "when and where," SQL answers "which objects are continuously growing," and AI agents answer "which of these growths involve truly suspicious reference chains." For complex applications, leaks often hide in corners like third-party SDKs, singleton holders, and anonymous callbacks—manually reviewing heap dumps is extremely costly.
Perfetto is the system-level tracing infrastructure on Android that has gradually replaced systrace since Android 10. Open-sourced by Google, it includes a collection daemon (traced), a tracing protocol (protobuf format), an analysis library (TraceProcessor), and a visualization UI (Perfetto UI). It supports hundreds of data sources, including ftrace, atrace, Java heap sampling, native memory allocation (heapprofd), GC events, CPU scheduling, and more, and can align events from different sources onto a unified timeline. Compared to older tools, Perfetto trace files are structured protobufs that can be queried directly using a SQL engine (TraceProcessor has built-in SQLite)—this is precisely the prerequisite that enables feeding trace data into SQL analysis in this article.
heapprofd is Perfetto's native heap profiler, which records malloc/free call stacks through sampling to observe native memory growth trends. Unlike the Java heap, native allocations are not managed by GC, so leaks tend to be more hidden. The native memory timeline mentioned in the article primarily relies on this mechanism; configuration requires specifying the target process and sampling interval, and overhead increases with higher sampling rates.
Perfetto Collection: Turning Memory Changes into a Timeline
Perfetto is Android's platform-level tracing tool, capable of simultaneously recording Java heap size, native allocations, GC events, and thread activity. The key point emphasized in the article is not capturing a single snapshot, but collecting multiple times in a time series to form comparable memory trajectories. Only when you observe on the timeline that the count of a certain class of objects is monotonically increasing and does not drop after GC do you have sufficient reason to suspect a leak.
In practice, you need to configure appropriate tracing categories and sampling intervals to avoid the overhead of tracing itself interfering with judgment. The author's approach is to design collection windows around suspicious scenarios (e.g., repeatedly entering and exiting a certain page) so that memory curves align with user actions—this way subsequent SQL analysis can associate object growth with specific interactions.
SQL Analysis: Using Queries Instead of Manual Scanning
Heap dumps and trace data are massive, making direct reading almost infeasible. The author's solution is to import snapshot data into a queryable structure (e.g., class names, instance counts, reference relationships, timestamps) and use SQL for aggregation and comparison. Typical queries include: counting classes whose instance counts continuously grow over time periods, identifying object sets held by singletons or static fields, and comparing reference chain differences between two snapshots.
The insight here is that memory leaks manifest at the data level as "instance counts of a specific class growing linearly with the number of operations"—a pattern very well suited to SQL expression. Compared to manually expanding items one by one in a heap analyzer, SQL can compress the candidate range from tens of thousands of classes down to a handful of anomalous ones, greatly reducing subsequent analysis costs.
The common format for heap dumps is HPROF (Heap Profile), defined by the JVM/ART, containing class metadata, instance field values, reference relationships, and the set of root objects. Raw HPROF is a binary format and cannot be directly queried with SQL; it usually needs to be parsed into table structures first—for example, using MAT's parsing library, Google's hprof tool, or a custom parser—then exported as CSV/Parquet and imported into SQLite or DuckDB. Key tables include: class table (class name, instance count, shallow size), instance table (object ID, class ID, field values), and reference table (source object ID, target object ID, reference type).
A commonly used SQL pattern for leak analysis is differential querying: perform a FULL OUTER JOIN on the instance tables of two snapshots by class to find classes whose instance counts only increase and never decrease; then combine with the reference table for reachability analysis to determine whether these instances are still strongly referenced by GC Roots (static fields, thread stacks, JNI global references, etc.). Perfetto's TraceProcessor also exposes a SQL interface that can directly aggregate heap sampling tables within trace files, eliminating the export step.
AI Agents: Handling Candidate Filtering and Fix Recommendations
The suspicious classes filtered out by SQL may still contain many false positives, such as normal growth from caches and object pools. The article mentions using AI agents to further analyze reference chains and code context, determining which growth is by design and which is a genuine lifecycle mismatch. The advantage of AI agents is that they can simultaneously read heap data fragments and source code, quickly provide explanations of "who holds whom and why it hasn't been released," and draft fix directions—for example, switching to weak references, cleaning up listeners in lifecycle callbacks, or breaking strong references from static singletons.
What requires caution is that conclusions given by AI agents still need developer review. There is a gap between heap data and code semantics; agents may misjudge normal caches as leaks, or miss cross-process or native-layer issues. Positioning them as "assistants that narrow the scope" rather than "final arbiters" is more realistic.
Implementation Suggestions and Limitations
To put this pipeline into use, you can start with a specific suspicious scenario: first define reproduction steps, use Perfetto to capture the memory trajectory under that scenario, import into SQL for class-level growth ranking, and then hand the top candidates to an AI agent for analysis. Throughout the process, the reusability of collection configurations and analysis scripts determines long-term benefits.
The limitations are also obvious: Perfetto tracing has a learning curve, SQL analysis requires designing a data model in advance, and the reliability of AI agents depends on the quality of context. In addition, native memory leaks and some system-level issues remain difficult to fully cover. This approach is better suited as a supplement to existing tools rather than a replacement for lightweight detection like LeakCanary.
For teams pursuing stability, engineering and datafying memory leak investigation is itself a direction worth investing in. Perfetto provides observability, SQL provides scalable analysis capability, and AI agents provide semantic understanding capability—together, the three fill exactly the gap in traditional workflows where "there's too much data and too few hands."
LeakCanary is Square's open-source runtime leak detection library. Its principle is to monitor whether an object is reclaimed after Activity/Fragment destruction via weak references + ReferenceQueue; if not reclaimed, it triggers a heap dump and uses Shark to analyze the shortest strong reference chain. Its advantages are zero configuration and instant alerts, making it suitable for catching point leaks during development; its limitations are that it only covers objects with clear lifecycles, and each heap dump trigger incurs performance overhead, making it unsuitable for long-term online collection.
The pipeline in this article is complementary: LeakCanary answers "did this object leak?", Perfetto+SQL answers "which class of objects continuously grows under what operations," and AI agents answer "why." In practice, you can first use LeakCanary during development to quickly locate obvious leaks, then use this article's method in staging or canary environments for systematic regression, covering slow-growth leaks that LeakCanary is less likely to trigger.
One-line Summary
Chaining Perfetto collection, SQL aggregation, and AI agent filtering into a reusable Android memory leak investigation pipeline.
Paragraph Summary
The article introduces a systematic approach to Android memory leak investigation, centered on recombining three existing tools: Perfetto captures Java heap and native memory trajectories in a time series, SQL turns massive snapshots into queryable structures and compresses the candidate range through class-level growth ranking, and AI agents read reference chains and source code context to judge which growths are genuinely suspicious lifecycle mismatches and draft fix directions. The author emphasizes that Perfetto's value lies in multiple collections and observing object growth curves that don't drop after GC; SQL turns manual heap dump flipping into pattern-based queries; and AI agents are positioned as scope-narrowing assistants rather than final arbiters. This method is suitable as a supplement to tools like LeakCanary, while native leaks and system-level issues remain difficult to fully cover.
Related articles

Tencent WorkBuddy in Practice: Building an AI Automated Testing Workbench with SKILL Capabilities
Based on Bilibili creator Baili Yang's sharing, this article analyzes how Tencent WorkBuddy AI agent desktop workbench can be used for automated testing: the shift from AI-assisted to AI-led, the relationship among large models, agents, and SKILL capabilities, zero-configuration installation and permission control, and practical ideas for building a personal AI automated testing workbench.

Adding Authentication to Remix SaaS Apps: A Practical Guide to WorkOS AuthKit
Based on the official WorkOS AuthKit guide, this article covers the full approach to integrating authentication in Remix or React Router SaaS apps, including session management, protected routes, multi-tenant organizations, enterprise SSO, and SCIM sync, and analyzes its engineering value for SaaS teams.

Claude Code v2.1.335 Update: Remote MCP Connections and Enhanced Terminal Experience
Claude Code v2.1.335 update explained: new claude mcp add --web remote MCP connections, Tab completion, fullscreen file peeking, harness-audit tool, and batch fixes for Windows/macOS and VS Code.