ui: support baseline diffs in Flamegraph

An optional baselineColumn compares the tree with a baseline in the same
flamegraph operator query. Nodes are laid out by their value in both
trees and colored by their change: green for a shrink, grey for none and
yellow to red for a growth, each side scaled by its largest change, with
a legend of that range next to the tabs. The root label and tooltips show
the current, baseline and delta values.
diff --git a/ui/src/components/tree_explorer_fetcher.ts b/ui/src/components/tree_explorer_fetcher.ts
index 657d845..15b59a9 100644
--- a/ui/src/components/tree_explorer_fetcher.ts
+++ b/ui/src/components/tree_explorer_fetcher.ts
@@ -57,6 +57,11 @@
 export interface AggTreeExplorerQueryColumn extends TreeExplorerQueryColumn {
   // The aggregation to be run when nodes are merged together in the tree.
   readonly mergeAggregation: 'ONE_OR_SUMMARY' | 'SUM' | 'CONCAT_WITH_COMMA';
+
+  // Optional column of `statement` holding the property's value in the
+  // baseline (see TreeExplorerQueryMetric.baselineColumn), merged the same
+  // way.
+  readonly baselineName?: string;
 }
 
 export interface TreeExplorerQueryMetric {
@@ -87,6 +92,12 @@
   // `aggregatableProperties`.
   readonly statement: string;
 
+  // Optional numeric column of `statement` holding each row's value in a
+  // baseline to compare the tree with. Nodes are merged the same way for both
+  // values, so each node also gets its values in the baseline, and nodes are
+  // laid out by their value in both trees.
+  readonly baselineColumn?: string;
+
   // Additional contextual columns containing data which should not be merged
   // between sibling nodes, even if they have the same name.
   //
@@ -177,8 +188,17 @@
   readonly metric: TreeExplorerQueryMetric;
   readonly table: DisposableSqlEntity;
   readonly unfilteredCumulativeValue: number;
+  readonly unfilteredBaselineCumulativeValue: number;
+  // The value columns of a diff (see computeTree) the operator has outputs
+  // for: it has none for a column without values, e.g. when the source has no
+  // rows.
+  readonly diffColumns: ReadonlySet<string>;
 }
 
+// With a baseline, `value` holds each row's value in both trees, which lays
+// the nodes out, and this column holds its current value.
+const CURRENT_COLUMN = '_current';
+
 interface MetricTableSlot {
   readonly metric: TreeExplorerQueryMetric;
   readonly memo: AsyncMemo<MetricTable>;
@@ -255,12 +275,21 @@
       ...(metric.unaggregatableProperties ?? []),
       ...(metric.aggregatableProperties ?? []),
     ];
+    const baseline = metric.baselineColumn;
     const sourceColumns = [
       's.id',
       's.parentId as parent_id',
       's.name',
-      's.value',
+      baseline === undefined ? 's.value' : `s.value + s.${baseline} as value`,
       ...properties.map((property) => `s.${property.name}`),
+      ...(metric.aggregatableProperties ?? []).flatMap((property) =>
+        property.baselineName === undefined
+          ? []
+          : [`s.${property.baselineName}`],
+      ),
+      ...(baseline === undefined
+        ? []
+        : [`s.value as ${CURRENT_COLUMN}`, `s.${baseline}`]),
     ];
     const table = await createVirtualTable({
       engine: this.trace.engine,
@@ -270,20 +299,58 @@
       ))`,
     });
     try {
-      const result = await this.trace.engine.query(`
-        select cumulative_value
-        from ${table.name}(__intrinsic_flamegraph_config(
-          'value', 'value',
-          'view', 'TOP_DOWN'
-        ))
-        where __intrinsic_flamegraph_find(_tree_id, 'SUPER_ROOT')
-      `);
+      const diffColumns = new Set<string>();
+      let unfilteredCumulativeValue = 0;
+      let unfilteredBaselineCumulativeValue = 0;
+      if (baseline === undefined) {
+        const result = await this.trace.engine.query(`
+          select cumulative_value
+          from ${table.name}(__intrinsic_flamegraph_config(
+            'value', 'value',
+            'view', 'TOP_DOWN'
+          ))
+          where __intrinsic_flamegraph_find(_tree_id, 'SUPER_ROOT')
+        `);
+        unfilteredCumulativeValue = result.firstRow({
+          cumulative_value: NUM,
+        }).cumulative_value;
+      } else {
+        const names = [CURRENT_COLUMN, baseline].map((column) =>
+          sqliteString(`cumulative_${column}`),
+        );
+        const outputs = await this.trace.engine.query(`
+          select name from pragma_table_info(${sqliteString(table.name)})
+          where name in (${names.join(', ')})
+        `);
+        for (const it = outputs.iter({name: STR}); it.valid(); it.next()) {
+          diffColumns.add(it.name.substring('cumulative_'.length));
+        }
+        if (diffColumns.size > 0) {
+          const hasCurrent = diffColumns.has(CURRENT_COLUMN);
+          const hasBaseline = diffColumns.has(baseline);
+          const configArgs = [
+            `'value', 'value'`,
+            ...(hasCurrent ? [`'value', ${sqliteString(CURRENT_COLUMN)}`] : []),
+            ...(hasBaseline ? [`'value', ${sqliteString(baseline)}`] : []),
+            `'view', 'TOP_DOWN'`,
+          ];
+          const totals = await this.trace.engine.query(`
+            select
+              ${hasCurrent ? `coalesce(sum(self_${CURRENT_COLUMN}), 0)` : '0'} as currentTotal,
+              ${hasBaseline ? `coalesce(sum(self_${baseline}), 0)` : '0'} as baselineTotal
+            from ${table.name}(__intrinsic_flamegraph_config(${configArgs.join(', ')}))
+          `);
+          const row = totals.firstRow({currentTotal: NUM, baselineTotal: NUM});
+          unfilteredCumulativeValue = row.currentTotal;
+          unfilteredBaselineCumulativeValue = row.baselineTotal;
+        }
+      }
       return {
         metric,
         table,
-        unfilteredCumulativeValue: result.firstRow({
-          cumulative_value: NUM,
-        }).cumulative_value,
+        unfilteredCumulativeValue,
+        unfilteredBaselineCumulativeValue,
+        diffColumns,
         [Symbol.asyncDispose]: () => table[Symbol.asyncDispose](),
       };
     } catch (error) {
@@ -304,6 +371,7 @@
     optionalNodeActions,
     optionalRootActions,
     optionalMarker,
+    baselineColumn,
   } = metricTable.metric;
   const agg = aggregatableProperties ?? [];
   const aggCols = agg.map((x) => x.name);
@@ -340,20 +408,49 @@
       `'aggregate', ${sqliteString(column.mergeAggregation)}, ` +
         `${sqliteString(column.name)}, ${sqliteString(column.name)}`,
     );
+    if (column.baselineName !== undefined) {
+      configArgs.push(
+        `'aggregate', ${sqliteString(column.mergeAggregation)}, ` +
+          `${sqliteString(column.baselineName)}, ` +
+          sqliteString(column.baselineName),
+      );
+    }
   }
+  const aggBaselineCols = agg.flatMap((x) =>
+    x.baselineName === undefined ? [] : [x.baselineName],
+  );
+  // With a baseline, the current and baseline values come from extra value
+  // columns, each with self_<name> and cumulative_<name> outputs. A column
+  // without values is 0 everywhere.
+  const diffValue = (column: string) => {
+    if (!metricTable.diffColumns.has(column)) {
+      return {self: '0', cumulative: '0'};
+    }
+    configArgs.push(`'value', ${sqliteString(column)}`);
+    return {self: `self_${column}`, cumulative: `cumulative_${column}`};
+  };
+  const current =
+    baselineColumn === undefined
+      ? {self: 'self_value', cumulative: 'cumulative_value'}
+      : diffValue(CURRENT_COLUMN);
+  const baseline =
+    baselineColumn === undefined ? undefined : diffValue(baselineColumn);
 
   const outputColumns = [
     '_tree_id as id',
     'IFNULL(_tree_parent_id, -1) as parentId',
     'depth',
     `IIF(IFNULL(name, '') = '', 'unknown', name) as name`,
-    'self_value as selfValue',
-    'cumulative_value as cumulativeValue',
+    `${current.self} as selfValue`,
+    `${current.cumulative} as cumulativeValue`,
     'parent_cumulative_value as parentCumulativeValue',
     'x_start as xStart',
     'x_end as xEnd',
     ...unaggCols,
     ...aggCols,
+    ...aggBaselineCols,
+    `${baseline?.cumulative ?? 'NULL'} as baselineCumulativeValue`,
+    `${baseline?.self ?? 'NULL'} as baselineSelfValue`,
   ];
 
   // The operator emits rows pre-ordered for rendering with layout geometry
@@ -377,10 +474,18 @@
     xStart: NUM,
     xEnd: NUM,
     ...Object.fromEntries(unaggCols.map((m) => [m, STR_NULL])),
-    ...Object.fromEntries(aggCols.map((m) => [m, UNKNOWN])),
+    ...Object.fromEntries(
+      [...aggCols, ...aggBaselineCols].map((m) => [m, UNKNOWN]),
+    ),
+    baselineCumulativeValue: NUM_NULL,
+    baselineSelfValue: NUM_NULL,
   });
   let postiveRootsValue = 0;
   let negativeRootsValue = 0;
+  let postiveRootsBaselineValue = 0;
+  let negativeRootsBaselineValue = 0;
+  let maxGrowth = 0;
+  let maxShrink = 0;
   let minDepth = 0;
   let maxDepth = 0;
   const nodes = [];
@@ -403,9 +508,13 @@
       if (r !== null) {
         // UNKNOWN-typed aggregations (e.g. SUM) can yield number/bigint.
         const value = String(r);
+        const baselineValue =
+          a.baselineName === undefined ? null : it.get(a.baselineName);
         properties.set(a.name, {
           displayName: a.displayName,
           value,
+          baselineValue:
+            baselineValue === null ? undefined : String(baselineValue),
           isVisible: a.isVisible ? a.isVisible(value) : true,
           isAggregatable: true,
         });
@@ -434,11 +543,20 @@
       properties,
       marker,
       propertyValues,
+      baselineCumulativeValue: it.baselineCumulativeValue ?? undefined,
+      baselineSelfValue: it.baselineSelfValue ?? undefined,
     });
     if (it.depth === 1) {
       postiveRootsValue += it.cumulativeValue;
+      postiveRootsBaselineValue += it.baselineCumulativeValue ?? 0;
     } else if (it.depth === -1) {
       negativeRootsValue += it.cumulativeValue;
+      negativeRootsBaselineValue += it.baselineCumulativeValue ?? 0;
+    }
+    if (it.baselineCumulativeValue !== null) {
+      const change = it.cumulativeValue - it.baselineCumulativeValue;
+      maxGrowth = Math.max(maxGrowth, change);
+      maxShrink = Math.max(maxShrink, -change);
     }
     minDepth = Math.min(minDepth, it.depth);
     maxDepth = Math.max(maxDepth, it.depth);
@@ -447,6 +565,19 @@
     nodes,
     allRootsCumulativeValue:
       view.kind === 'BOTTOM_UP' ? negativeRootsValue : postiveRootsValue,
+    diff:
+      baselineColumn === undefined
+        ? undefined
+        : {
+            allRootsBaselineCumulativeValue:
+              view.kind === 'BOTTOM_UP'
+                ? negativeRootsBaselineValue
+                : postiveRootsBaselineValue,
+            unfilteredBaselineCumulativeValue:
+              metricTable.unfilteredBaselineCumulativeValue,
+            maxGrowth,
+            maxShrink,
+          },
     unfilteredCumulativeValue: metricTable.unfilteredCumulativeValue,
     minDepth,
     maxDepth,
diff --git a/ui/src/components/tree_explorer_panel.ts b/ui/src/components/tree_explorer_panel.ts
index 9700f5d..2c11dd1 100644
--- a/ui/src/components/tree_explorer_panel.ts
+++ b/ui/src/components/tree_explorer_panel.ts
@@ -18,6 +18,7 @@
 import {EmptyState} from '../widgets/empty_state';
 import {Spinner} from '../widgets/spinner';
 import {Flamegraph, buildFlamegraphExportString} from '../widgets/flamegraph';
+import {renderDiffLegend} from '../widgets/flamegraph_diff';
 import type {ExportDownloadItem} from '../widgets/export_button';
 import {TreeExplorerFilterBar} from '../widgets/tree_explorer_filter_bar';
 import {
@@ -178,6 +179,10 @@
             displayMode: key as TreeExplorerDisplayMode,
           });
         },
+        rightContent:
+          displayMode === 'flamegraph' &&
+          data?.diff !== undefined &&
+          renderDiffLegend(data.diff, unit),
         tabs: [
           {
             key: 'flamegraph',
diff --git a/ui/src/widgets/flamegraph.ts b/ui/src/widgets/flamegraph.ts
index d653dec..033ec4a 100644
--- a/ui/src/widgets/flamegraph.ts
+++ b/ui/src/widgets/flamegraph.ts
@@ -43,6 +43,7 @@
   FILTER_TYPES,
   type FilterType,
   type TreeExplorerData,
+  type TreeExplorerDiff,
   type TreeExplorerFilter,
   type TreeExplorerMetric,
   type TreeExplorerNode,
@@ -57,6 +58,12 @@
   getUnitDisplayName,
   metricId,
 } from './tree_explorer';
+import {
+  diffColor,
+  diffScore,
+  displayDiff,
+  renderDiffTable,
+} from './flamegraph_diff';
 
 const LABEL_FONT_STYLE = '12px Roboto';
 const NODE_HEIGHT = 20;
@@ -390,8 +397,16 @@
               {
                 trigger: m('.popup-anchor', {
                   style: {
-                    left: this.tooltipPos?.x + 'px',
-                    top: this.tooltipPos?.y + 'px',
+                    left:
+                      this.tooltipPos !== undefined
+                        ? `${this.tooltipPos.x}px`
+                        : undefined,
+                    // Center on the bar so row 0 (root) isn't treated as
+                    // clipped off the top edge by Popper's hide modifier.
+                    top:
+                      this.tooltipPos !== undefined
+                        ? `${this.tooltipPos.y + NODE_HEIGHT / 2}px`
+                        : undefined,
                   },
                 }),
                 fitContent: true,
@@ -450,7 +465,7 @@
           this.attrs.data,
           this.zoomRegion ?? {
             queryXStart: 0,
-            queryXEnd: this.attrs.data.allRootsCumulativeValue,
+            queryXEnd: layoutWidth(this.attrs.data),
             type: 'ROOT',
           },
           size.width,
@@ -475,7 +490,7 @@
     const yStart = canvasRect.top;
     const yEnd = canvasRect.bottom;
 
-    const {allRootsCumulativeValue, unfilteredCumulativeValue, nodes} =
+    const {allRootsCumulativeValue, unfilteredCumulativeValue, nodes, diff} =
       this.attrs.data;
     const unit = ensureExists(this.selectedMetric).unit;
 
@@ -500,22 +515,45 @@
       }
 
       const hover = isIntersecting(this.hoveredX, this.hoveredY, node);
+      const greyed = state === 'PARTIAL';
       let name: string;
       let colorScheme;
       if (source.kind === 'ROOT') {
-        const val = displaySize(allRootsCumulativeValue, unit);
-        const percent = displayPercentage(
-          allRootsCumulativeValue,
-          unfilteredCumulativeValue,
-        );
-        name = `root: ${val} (${percent})`;
-        colorScheme = getFlamegraphColorScheme('root', state === 'PARTIAL');
+        if (diff !== undefined) {
+          const baseline = diff.allRootsBaselineCumulativeValue;
+          name = `root: ${displayDiff(baseline, allRootsCumulativeValue, unit)}`;
+          colorScheme = getDiffColorScheme(
+            allRootsCumulativeValue - baseline,
+            diff,
+            greyed,
+          );
+        } else {
+          const val = displaySize(allRootsCumulativeValue, unit);
+          const percent = displayPercentage(
+            allRootsCumulativeValue,
+            unfilteredCumulativeValue,
+          );
+          name = `root: ${val} (${percent})`;
+          colorScheme = getFlamegraphColorScheme('root', greyed);
+        }
       } else if (source.kind === 'MERGED') {
         name = '(merged)';
-        colorScheme = getFlamegraphColorScheme(name, state === 'PARTIAL');
+        // In a diff, nodes too small to draw are shown as unchanged.
+        colorScheme =
+          diff !== undefined
+            ? getDiffColorScheme(0, diff, greyed)
+            : getFlamegraphColorScheme(name, greyed);
       } else {
-        name = nodes[source.queryIdx]!.name;
-        colorScheme = getFlamegraphColorScheme(name, state === 'PARTIAL');
+        const node = nodes[source.queryIdx]!;
+        name = node.name;
+        colorScheme =
+          diff !== undefined
+            ? getDiffColorScheme(
+                node.cumulativeValue - (node.baselineCumulativeValue ?? 0),
+                diff,
+                greyed,
+              )
+            : getFlamegraphColorScheme(name, greyed);
       }
       const highlighted =
         source.kind === 'NODE' &&
@@ -592,9 +630,36 @@
       unfilteredCumulativeValue,
       nodeActions,
       rootActions,
+      diff,
     } = ensureExists(this.attrs.data);
     const {unit, nameColumnLabel} = ensureExists(this.selectedMetric);
+    const allTotals =
+      diff === undefined
+        ? undefined
+        : {
+            baseline: diff.unfilteredBaselineCumulativeValue,
+            current: unfilteredCumulativeValue,
+          };
     if (source.kind === 'ROOT') {
+      if (diff !== undefined) {
+        return m(
+          'div',
+          m(
+            '.tooltip-text-line',
+            m('.tooltip-bold-text', 'root'),
+            this.renderActionsMenu(rootActions, new Map()),
+          ),
+          renderDiffTable([
+            {
+              label: 'Cumulative',
+              baseline: diff.allRootsBaselineCumulativeValue,
+              current: allRootsCumulativeValue,
+              unit,
+              allTotals,
+            },
+          ]),
+        );
+      }
       const val = displaySize(allRootsCumulativeValue, unit);
       const percent = displayPercentage(
         allRootsCumulativeValue,
@@ -612,6 +677,7 @@
       );
     }
     const {queryIdx} = source;
+    const node = nodes[queryIdx]!;
     const {
       name,
       cumulativeValue,
@@ -619,7 +685,7 @@
       parentCumulativeValue,
       properties,
       marker,
-    } = nodes[queryIdx]!;
+    } = node;
 
     const percent = displayPercentage(
       cumulativeValue,
@@ -642,6 +708,19 @@
       selfPercentText += `, parent: ${parentSelfPercent}`;
     }
     const nameLabel = nameColumnLabel ?? 'Name';
+    // In a diff, properties with a baseline value are rows of the diff table.
+    const inDiffTable = (p: TreeExplorerPropertyDefinition) =>
+      diff !== undefined && p.baselineValue !== undefined;
+    const propertyLines = Array.from(properties, ([_, value]) => {
+      if (value.isVisible && !inDiffTable(value)) {
+        return m(
+          '.tooltip-text-line',
+          m('.tooltip-bold-text', value.displayName + ':'),
+          m('.tooltip-text', value.value),
+        );
+      }
+      return null;
+    });
     const defaultContent = [
       // Show marker at the top of the tooltip
       marker &&
@@ -651,36 +730,62 @@
         m('.tooltip-bold-text', `${nameLabel}:`),
         m('.tooltip-text', name),
       ),
-      m(
-        '.tooltip-text-line',
-        m('.tooltip-bold-text', 'Cumulative:'),
-        m(
-          '.tooltip-text',
-          `${displaySize(cumulativeValue, unit)} (${percentText})`,
-        ),
+      // In a diff, the properties stay with the name, above the diff table.
+      diff !== undefined && propertyLines,
+      diff !== undefined
+        ? renderDiffTable([
+            {
+              label: 'Cumulative',
+              baseline: node.baselineCumulativeValue ?? 0,
+              current: cumulativeValue,
+              unit,
+              allTotals,
+            },
+            {
+              label: 'Self',
+              baseline: node.baselineSelfValue ?? 0,
+              current: selfValue,
+              unit,
+              allTotals,
+            },
+            ...Array.from(properties.values())
+              .filter((p) => p.isVisible && inDiffTable(p))
+              .map((p) => ({
+                label: p.displayName,
+                baseline: Number(p.baselineValue),
+                current: Number(p.value),
+                unit: '',
+              })),
+          ])
+        : [
+            m(
+              '.tooltip-text-line',
+              m('.tooltip-bold-text', 'Cumulative:'),
+              m(
+                '.tooltip-text',
+                `${displaySize(cumulativeValue, unit)} (${percentText})`,
+              ),
+            ),
+            m(
+              '.tooltip-text-line',
+              m('.tooltip-bold-text', 'Self:'),
+              m(
+                '.tooltip-text',
+                `${displaySize(selfValue, unit)} (${selfPercentText})`,
+              ),
+            ),
+          ],
+      diff === undefined && propertyLines,
+      this.renderNodeActionBar(
+        source,
+        name,
+        node,
+        // The host's actions act on the current tree, which nodes only the
+        // baseline has are missing from.
+        diff !== undefined && cumulativeValue === 0 ? [] : nodeActions,
       ),
-      m(
-        '.tooltip-text-line',
-        m('.tooltip-bold-text', 'Self:'),
-        m(
-          '.tooltip-text',
-          `${displaySize(selfValue, unit)} (${selfPercentText})`,
-        ),
-      ),
-      Array.from(properties, ([_, value]) => {
-        if (value.isVisible) {
-          return m(
-            '.tooltip-text-line',
-            m('.tooltip-bold-text', value.displayName + ':'),
-            m('.tooltip-text', value.value),
-          );
-        }
-        return null;
-      }),
-      this.renderNodeActionBar(source, name, nodes[queryIdx]!, nodeActions),
     ];
     const {renderNodeTooltip} = this.attrs;
-    const node = nodes[queryIdx]!;
     return m(
       'div',
       renderNodeTooltip === undefined
@@ -1191,11 +1296,13 @@
 }
 
 function computeRenderNodes(
-  {nodes, allRootsCumulativeValue, minDepth}: TreeExplorerData,
+  data: TreeExplorerData,
   zoomRegion: ZoomRegion,
   canvasWidth: number,
   yOffset: number,
 ): ReadonlyArray<RenderNode> {
+  const {nodes, minDepth} = data;
+  const rootsWidth = layoutWidth(data);
   const renderNodes: RenderNode[] = [];
 
   const mergedKeyToX = new Map<string, number>();
@@ -1207,12 +1314,11 @@
     source: {
       kind: 'ROOT',
       queryXStart: 0,
-      queryXEnd: allRootsCumulativeValue,
+      queryXEnd: rootsWidth,
       type: 'ROOT',
     },
     state:
-      zoomRegion.queryXStart === 0 &&
-      zoomRegion.queryXEnd === allRootsCumulativeValue
+      zoomRegion.queryXStart === 0 && zoomRegion.queryXEnd === rootsWidth
         ? 'NORMAL'
         : 'PARTIAL',
   });
@@ -1231,7 +1337,7 @@
     }
     const queryXPerPx = depthMatchingZoom
       ? zoomQueryWidth / canvasWidth
-      : allRootsCumulativeValue / canvasWidth;
+      : rootsWidth / canvasWidth;
     const relativeXStart = depthMatchingZoom
       ? qXStart - zoomRegion.queryXStart
       : qXStart;
@@ -1399,6 +1505,35 @@
 // Cache for computed color schemes by name
 const colorSchemeCache = new Map<string, ColorScheme>();
 
+// Nodes compared with a baseline are colored by their change (see diffScore),
+// rounded to steps so that the color schemes can be cached.
+const DIFF_COLOR_STEPS = 32;
+const diffColorSchemeCache = new Map<number, ColorScheme>();
+
+function getDiffColorScheme(
+  change: number,
+  diff: TreeExplorerDiff,
+  greyed: boolean,
+): ColorScheme {
+  if (greyed) {
+    return GREYED_COLOR_SCHEME;
+  }
+  const step = Math.round(diffScore(change, diff) * DIFF_COLOR_STEPS);
+  let scheme = diffColorSchemeCache.get(step);
+  if (scheme === undefined) {
+    const base = diffColor(step / DIFF_COLOR_STEPS);
+    scheme = makeColorScheme(base, base.darken(15));
+    diffColorSchemeCache.set(step, scheme);
+  }
+  return scheme;
+}
+
+// The width of the roots in the units of the nodes' xStart and xEnd: in a
+// diff, nodes are laid out by their value in both trees.
+function layoutWidth({allRootsCumulativeValue, diff}: TreeExplorerData) {
+  return allRootsCumulativeValue + (diff?.allRootsBaselineCumulativeValue ?? 0);
+}
+
 function getFlamegraphColorScheme(name: string, greyed: boolean): ColorScheme {
   if (greyed) {
     return GREYED_COLOR_SCHEME;
diff --git a/ui/src/widgets/flamegraph_diff.scss b/ui/src/widgets/flamegraph_diff.scss
new file mode 100644
index 0000000..a524be4
--- /dev/null
+++ b/ui/src/widgets/flamegraph_diff.scss
@@ -0,0 +1,110 @@
+// 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.
+
+.pf-flamegraph-diff-legend {
+  display: flex;
+  align-items: center;
+  align-self: center;
+  gap: 4px;
+  padding-right: 8px;
+  font-size: var(--pf-font-size-s);
+  color: var(--pf-color-text-muted);
+  user-select: none;
+
+  // A canvas one pixel high, stretched into a color scale.
+  &__scale {
+    width: 96px;
+    height: 10px;
+    border-radius: 2px;
+  }
+}
+
+.pf-flamegraph-diff-table {
+  margin: 4px 0 0;
+  border-collapse: collapse;
+  cursor: text;
+
+  th,
+  td {
+    padding: 4px 10px;
+    vertical-align: top;
+    white-space: nowrap;
+
+    &:first-child {
+      padding-left: 0;
+      padding-right: 12px;
+    }
+
+    &:last-child {
+      padding-right: 0;
+    }
+  }
+
+  th {
+    font-weight: 600;
+    text-align: left;
+  }
+
+  thead th,
+  td {
+    text-align: right;
+  }
+
+  thead th {
+    padding-top: 2px;
+    padding-bottom: 5px;
+    color: var(--pf-color-text-muted);
+    border-bottom: 1px solid var(--pf-color-border-secondary);
+  }
+
+  tbody tr:first-child th,
+  tbody tr:first-child td {
+    padding-top: 6px;
+  }
+
+  td {
+    font-variant-numeric: tabular-nums;
+  }
+
+  &__change--grew {
+    color: var(--pf-color-danger);
+  }
+
+  &__change--shrank {
+    color: var(--pf-color-success);
+  }
+
+  &__sub {
+    margin-top: 1px;
+    font-size: var(--pf-font-size-s);
+    font-weight: 400;
+    color: var(--pf-color-text-muted);
+
+    &--grew {
+      color: color-mix(
+        in srgb,
+        var(--pf-color-danger) 65%,
+        var(--pf-color-text-muted)
+      );
+    }
+
+    &--shrank {
+      color: color-mix(
+        in srgb,
+        var(--pf-color-success) 65%,
+        var(--pf-color-text-muted)
+      );
+    }
+  }
+}
diff --git a/ui/src/widgets/flamegraph_diff.ts b/ui/src/widgets/flamegraph_diff.ts
new file mode 100644
index 0000000..51e37be
--- /dev/null
+++ b/ui/src/widgets/flamegraph_diff.ts
@@ -0,0 +1,233 @@
+// 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.
+
+// Colors, legend and tooltip table of a tree compared with a baseline (see
+// TreeExplorerData.diff).
+
+import './flamegraph_diff.scss';
+import m from 'mithril';
+import {classNames} from '../base/classnames';
+import {HSLColor, hexToRgb, rgbToHsl} from '../base/color';
+import {
+  type TreeExplorerDiff,
+  displayChange,
+  displayRelativeChange,
+  displaySize,
+} from './tree_explorer';
+
+// The colors of a change from the largest shrink (-1) through no change (0)
+// to the largest growth (1): green, grey, yellow and red.
+const DIFF_COLOR_STOPS: ReadonlyArray<readonly [number, string]> = [
+  [-1, '#86d68c'],
+  [0, '#dddddd'],
+  [0.25, '#eed95e'],
+  [1, '#d95b54'],
+];
+
+// A change scaled into [-1, 1] by the largest change in its direction.
+export function diffScore(change: number, diff: TreeExplorerDiff): number {
+  if (change > 0) {
+    return diff.maxGrowth > 0 ? Math.min(change / diff.maxGrowth, 1) : 1;
+  }
+  if (change < 0) {
+    return diff.maxShrink > 0 ? -Math.min(-change / diff.maxShrink, 1) : -1;
+  }
+  return 0;
+}
+
+export function diffColor(score: number): HSLColor {
+  let i = 1;
+  while (i < DIFF_COLOR_STOPS.length - 1 && score > DIFF_COLOR_STOPS[i]![0]) {
+    i++;
+  }
+  const [from, fromHex] = DIFF_COLOR_STOPS[i - 1]!;
+  const [to, toHex] = DIFF_COLOR_STOPS[i]!;
+  const t = (score - from) / (to - from);
+  const a = hexToRgb(fromHex);
+  const b = hexToRgb(toHex);
+  const mix = (k: 0 | 1 | 2) => Math.round(a[k] + (b[k] - a[k]) * t);
+  return new HSLColor(rgbToHsl([mix(0), mix(1), mix(2)]));
+}
+
+// Formats a value of a diff, e.g. "23.23 MiB → 26.39 MiB (+3.16 MiB, +13.60%)".
+export function displayDiff(
+  baseline: number,
+  current: number,
+  unit: string,
+): string {
+  const change = displayChange(current - baseline, unit);
+  const relative = displayRelativeChange(baseline, current);
+  return (
+    `${displaySize(baseline, unit)} → ${displaySize(current, unit)} ` +
+    `(${change}, ${relative})`
+  );
+}
+
+// The colors of the changes, from the largest shrink to the largest growth.
+export function renderDiffLegend(
+  diff: TreeExplorerDiff,
+  unit: string,
+): m.Children {
+  const paint = ({dom}: m.VnodeDOM) =>
+    paintLegend(dom as HTMLCanvasElement, diff);
+  return m(
+    '.pf-flamegraph-diff-legend',
+    displayChange(-diff.maxShrink, unit),
+    m('canvas.pf-flamegraph-diff-legend__scale', {
+      width: LEGEND_STEPS,
+      height: 1,
+      oncreate: paint,
+      onupdate: paint,
+    }),
+    displayChange(diff.maxGrowth, unit),
+  );
+}
+
+const LEGEND_STEPS = 64;
+
+function paintLegend(canvas: HTMLCanvasElement, diff: TreeExplorerDiff) {
+  const ctx = canvas.getContext('2d');
+  if (ctx === null) return;
+  const range = diff.maxShrink + diff.maxGrowth;
+  for (let i = 0; i < LEGEND_STEPS; i++) {
+    const change = -diff.maxShrink + ((i + 0.5) / LEGEND_STEPS) * range;
+    ctx.fillStyle = diffColor(diffScore(change, diff)).cssString;
+    ctx.fillRect(i, 0, 1, 1);
+  }
+}
+
+export interface DiffTableRow {
+  readonly label: string;
+  readonly baseline: number;
+  readonly current: number;
+  readonly unit: string;
+  // Visible totals of all values on each side; when set, adds an "all:"
+  // sub-line showing each side's share and their difference in percentage points.
+  readonly allTotals?: {
+    readonly baseline: number;
+    readonly current: number;
+  };
+}
+
+// Formats a difference of percentages in percentage points, e.g. "+11.3 pp".
+export function displayPercentPointDelta(delta: number, decimals = 1): string {
+  // Avoid "-0.0 pp" for tiny negative deltas that round to zero.
+  const rounded = Number(delta.toFixed(decimals));
+  if (rounded === 0) return `${(0).toFixed(decimals)} pp`;
+  return `${rounded > 0 ? '+' : ''}${rounded.toFixed(decimals)} pp`;
+}
+
+// Sign of a value after rounding to `decimals`, so a value displayed as zero
+// is not colored as growing or shrinking.
+export function roundedSign(value: number, decimals = 1): -1 | 0 | 1 {
+  const rounded = Number(value.toFixed(decimals));
+  if (rounded > 0) return 1;
+  if (rounded < 0) return -1;
+  return 0;
+}
+
+// The values of a node (or of the root) in the current and baseline trees,
+// and how they changed.
+export function renderDiffTable(rows: ReadonlyArray<DiffTableRow>): m.Children {
+  return m(
+    'table.pf-flamegraph-diff-table',
+    m(
+      'thead',
+      m(
+        'tr',
+        m('th'),
+        m('th', 'Current'),
+        m('th', 'Baseline'),
+        m('th', 'Current − Baseline'),
+      ),
+    ),
+    m(
+      'tbody',
+      rows.map(({label, baseline, current, unit, allTotals}) => {
+        const delta = current - baseline;
+        const changeClass = classNames(
+          delta > 0 && 'pf-flamegraph-diff-table__change--grew',
+          delta < 0 && 'pf-flamegraph-diff-table__change--shrank',
+        );
+        const styled = (text: string) =>
+          changeClass ? m('span', {className: changeClass}, text) : text;
+        const currentShare =
+          allTotals === undefined
+            ? undefined
+            : allTotals.current === 0
+              ? 0
+              : (current / allTotals.current) * 100;
+        const baselineShare =
+          allTotals === undefined
+            ? undefined
+            : allTotals.baseline === 0
+              ? 0
+              : (baseline / allTotals.baseline) * 100;
+        const ppDelta =
+          currentShare !== undefined && baselineShare !== undefined
+            ? currentShare - baselineShare
+            : undefined;
+        const ppSign = ppDelta === undefined ? 0 : roundedSign(ppDelta, 2);
+        return m(
+          'tr',
+          m(
+            'th',
+            m('div', label),
+            allTotals !== undefined &&
+              m('.pf-flamegraph-diff-table__sub', '% of all'),
+          ),
+          m(
+            'td',
+            m('div', displaySize(current, unit)),
+            currentShare !== undefined &&
+              m(
+                '.pf-flamegraph-diff-table__sub',
+                `${currentShare.toFixed(2)}%`,
+              ),
+          ),
+          m(
+            'td',
+            m('div', displaySize(baseline, unit)),
+            baselineShare !== undefined &&
+              m(
+                '.pf-flamegraph-diff-table__sub',
+                `${baselineShare.toFixed(2)}%`,
+              ),
+          ),
+          m(
+            'td',
+            m(
+              'div',
+              styled(displayChange(delta, unit)),
+              ' (',
+              styled(displayRelativeChange(baseline, current)),
+              ')',
+            ),
+            ppDelta !== undefined &&
+              m(
+                '.pf-flamegraph-diff-table__sub',
+                {
+                  className: classNames(
+                    ppSign > 0 && 'pf-flamegraph-diff-table__sub--grew',
+                    ppSign < 0 && 'pf-flamegraph-diff-table__sub--shrank',
+                  ),
+                },
+                displayPercentPointDelta(ppDelta, 2),
+              ),
+          ),
+        );
+      }),
+    ),
+  );
+}
diff --git a/ui/src/widgets/tree_explorer.ts b/ui/src/widgets/tree_explorer.ts
index 9713830..94583d8 100644
--- a/ui/src/widgets/tree_explorer.ts
+++ b/ui/src/widgets/tree_explorer.ts
@@ -71,6 +71,9 @@
 export type TreeExplorerPropertyDefinition = {
   displayName: string;
   value: string;
+  // The value in the baseline the tree is compared with, for properties that
+  // have one (see AggTreeExplorerQueryColumn.baselineName).
+  baselineValue?: string;
   isVisible: boolean;
   isAggregatable: boolean;
 };
@@ -90,12 +93,32 @@
   readonly propertyValues: ReadonlyMap<string, string>;
   readonly xStart: number;
   readonly xEnd: number;
+  // The node's cumulative and self values in the baseline the tree is compared
+  // with, if any.
+  readonly baselineCumulativeValue?: number;
+  readonly baselineSelfValue?: number;
+}
+
+// How a tree compared with a baseline changed (see
+// TreeExplorerQueryMetric.baselineColumn).
+export interface TreeExplorerDiff {
+  // allRootsCumulativeValue in the baseline.
+  readonly allRootsBaselineCumulativeValue: number;
+  // unfilteredCumulativeValue in the baseline.
+  readonly unfilteredBaselineCumulativeValue: number;
+  // The largest growth and the largest shrink of a node's cumulative value,
+  // both positive. Each scales the colors of the changes in its direction.
+  readonly maxGrowth: number;
+  readonly maxShrink: number;
 }
 
 export interface TreeExplorerData {
   readonly nodes: ReadonlyArray<TreeExplorerNode>;
   readonly unfilteredCumulativeValue: number;
   readonly allRootsCumulativeValue: number;
+  // Set when the tree is compared with a baseline. Nodes are then laid out by
+  // their value in both trees, so that nodes only the baseline has are drawn.
+  readonly diff?: TreeExplorerDiff;
   readonly minDepth: number;
   readonly maxDepth: number;
   readonly nodeActions: ReadonlyArray<TreeExplorerOptionalAction>;
@@ -457,6 +480,32 @@
   return `${((size / totalSize) * 100.0).toFixed(2)}%`;
 }
 
+// Formats a signed change in the metric's unit, e.g. "+1.20 MiB".
+export function displayChange(change: number, unit: string): string {
+  if (change === 0) return displaySize(0, unit);
+  return `${change < 0 ? '-' : '+'}${displaySize(Math.abs(change), unit)}`;
+}
+
+// The change from `baseline` to `current` in percent of `baseline`, or
+// undefined for a new value, which has no baseline to divide by.
+export function relativeChange(
+  baseline: number,
+  current: number,
+): number | undefined {
+  if (baseline === 0) return current === 0 ? 0 : undefined;
+  return ((current - baseline) / baseline) * 100;
+}
+
+// Formats relativeChange, e.g. "+13.60%", or "new".
+export function displayRelativeChange(
+  baseline: number,
+  current: number,
+): string {
+  const change = relativeChange(baseline, current);
+  if (change === undefined) return 'new';
+  return `${change > 0 ? '+' : ''}${change.toFixed(2)}%`;
+}
+
 export function getUnitDisplayName(unit: string | undefined): string {
   if (unit === undefined || unit === '' || unit === 'count') {
     return 'count';