ui: compare heap dumps in the Heap Dump Explorer flamegraph

Add a "Compare with" picker to the Flamegraph tab that diffs the selected
dump against another dump of the trace. Path hashes differ per dump, so
compared dumps concatenate them instead of grouping by them, and a
path-hash pivot is cleared when a comparison starts. Self Count is
compared too.
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/heap_dump_page.ts b/ui/src/plugins/com.android.HeapDumpExplorer/heap_dump_page.ts
index 4799827..8b8e72e 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/heap_dump_page.ts
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/heap_dump_page.ts
@@ -21,6 +21,7 @@
 import {Tabs} from '../../widgets/tabs';
 import type {TabsTab} from '../../widgets/tabs';
 import {formatDuration} from '../../components/time_utils';
+import {DurationWidget} from '../../components/widgets/duration';
 import type {NavState, NavView} from './nav_state';
 import type {HeapDump} from './types';
 import {OverviewView} from './views/overview_view';
@@ -114,6 +115,11 @@
         trace,
         upid: activeDump.upid,
         ts: activeDump.ts,
+        dumps: session.dumps,
+        baselineDump: session.baselineDump,
+        onBaselineDumpChange: session.setBaselineDump.bind(session),
+        processLabel,
+        dumpLabel: (d) => dumpLabel(session, d),
         state: session.flamegraphPanelState,
         onStateChange: session.setFlamegraphPanelState.bind(session),
         onShowObjects: (pathHashes, isDominator) =>
@@ -275,17 +281,24 @@
   return d.pid !== null ? `${name} (pid ${d.pid})` : name;
 }
 
+function dumpLabel(session: HeapDumpExplorerSession, d: HeapDump): string {
+  const offset = Time.diff(d.ts, session.trace.traceInfo.start);
+  return `${processLabel(d)} — ${formatDuration(session.trace, offset)}`;
+}
+
 function renderDumpSelector(session: HeapDumpExplorerSession): m.Children {
   const allDumps = session.dumps;
   const active = session.activeDump;
   if (allDumps.length <= 1 || active === null) return null;
 
+  const offset = Time.diff(active.ts, session.trace.traceInfo.start);
   return m(
     '.pf-hde-dump-selector',
     m('span.pf-hde-dump-selector__label', 'Heap dump:'),
     m(
       PopupMenu,
       {
+        fitContent: true,
         trigger: m(Button, {
           label: processLabel(active),
           icon: 'memory',
@@ -295,14 +308,14 @@
         }),
       },
       allDumps.map((d) => {
-        const offset = Time.diff(d.ts, session.trace.traceInfo.start);
         return m(MenuItem, {
-          label: `${processLabel(d)} — ${formatDuration(session.trace, offset)}`,
+          label: dumpLabel(session, d),
           active: d === active,
           onclick: () => session.selectDump(d),
         });
       }),
     ),
+    m(DurationWidget, {trace: session.trace, dur: offset}),
   );
 }
 
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/persisted_state.ts b/ui/src/plugins/com.android.HeapDumpExplorer/persisted_state.ts
index c567118..a628559 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/persisted_state.ts
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/persisted_state.ts
@@ -55,6 +55,8 @@
     instanceTabs: z.array(INSTANCE_TAB_SCHEMA).optional(),
     // Filter / pivot / view state of the main Flamegraph tab.
     flamegraphPanelState: TREE_EXPLORER_STATE_SCHEMA.optional(),
+    // The dump the main Flamegraph tab is compared with.
+    baselineDump: DUMP_REF_SCHEMA.optional(),
     // Filter / pivot / view state of the Callstack tab.
     callstackPanelState: TREE_EXPLORER_STATE_SCHEMA.optional(),
   })
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/session.ts b/ui/src/plugins/com.android.HeapDumpExplorer/session.ts
index 218e901..a342742 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/session.ts
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/session.ts
@@ -143,6 +143,7 @@
         s.flamegraphTabs = undefined;
         s.instanceTabs = undefined;
         s.flamegraphPanelState = undefined;
+        s.baselineDump = undefined;
         s.callstackPanelState = undefined;
       });
     }
@@ -165,6 +166,7 @@
       s.flamegraphTabs = undefined;
       s.instanceTabs = undefined;
       s.flamegraphPanelState = undefined;
+      s.baselineDump = undefined;
       s.callstackPanelState = undefined;
     });
   }
@@ -379,6 +381,29 @@
     });
   }
 
+  // The dump the main Flamegraph tab is compared with, if any.
+  get baselineDump(): HeapDump | undefined {
+    const ref = this.storage.get().baselineDump;
+    if (ref === undefined) return undefined;
+    const dump = this._dumps.find(
+      (d) => d.upid === ref.upid && d.ts === BigInt(ref.ts),
+    );
+    // A link can name the active dump, which can't be compared with itself.
+    return dump === this.activeDump ? undefined : dump;
+  }
+
+  setBaselineDump(dump: HeapDump | undefined): void {
+    this.edit((s) => {
+      s.baselineDump =
+        dump === undefined
+          ? undefined
+          : {upid: dump.upid, ts: dump.ts.toString()};
+      if (dump !== undefined) {
+        s.flamegraphPanelState = withoutPathHashPivot(s.flamegraphPanelState);
+      }
+    });
+  }
+
   get callstackPanelState(): TreeExplorerState | undefined {
     return this.storage.get().callstackPanelState;
   }
@@ -397,6 +422,8 @@
     label: string,
     isDominator: boolean,
   ): void {
+    // A path hash names a node of the active dump only.
+    this.setBaselineDump(undefined);
     this.setFlamegraphPanelState({
       selectedMetricId: isDominator
         ? METRIC_DOMINATED_OBJECT_SIZE
@@ -414,6 +441,20 @@
   }
 }
 
+// A path hash names a node of the active dump only, so a pivot at one (see
+// openFlamegraphPivotedAt) matches nothing once another dump is shown too.
+function withoutPathHashPivot(
+  state: TreeExplorerState | undefined,
+): TreeExplorerState | undefined {
+  if (
+    state?.view.kind !== 'PIVOT' ||
+    !/^\/\^-?\d+\$\/$/.test(state.view.pivot)
+  ) {
+    return state;
+  }
+  return {...state, view: {kind: 'TOP_DOWN'}};
+}
+
 function makeHref(sub: string | undefined): string {
   return `#!/heapdump${sub ? '/' + sub : ''}`;
 }
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/storage_schema_unittest.ts b/ui/src/plugins/com.android.HeapDumpExplorer/storage_schema_unittest.ts
index 00bf406..32cec22 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/storage_schema_unittest.ts
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/storage_schema_unittest.ts
@@ -34,6 +34,7 @@
       flamegraphTabs: [{pathHashes: 'abc', isDominator: true}],
       instanceTabs: [{objId: 42, label: 'java.lang.String'}],
       flamegraphPanelState: TREE_STATE,
+      baselineDump: {upid: 5, ts: '323456789012345'},
       callstackPanelState: TREE_STATE,
     };
     expect(HDE_STATE_SCHEMA.parse(state)).toEqual(state);
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/styles.scss b/ui/src/plugins/com.android.HeapDumpExplorer/styles.scss
index 952b319..02fbb20 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/styles.scss
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/styles.scss
@@ -90,6 +90,15 @@
   color: var(--pf-color-text-hint);
 }
 
+// Dump picker above the Flamegraph tab's tree explorer.
+.pf-hde-flamegraph-dumps {
+  display: flex;
+  align-items: center;
+  gap: 0.5rem;
+  padding: 0.5rem 1rem 0;
+  font-size: 0.875rem;
+}
+
 .pf-hde-error-text {
   color: var(--pf-color-danger);
   padding: 1rem;
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view.ts b/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view.ts
index 6522c9b..f8732be 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view.ts
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view.ts
@@ -15,7 +15,8 @@
 import m from 'mithril';
 import {download} from '../../../base/download_utils';
 import type {Trace} from '../../../public/trace';
-import type {time} from '../../../base/time';
+import {Time, type time} from '../../../base/time';
+import {DurationWidget} from '../../../components/widgets/duration';
 import {
   TreeExplorerFetcher,
   type TreeExplorerQueryMetric,
@@ -37,7 +38,10 @@
   type PprofProfileType,
 } from '../../../base/trace_converter';
 
+import {Button} from '../../../widgets/button';
+import {MenuItem, PopupMenu} from '../../../widgets/menu';
 import {showModal} from '../../../widgets/modal';
+import {Stack, StackAuto, StackFixed} from '../../../widgets/stack';
 import {
   mergedClassNodeIcon,
   mergedClassNodeTooltipRenderer,
@@ -45,9 +49,10 @@
 import {
   MERGED_CLASS_FLAMEGRAPH_PROPERTY,
   MERGED_CLASS_PROPERTY,
-  mergedClassColumnSql,
+  mergedClassNamesSql,
 } from '../../dev.perfetto.HeapProfile/merged_class_sql';
 import {NUM} from '../../../trace_processor/query_result';
+import type {HeapDump} from '../types';
 
 // Referenced by session.openFlamegraphPivotedAt.
 export const METRIC_OBJECT_SIZE = 'Object Size';
@@ -57,6 +62,13 @@
   readonly trace: Trace;
   readonly upid: number;
   readonly ts: time;
+  // Every heap dump of the trace: this one can be compared with the others.
+  readonly dumps: ReadonlyArray<HeapDump>;
+  // The dump the flamegraph is compared with, if any.
+  readonly baselineDump: HeapDump | undefined;
+  readonly onBaselineDumpChange: (dump: HeapDump | undefined) => void;
+  readonly processLabel: (dump: HeapDump) => string;
+  readonly dumpLabel: (dump: HeapDump) => string;
   readonly state: TreeExplorerState | undefined;
   readonly onStateChange: (state: TreeExplorerState) => void;
   // Open the flamegraph-objects tab for `pathHashes` (CSV).
@@ -91,11 +103,45 @@
   mergeAggregation: 'SUM' as const,
 };
 
-// Build a JAVA_HEAP_GRAPH metric for the BFS or dominator class tree,
-// projecting `valueColumn` as `value` and the other column for tooltips.
+// Self Count of the baseline dump, when compared with one.
+const SELF_COUNT_BASELINE = 'baseline_self_count';
+
+// Several dumps can't be grouped by path_hash_stable: the hash is computed per
+// dump, so it would keep their nodes apart. It is concatenated instead, as
+// dev.perfetto.HeapProfile does, so that the objects of a node can still be
+// listed.
+const MULTI_DUMP_UNAGG_PROPS = UNAGG_PROPS.filter(
+  (p) => p.name !== 'path_hash_stable',
+);
+const PATH_HASH_AGG_PROP = {
+  name: 'path_hash_stable',
+  displayName: 'Path Hash',
+  mergeAggregation: 'CONCAT_WITH_COMMA' as const,
+  isVisible: () => false,
+};
+
+type DumpRef = Pick<HeapDump, 'upid' | 'ts'>;
+
+function inDumpsSql(dumps: ReadonlyArray<DumpRef>): string {
+  return dumps
+    .map((d) => `(upid = ${d.upid} and graph_sample_ts = ${d.ts})`)
+    .join(' or ');
+}
+
+// '1' if the class named by `t.name` is potentially merged in any of `dumps`.
+function potentiallyMergedColumnSql(dumps: ReadonlyArray<DumpRef>): string {
+  const names = dumps
+    .map((d) => `select name from (${mergedClassNamesSql(d.upid, d.ts)})`)
+    .join(' union ');
+  return `CAST(t.name IN (${names}) AS TEXT) AS ${MERGED_CLASS_PROPERTY}`;
+}
+
+// Build a JAVA_HEAP_GRAPH metric for the BFS or dominator class tree of
+// `dump`, projecting `valueColumn` as `value` and the other column for
+// tooltips. The values of `baselineDump`, if any, are the baseline.
 function buildMetric(
-  upid: number,
-  ts: time,
+  dump: DumpRef,
+  baselineDump: DumpRef | undefined,
   name: string,
   unit: string,
   valueColumn: 'self_size' | 'self_count',
@@ -109,6 +155,13 @@
     ? 'android.memory.heap_graph.dominator_class_tree'
     : 'android.memory.heap_graph.class_tree';
   const otherCol = valueColumn === 'self_size' ? 'self_count' : 'self_size';
+  const compared = baselineDump !== undefined;
+  const allDumps = compared ? [dump, baselineDump] : [dump];
+  // `column` on the rows of `of`, and 0 on the rows of the other dump.
+  const valueOf = (column: string, of: DumpRef) =>
+    compared ? `iif(${inDumpsSql([of])}, ${column}, 0)` : column;
+  // Size metrics show Self Count, which gets its baseline too.
+  const selfCount = valueColumn === 'self_size';
   return {
     name,
     unit,
@@ -120,16 +173,36 @@
         ifnull(name, 'unknown') as name,
         root_type,
         heap_type,
-        ${valueColumn} as value,
-        ${otherCol},
-        CAST(path_hash_stable AS TEXT) AS path_hash_stable,
-        ${mergedClassColumnSql('t.name', upid, ts)}
+        ${valueOf(valueColumn, dump)} as value,
+        ${valueOf(otherCol, dump)} as ${otherCol},
+        ${
+          compared
+            ? `iif(${inDumpsSql([dump])}, CAST(path_hash_stable AS TEXT), NULL)`
+            : 'CAST(path_hash_stable AS TEXT)'
+        }
+          AS path_hash_stable,
+        ${compared ? `${valueOf(valueColumn, baselineDump)} as baseline,` : ''}
+        ${
+          compared && selfCount
+            ? `${valueOf('self_count', baselineDump)} as ${SELF_COUNT_BASELINE},`
+            : ''
+        }
+        ${potentiallyMergedColumnSql(allDumps)}
       from ${tree} t
-      where graph_sample_ts = ${ts} and upid = ${upid}
+      where ${inDumpsSql(allDumps)}
     `,
-    unaggregatableProperties: UNAGG_PROPS,
-    aggregatableProperties:
-      valueColumn === 'self_size' ? [SELF_COUNT_AGG_PROP] : [],
+    baselineColumn: compared ? 'baseline' : undefined,
+    unaggregatableProperties: compared ? MULTI_DUMP_UNAGG_PROPS : UNAGG_PROPS,
+    aggregatableProperties: [
+      ...(selfCount
+        ? [
+            compared
+              ? {...SELF_COUNT_AGG_PROP, baselineName: SELF_COUNT_BASELINE}
+              : SELF_COUNT_AGG_PROP,
+          ]
+        : []),
+      ...(compared ? [PATH_HASH_AGG_PROP] : []),
+    ],
     optionalNodeActions: [showObjectsAction],
   };
 }
@@ -168,9 +241,9 @@
   },
 ];
 
-function buildHeapGraphMetrics(
-  upid: number,
-  ts: time,
+export function buildHeapGraphMetrics(
+  dump: DumpRef,
+  baselineDump: DumpRef | undefined,
   onShowObjects: (pathHashes: string, isDominator: boolean) => void,
 ): ReadonlyArray<TreeExplorerQueryMetric> {
   const showObjectsAction = (
@@ -188,8 +261,8 @@
   });
   return METRIC_SPECS.map((s) =>
     buildMetric(
-      upid,
-      ts,
+      dump,
+      baselineDump,
       s.name,
       s.unit,
       s.valueColumn,
@@ -199,9 +272,55 @@
   );
 }
 
+function renderComparePicker(attrs: FlamegraphViewAttrs): m.Children {
+  const others = attrs.dumps.filter(
+    (d) => !(d.upid === attrs.upid && d.ts === attrs.ts),
+  );
+  if (others.length === 0) return null;
+  const {baselineDump, dumpLabel, processLabel} = attrs;
+  return m(
+    StackFixed,
+    {className: 'pf-hde-flamegraph-dumps'},
+    m(
+      PopupMenu,
+      {
+        fitContent: true,
+        trigger: m(Button, {
+          label:
+            baselineDump === undefined
+              ? 'Compare with'
+              : `Compare with ${processLabel(baselineDump)}`,
+          icon: 'compare_arrows',
+          rightIcon: 'arrow_drop_down',
+          compact: true,
+        }),
+      },
+      [
+        m(MenuItem, {
+          label: 'No comparison',
+          active: baselineDump === undefined,
+          onclick: () => attrs.onBaselineDumpChange(undefined),
+        }),
+        ...others.map((d) =>
+          m(MenuItem, {
+            label: dumpLabel(d),
+            active: d === baselineDump,
+            onclick: () => attrs.onBaselineDumpChange(d),
+          }),
+        ),
+      ],
+    ),
+    baselineDump !== undefined &&
+      m(DurationWidget, {
+        trace: attrs.trace,
+        dur: Time.diff(baselineDump.ts, attrs.trace.traceInfo.start),
+      }),
+  );
+}
+
 export function FlamegraphView(): m.Component<FlamegraphViewAttrs> {
-  // The fetcher is created for the dump it serves and disposed by the memo when
-  // the dump changes or when this view is removed.
+  // The fetcher is created for the dumps it serves and disposed by the memo
+  // when they change or when this view is removed.
   const fetcherMemo = new Memo<TreeExplorerFetcher>();
 
   // Mirrors dev.perfetto.HeapProfile: if the heap graph is incomplete we gate
@@ -215,12 +334,16 @@
 
   return {
     view({attrs}) {
+      const dump: DumpRef = {upid: attrs.upid, ts: attrs.ts};
+      const baselineDump = attrs.baselineDump;
+      const ref = (d: DumpRef | undefined) =>
+        d === undefined ? null : {upid: d.upid, ts: d.ts};
       const fetcher = fetcherMemo.use({
-        key: {upid: attrs.upid, ts: attrs.ts},
+        key: {dump: ref(dump), baselineDump: ref(baselineDump)},
         compute: () =>
           new TreeExplorerFetcher(
             attrs.trace,
-            buildHeapGraphMetrics(attrs.upid, attrs.ts, attrs.onShowObjects),
+            buildHeapGraphMetrics(dump, baselineDump, attrs.onShowObjects),
           ),
       });
       const metrics = fetcher.metrics;
@@ -249,26 +372,38 @@
           incompleteFlamegraphModal(attrs.trace, () => {
             incomplete.dismissed = true;
           }),
-        m(TreeExplorerPanel, {
-          fetcher,
-          state,
-          onStateChange: attrs.onStateChange,
-          nodeIcon: MERGED_CLASS_NODE_ICON,
-          renderNodeTooltip: MERGED_CLASS_NODE_TOOLTIP,
-          extraDownloadItems: [
-            {
-              label: 'Pprof profile (.pb)',
-              icon: 'file_download',
-              description:
-                'Whole snapshot, converted from the trace: filters, the ' +
-                'selected measure and the view direction are not applied.',
-              title:
-                'Download the full profile as pprof, for use with pprof tools',
-              onDownload: () =>
-                downloadPprof(attrs.trace, attrs.upid, attrs.ts),
-            },
-          ],
-        }),
+        m(Stack, {fillHeight: true, spacing: 'none'}, [
+          renderComparePicker(attrs),
+          m(
+            StackAuto,
+            m(TreeExplorerPanel, {
+              fetcher,
+              state,
+              onStateChange: attrs.onStateChange,
+              nodeIcon: MERGED_CLASS_NODE_ICON,
+              renderNodeTooltip: MERGED_CLASS_NODE_TOOLTIP,
+              // A pprof holds one snapshot, so it can't show a diff.
+              extraDownloadItems:
+                baselineDump !== undefined
+                  ? []
+                  : [
+                      {
+                        label: 'Pprof profile (.pb)',
+                        icon: 'file_download',
+                        description:
+                          'Whole snapshot, converted from the trace: ' +
+                          'filters, the selected measure and the view ' +
+                          'direction are not applied.',
+                        title:
+                          'Download the full profile as pprof, for use ' +
+                          'with pprof tools',
+                        onDownload: () =>
+                          downloadPprof(attrs.trace, attrs.upid, attrs.ts),
+                      },
+                    ],
+            }),
+          ),
+        ]),
       ];
     },
     onremove() {
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view_unittest.ts b/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view_unittest.ts
new file mode 100644
index 0000000..735b7e1
--- /dev/null
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view_unittest.ts
@@ -0,0 +1,36 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import {Time} from '../../../base/time';
+import {buildHeapGraphMetrics} from './flamegraph_view';
+
+const DUMP_A = {upid: 1, ts: Time.fromRaw(100n)};
+const DUMP_B = {upid: 2, ts: Time.fromRaw(200n)};
+
+function groupingColumns(
+  dump: typeof DUMP_A,
+  baselineDump?: typeof DUMP_A,
+): string[] {
+  return buildHeapGraphMetrics(dump, baselineDump, () => {}).flatMap((metric) =>
+    (metric.unaggregatableProperties ?? []).map((p) => p.name),
+  );
+}
+
+test('one dump groups nodes by their path hash', () => {
+  expect(groupingColumns(DUMP_A)).toContain('path_hash_stable');
+});
+
+test('compared dumps are not grouped by the per-dump path hash', () => {
+  expect(groupingColumns(DUMP_A, DUMP_B)).not.toContain('path_hash_stable');
+});