ui: diff heap dumps in the Heap Dump Explorer flamegraph Add a "Compare with" picker above the Flamegraph tab to compare the selected heap dump against another dump in the trace using TreeExplorer's baseline diff support. Compared dumps are not grouped by path_hash_stable, which differs per dump; it is concatenated instead so "Show objects from this class" still lists the node's objects, and active path-hash pivots are cleared when starting a comparison.
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..3bd51f9 100644 --- a/ui/src/plugins/com.android.HeapDumpExplorer/heap_dump_page.ts +++ b/ui/src/plugins/com.android.HeapDumpExplorer/heap_dump_page.ts
@@ -114,6 +114,10 @@ trace, upid: activeDump.upid, ts: activeDump.ts, + dumps: session.dumps, + compareWith: session.flamegraphCompareWith, + onCompareWithChange: session.setFlamegraphCompareWith.bind(session), + dumpLabel: (d) => dumpLabel(session, d), state: session.flamegraphPanelState, onStateChange: session.setFlamegraphPanelState.bind(session), onShowObjects: (pathHashes, isDominator) => @@ -275,6 +279,11 @@ 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; @@ -295,9 +304,8 @@ }), }, 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), });
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/persisted_state.ts b/ui/src/plugins/com.android.HeapDumpExplorer/persisted_state.ts index c567118..57f39c4 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. + flamegraphCompareWith: 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..d5038d98 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.flamegraphCompareWith = undefined; s.callstackPanelState = undefined; }); } @@ -165,6 +166,7 @@ s.flamegraphTabs = undefined; s.instanceTabs = undefined; s.flamegraphPanelState = undefined; + s.flamegraphCompareWith = undefined; s.callstackPanelState = undefined; }); } @@ -379,6 +381,29 @@ }); } + // The dump the main Flamegraph tab is compared with, if any. + get flamegraphCompareWith(): HeapDump | undefined { + const ref = this.storage.get().flamegraphCompareWith; + 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; + } + + setFlamegraphCompareWith(dump: HeapDump | undefined): void { + this.edit((s) => { + s.flamegraphCompareWith = + 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.setFlamegraphCompareWith(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..d5c12a3 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, + flamegraphCompareWith: {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..d3f56a8 100644 --- a/ui/src/plugins/com.android.HeapDumpExplorer/styles.scss +++ b/ui/src/plugins/com.android.HeapDumpExplorer/styles.scss
@@ -90,6 +90,16 @@ color: var(--pf-color-text-hint); } +// Dump picker above the Flamegraph tab's tree explorer. +.pf-hde-flamegraph-dumps { + padding: 0.5rem 1rem 0; + font-size: 0.875rem; + + &__hint { + color: var(--pf-color-text-hint); + } +} + .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..4c48b7f 100644 --- a/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view.ts +++ b/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view.ts
@@ -37,7 +37,10 @@ type PprofProfileType, } from '../../../base/trace_converter'; +import {Button} from '../../../widgets/button'; +import {MenuItem, PopupMenu} from '../../../widgets/menu'; import {showModal} from '../../../widgets/modal'; +import {Inline, Stack, StackAuto, StackFixed} from '../../../widgets/stack'; import { mergedClassNodeIcon, mergedClassNodeTooltipRenderer, @@ -45,9 +48,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 +61,12 @@ 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 compareWith: HeapDump | undefined; + readonly onCompareWithChange: (dump: HeapDump | undefined) => void; + readonly dumpLabel: (dump: HeapDump) => string; readonly state: TreeExplorerState | undefined; readonly onStateChange: (state: TreeExplorerState) => void; // Open the flamegraph-objects tab for `pathHashes` (CSV). @@ -91,11 +101,42 @@ 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. +// 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 +150,11 @@ ? '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; return { name, unit, @@ -120,16 +166,21 @@ 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}, + iif(${inDumpsSql([dump])}, CAST(path_hash_stable AS TEXT), NULL) + AS path_hash_stable, + ${compared ? `${valueOf(valueColumn, baselineDump)} as 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: [ + ...(valueColumn === 'self_size' ? [SELF_COUNT_AGG_PROP] : []), + ...(compared ? [PATH_HASH_AGG_PROP] : []), + ], optionalNodeActions: [showObjectsAction], }; } @@ -168,9 +219,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 +239,8 @@ }); return METRIC_SPECS.map((s) => buildMetric( - upid, - ts, + dump, + baselineDump, s.name, s.unit, s.valueColumn, @@ -199,9 +250,56 @@ ); } +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 {compareWith, dumpLabel} = attrs; + return m( + StackFixed, + {className: 'pf-hde-flamegraph-dumps'}, + m(Inline, {spacing: 'small'}, [ + m( + PopupMenu, + { + trigger: m(Button, { + label: + compareWith === undefined + ? 'Compare with' + : `Compare with ${dumpLabel(compareWith)}`, + icon: 'compare_arrows', + rightIcon: 'arrow_drop_down', + compact: true, + }), + }, + [ + m(MenuItem, { + label: 'No comparison', + active: compareWith === undefined, + onclick: () => attrs.onCompareWithChange(undefined), + }), + ...others.map((d) => + m(MenuItem, { + label: dumpLabel(d), + active: d === compareWith, + onclick: () => attrs.onCompareWithChange(d), + }), + ), + ], + ), + compareWith !== undefined && + m( + 'span.pf-hde-flamegraph-dumps__hint', + 'Red: more than the compared dump, blue: less.', + ), + ]), + ); +} + 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 +313,16 @@ return { view({attrs}) { + const dump: DumpRef = {upid: attrs.upid, ts: attrs.ts}; + const baselineDump = attrs.compareWith; + 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 +351,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'); +});