Perfetto, SQL & AI Agents: Automated Android Memory Leak Triage & Regression Tests

Google’s Android system health stack unifies lightweight production heap graphs (android.java_hprof), kernel RSS/swap counters, PerfettoSQL dominator-tree queries, warehouse-scale BigTrace clustering, and an open-source agentskills.io coding-agent skill. Instead of manually inspecting multi-hundred-megabyte .hprof files, AI agents query exact retaining field chains, patch Kotlin lifecycle bugs, and verify fixes with unit regression tests.
Perfetto, SQL & AI Agents: Automated Android Memory Leak Triage & Regression Tests: Google’s Android system health stack unifies lightweight production heap graphs (android.java_hprof), kernel RSS/swap counters, PerfettoSQL dominator-tree queries, warehouse-scale BigTrace clustering, and an open-source agentskills.io coding-agent skill. Instead of manually inspecting multi-hundred-megabyte .hprof files, AI agents query exact retaining field chains, patch Kotlin lifecycle bugs, and verify fixes with unit regression tests. Designed as a zero-dependency, open-source TypeScript architecture under the MIT License with native Model Context Protocol (MCP) support and deterministic phase state machines.
- Privacy-Safe Production Capture: android.java_hprof strips primitive strings and pixel buffers, recording only object classes, shallow/native sizes, and reference edges.
- Unified Java + Native Forensics: Correlates ART dominator trees with NativeAllocationRegistry, heapprofd C/C++ stacks, anon_rss, swap, and oom_score_adj.
- Deterministic PerfettoSQL Modules: Query android.memory.heap_graph.class_summary_tree and dominator_tree in CI via trace_processor_shell or Python.
- Automated Agent TDD Loop: Perfetto’s agentskills.io workflow traces leaked Fragment/Coroutine chains to Kotlin source lines and verifies NonCancellable/LifecycleOwner fixes.
import { createAgent } from '@smoke-monkey/harness';// Autonomous Android memory leak triage agent powered by Perfetto trace_processorconst leakHunter = createAgent({agentId: 'perfetto-android-leak-hunter',provider: 'anthropic',model: 'claude-sonnet-5-5',workspacePath: process.cwd(),permissions: {read_file: 'allow',write_file: 'allow',run_command: 'ask',},mcpServers: {filesystem: {command: 'npx',args: ['-y', '@modelcontextprotocol/server-filesystem', process.cwd()],},},});async function diagnoseTrace() {const result = await leakHunter.run('Query ./traces/photo_picker_leak.perfetto-trace with trace_processor_shell using android.memory.heap_graph.dominator_tree, map the top retaining reference chain to Kotlin source, patch the LifecycleOwner leak, and add a unit regression test.');console.log('Perfetto triage complete:', result.summary);}diagnoseTrace().catch(console.error);
Watch: Related Video Guides
How to use Perfetto Traces to Debug Performance Issues
Debug Android Performance with Tracing & Perfetto | Find and Fix App Bottlenecks
Why Perfetto Heap Graphs Beat Traditional .hprof Snapshots
Traditional JVM .hprof dumps serialize every string, primitive array, and pixel buffer, creating multi-hundred-megabyte artifacts restricted to debuggable builds and isolated from OS telemetry. Perfetto (android.java_hprof) captures only the live object reference graph—classes, shallow sizes, NativeAllocationRegistry native bytes, and field edges—making snapshots fast, privacy-safe, and runnable on production builds.
| Real-World Android Leak Pattern | Retaining Root Signature | Production Case Study | Verified Kotlin Remediation |
|---|---|---|---|
| Callback Registry Mismatch | ActivityResultRegistry -> ExternalSyntheticLambda0 -> Fragment | Google Messages (142.3 MB retained) | Pass fragment as LifecycleOwner or use fragment.registerForActivityResult() |
| Window-Root Scope Leak | decorView / ViewTreeObserver -> OnPreDrawListener -> RecyclerView | YouTube (88.4 MB avg cluster) | Attach insets listener to target View or remove in view.doOnDetach {} |
| Cancelled Coroutine Teardown | uiScope.launch throws CancellationException before unbind() | Google Camera (64.8 MB + [native]) | Wrap cleanup inside uiScope.launch(NonCancellable) { ... } |
| Unbounded Asset / Queue Retention | LruCache missing sizeOf() or unbounded LinkedBlockingQueue | Google Photos / Pixel Watch | Implement Closeable, override sizeOf(), and bound I/O executor queues |
Pinpointing Retained Heap Objects with PerfettoSQL & BigTrace
Sorting raw heap objects by Object Size highlights noise like byte[] and java.lang.String. Perfetto’s standard library exposes dominator tree SQL modules (android.memory.heap_graph.*) that rank classes and exact object instances by how much memory becomes unreachable if collected.
-- 1. Find classes dominating retained memory along GC root shortest paths
INCLUDE PERFETTO MODULE android.memory.heap_graph.class_summary_tree;
SELECT
name AS class_name,
root_type,
self_count,
cumulative_size / (1024 * 1024) AS retained_mb
FROM android_heap_graph_class_summary_tree
ORDER BY cumulative_size DESC
LIMIT 20;
-- 2. Inspect the exact parent field pinning a leaked Fragment
SELECT
oc.name AS owner_class,
r.field_name,
rc.name AS referent_class,
ro.self_size
FROM heap_graph_reference r
JOIN heap_graph_object oo ON r.owner_id = oo.id
JOIN heap_graph_class oc ON oo.type_id = oc.id
JOIN heap_graph_object ro ON r.owned_id = ro.id
JOIN heap_graph_class rc ON ro.type_id = rc.id
WHERE rc.name LIKE '%AttachmentSheetFragment%';For fleet-wide telemetry (e.g., 10,000+ lab or beta traces in GCS), BigTrace distributes trace_processor across stateless gRPC workers and aggregates peak retained bytes into Pandas DataFrames, while TF-IDF + Silhouette-optimized K-Means clustering collapses 50 noisy dumps into 3 distinct root-cause clusters (Silhouette score 0.84).
Dominated Object Size vs Shallow Object Size
Always switch the Perfetto Heap Dump Explorer metric from Object Size to Dominated Object Size (or query heap_graph_dominator_tree) so a 64-byte Kotlin wrapper pinning a 24 MB [native] hardware buffer surfaces at the top.
Reproducible CLI Capture & Perfetto AI Agent Skill Setup
Capture a production heap snapshot without modifying build.gradle, install Perfetto’s agentskills.io skill (heap_dump.md, heap_dump_caching_optimizer.md, heap_dump_cluster.md), and run SQL triage directly from your terminal or Smoke Monkey Harness.
# 1. Download Perfetto capture helpers and record an ART heap snapshot
curl -O https://raw.githubusercontent.com/google/perfetto/main/tools/java_heap_dump
chmod +x java_heap_dump
./java_heap_dump -n com.example.myapp --wait-for-oom -o ./oom_heap.perfetto-trace
# 2. Install the official Perfetto AI coding-agent skill
curl -fsSL https://get.perfetto.dev/agents-install | python3 - --target .claude/skills
# 3. Execute automated PerfettoSQL leak checks in CI
pip install perfetto
trace_processor_shell -q check_leaks.sql ./oom_heap.perfetto-traceOnce grounded in the trace, the coding agent writes a kotlinx-coroutines-test reproduction test, verifies failure before the patch, applies the NonCancellable or LifecycleOwner fix, and confirms green Gradle execution before opening a pull request.
Frequently Asked Questions
Q:Can Perfetto capture Java/Kotlin heap dumps on non-debuggable Android builds?
Yes. The android.java_hprof data source records a lightweight reference graph without string values or bitmap pixel buffers, allowing fast, privacy-safe captures on release/userdebug builds without app code changes.
Q:What is the difference between Object Size and Dominated Object Size in Perfetto?
Object Size shows raw bytes of primitive types like byte[] and String, whereas Dominated Object Size reorganizes the flamegraph by the dominator tree to show the exact total memory (including [native] buffers) freed if an object is collected.
Q:How does Perfetto integrate with AI coding agents like Smoke Monkey or Claude Code?
Perfetto publishes an open-source agentskills.io skill bundling a trace_processor wrapper and workflows for single-dump dominator triage, duplicate-object caching audits, and TF-IDF multi-trace fleet clustering.
Q:How do you fix a Kotlin coroutine teardown leak where unbind() never runs?
When Fragment.onDestroyView() cancels uiScope immediately after calling controller.onClose(), uiScope.launch aborts with CancellationException before unbind() executes. Wrapping cleanup in uiScope.launch(NonCancellable) guarantees teardown completion.
Q:How does BigTrace scale PerfettoSQL across thousands of traces?
BigTrace distributes PerfettoSQL queries over gRPC across a stateless cluster of trace_processor workers (Docker or Kubernetes) reading directly from cloud object storage and returning an aggregated Pandas DataFrame.
Related Alternatives & Comparisons
Related Architecture Guides
View all guidesBest Open Source Coding Agents in 2026: Free, Local & Fully Hackable Harnesses
MCP Server Security Best Practices: Hardening Model Context Protocol Agents in 2026
Open Source Coding Agent Harness: Build a Forkable, Local AI Engineering Runtime
Build with Smoke Monkey Harness
Zero dependencies. 24 built-in tools. Human-in-the-loop safety. 100% open source under the MIT License.