ui: show diffs in TreeExplorer tables and exports

Update Call Tree and Functions to show Current, Baseline and colored
delta columns sorted by delta when comparing with a baseline, scale
colors and the diff legend to each tab's displayed deltas, and include
baseline, delta and delta % columns in flamegraph, Call Tree and
Functions exports.
diff --git a/ui/src/components/tree_explorer_panel.scss b/ui/src/components/tree_explorer_panel.scss
index 1798ec7..7c6bbee 100644
--- a/ui/src/components/tree_explorer_panel.scss
+++ b/ui/src/components/tree_explorer_panel.scss
@@ -48,6 +48,46 @@
   gap: 4px;
 }
 
+// A Change cell of a diff, colored like its flamegraph node.
+.pf-tree-explorer__change {
+  padding: 0 4px;
+  border-radius: 2px;
+}
+
+.pf-tree-explorer__delta--grew {
+  color: color-mix(
+    in srgb,
+    var(--pf-color-danger) 65%,
+    var(--pf-color-text-muted)
+  );
+}
+
+.pf-tree-explorer__delta--shrank {
+  color: color-mix(
+    in srgb,
+    var(--pf-color-success) 65%,
+    var(--pf-color-text-muted)
+  );
+}
+
+.pf-tree-explorer__info {
+  display: inline-flex;
+  align-items: center;
+  gap: 4px;
+}
+
+.pf-tree-explorer__info-icon {
+  font-size: 14px;
+  color: var(--pf-color-text-muted);
+  cursor: help;
+  opacity: 0.7;
+
+  &:hover {
+    opacity: 1;
+    color: var(--pf-color-text);
+  }
+}
+
 .pf-tree-explorer__node-icon {
   font-size: 16px;
   cursor: help;
diff --git a/ui/src/components/tree_explorer_panel.ts b/ui/src/components/tree_explorer_panel.ts
index 2c11dd1..9f79e82 100644
--- a/ui/src/components/tree_explorer_panel.ts
+++ b/ui/src/components/tree_explorer_panel.ts
@@ -26,6 +26,8 @@
   createDefaultTreeExplorerState,
   metricId,
   type TreeExplorerAddableMetric,
+  type TreeExplorerData,
+  type TreeExplorerDiff,
   type TreeExplorerDisplayMode,
   type TreeExplorerNodeIconFn,
   type TreeExplorerNodeTooltipRenderer,
@@ -37,6 +39,8 @@
   TreeExplorerFlatView,
   TreeExplorerTreeView,
   buildFlatExportString,
+  computeFlatDiff,
+  computeFlatFunctions,
 } from './tree_explorer_table_views';
 import {Tabs} from '../widgets/tabs';
 
@@ -87,6 +91,9 @@
 // panel.
 export class TreeExplorerPanel implements m.ClassComponent<TreeExplorerPanelAttrs> {
   private highlightPattern = '';
+  private cachedDiffData?: TreeExplorerData;
+  private cachedDiffMode?: TreeExplorerDisplayMode;
+  private cachedLegendDiff?: TreeExplorerDiff;
 
   view({attrs}: m.CVnode<TreeExplorerPanelAttrs>): m.Children {
     const {fetcher, state = createDefaultTreeExplorerState(fetcher.metrics)} =
@@ -142,11 +149,11 @@
                       );
                 },
           exportFileBaseName:
-            displayMode === 'flat'
+            (displayMode === 'flat'
               ? 'functions'
               : displayMode === 'tree'
                 ? 'call_tree'
-                : 'flamegraph',
+                : 'flamegraph') + (data?.diff !== undefined ? '_diff' : ''),
           extraDownloadItems: attrs.extraDownloadItems,
         }),
         children,
@@ -168,6 +175,18 @@
         ),
       );
 
+    if (this.cachedDiffData !== data || this.cachedDiffMode !== displayMode) {
+      this.cachedDiffData = data;
+      this.cachedDiffMode = displayMode;
+      this.cachedLegendDiff =
+        data?.diff === undefined
+          ? undefined
+          : displayMode === 'flat'
+            ? computeFlatDiff(data.diff, computeFlatFunctions(data))
+            : data.diff;
+    }
+    const legendDiff = this.cachedLegendDiff;
+
     return m(
       '.pf-tree-explorer',
       m(Tabs, {
@@ -180,9 +199,7 @@
           });
         },
         rightContent:
-          displayMode === 'flamegraph' &&
-          data?.diff !== undefined &&
-          renderDiffLegend(data.diff, unit),
+          legendDiff !== undefined && renderDiffLegend(legendDiff, unit),
         tabs: [
           {
             key: 'flamegraph',
diff --git a/ui/src/components/tree_explorer_table_views.ts b/ui/src/components/tree_explorer_table_views.ts
index ca99a81..bb40445 100644
--- a/ui/src/components/tree_explorer_table_views.ts
+++ b/ui/src/components/tree_explorer_table_views.ts
@@ -25,9 +25,13 @@
 } from '../base/export_formatters';
 import type {ExportFormat} from '../widgets/export_button';
 import {
+  displayChange,
   displaySize,
+  exportRelativeChange,
   getUnitDisplayName,
+  relativeChange,
   type TreeExplorerData,
+  type TreeExplorerDiff,
   type TreeExplorerMetric,
   type TreeExplorerNode,
   type TreeExplorerNodeIconFn,
@@ -41,6 +45,11 @@
 } from './widgets/datagrid/data_source';
 import type {IdBasedTree} from './widgets/datagrid/model';
 import type {Row, SqlValue} from '../trace_processor/query_result';
+import {diffColors} from '../widgets/flamegraph';
+import {
+  displayPercentPointDelta,
+  roundedSign,
+} from '../widgets/flamegraph_diff';
 import {Icon} from '../widgets/icon';
 import {Tooltip} from '../widgets/tooltip';
 
@@ -51,6 +60,22 @@
   expandedIds: new Set<bigint>(),
 };
 
+// Largest growth and shrink of Self Δ across the merged Functions rows,
+// matching Functions' pill-colored Self Δ column and legend.
+export function computeFlatDiff(
+  diff: TreeExplorerDiff,
+  functions: ReadonlyArray<TreeExplorerFlatFunction>,
+): TreeExplorerDiff {
+  let maxGrowth = 0;
+  let maxShrink = 0;
+  for (const fn of functions) {
+    const selfDelta = fn.self - (fn.baselineSelf ?? 0);
+    maxGrowth = Math.max(maxGrowth, selfDelta);
+    maxShrink = Math.max(maxShrink, -selfDelta);
+  }
+  return {...diff, maxGrowth, maxShrink};
+}
+
 export interface TreeExplorerTreeViewAttrs {
   readonly data: TreeExplorerData;
   readonly unit: string;
@@ -78,7 +103,11 @@
     }
     const fmtValue = (value: SqlValue) =>
       typeof value === 'number' ? displaySize(value, attrs.unit) : '';
-    return m(DataGrid, {
+    const diff = attrs.data.diff;
+    // Keyed so that the grid is re-created, with or without the diff columns,
+    // when comparing starts or stops.
+    const grid = m(DataGrid, {
+      key: String(diff !== undefined),
       className: 'pf-tree-explorer__grid',
       fillHeight: true,
       // The tree explorer's own filter bar is the filtering surface;
@@ -101,36 +130,149 @@
           },
         },
         total: {
-          title: 'Total',
+          title: diff === undefined ? 'Total' : 'Current total',
           columnType: 'quantitative',
           cellRenderer: fmtValue,
         },
         self: {
-          title: 'Self',
+          title: diff === undefined ? 'Self' : 'Current self',
           columnType: 'quantitative',
           cellRenderer: fmtValue,
         },
-        percent: {
-          title: '% of total',
-          columnType: 'quantitative',
-          cellRenderer: fmtPercent,
-        },
+        percent:
+          diff === undefined
+            ? percentColumn('% of total')
+            : percentColumn(
+                'Current total (% of all)',
+                'Current total / all visible current values',
+              ),
+        ...(diff !== undefined && {
+          baselinePercent: percentColumn(
+            'Baseline total (% of all)',
+            'Baseline total / all visible baseline values',
+          ),
+          percentDelta: percentColumn(
+            'Total Δ (% of all)',
+            'Current total (% of all) − Baseline total (% of all), in percentage points',
+            fmtPercentPointDelta,
+          ),
+          ...diffSchema(diff, attrs.unit, 'totalDelta'),
+        }),
       },
       data: this.source,
-      initialColumns: [
-        {id: 'name', field: 'name'},
-        {id: 'total', field: 'total', sort: 'DESC'},
-        {id: 'self', field: 'self'},
-        {id: 'percent', field: 'percent'},
-      ],
+      initialColumns:
+        diff === undefined
+          ? [
+              {id: 'name', field: 'name'},
+              {id: 'total', field: 'total', sort: 'DESC'},
+              {id: 'self', field: 'self'},
+              {id: 'percent', field: 'percent'},
+            ]
+          : [
+              {id: 'name', field: 'name'},
+              {id: 'total', field: 'total'},
+              {id: 'baselineTotal', field: 'baselineTotal'},
+              {id: 'totalDelta', field: 'totalDelta', sort: 'DESC'},
+              {id: 'totalDeltaPercent', field: 'totalDeltaPercent'},
+              {id: 'selfDelta', field: 'selfDelta'},
+            ],
       tree: this.tree ?? DEFAULT_TREE,
       onTreeChanged: (tree) => {
         this.tree = tree;
       },
     });
+    return [grid];
   }
 }
 
+// The columns of a diff. `pillColumn` gets flamegraph-colored pills matching
+// the tab's legend; the other delta column gets green/red signed text.
+function diffSchema(
+  diff: TreeExplorerDiff,
+  unit: string,
+  pillColumn: 'totalDelta' | 'selfDelta',
+) {
+  const size = (title: string) => ({
+    title,
+    columnType: 'quantitative' as const,
+    cellRenderer: (value: SqlValue) =>
+      typeof value === 'number' ? displaySize(value, unit) : '',
+  });
+  const change = (title: string, pill: boolean) => ({
+    title: renderInfoHeader(title, 'Current − Baseline'),
+    titleString: title,
+    columnType: 'quantitative' as const,
+    cellRenderer: (value: SqlValue) =>
+      pill ? renderChange(value, diff, unit) : renderSignedChange(value, unit),
+  });
+  const relativeDelta = (title: string, info: string) => ({
+    title: renderInfoHeader(title, info),
+    titleString: title,
+    columnType: 'quantitative' as const,
+    cellRenderer: fmtRelativeDelta,
+    cellFormatter: formatRelativeDeltaText,
+  });
+  return {
+    baselineTotal: size('Baseline total'),
+    totalDelta: change('Total Δ', pillColumn === 'totalDelta'),
+    totalDeltaPercent: relativeDelta(
+      'Total Δ %',
+      '(Current total − Baseline total) / Baseline total',
+    ),
+    baselineSelf: size('Baseline self'),
+    selfDelta: change('Self Δ', pillColumn === 'selfDelta'),
+    selfDeltaPercent: relativeDelta(
+      'Self Δ %',
+      '(Current self − Baseline self) / Baseline self',
+    ),
+  };
+}
+
+function renderSignedChange(value: SqlValue, unit: string): m.Children {
+  if (typeof value !== 'number') {
+    return '';
+  }
+  const sign: -1 | 0 | 1 = value > 0 ? 1 : value < 0 ? -1 : 0;
+  return renderSignedText(displayChange(value, unit), sign);
+}
+
+function renderChange(
+  value: SqlValue,
+  diff: TreeExplorerDiff,
+  unit: string,
+): m.Children {
+  if (typeof value !== 'number') {
+    return '';
+  }
+  const text = displayChange(value, unit);
+  const colors = diffColors(value, diff);
+  if (colors === undefined) {
+    return text;
+  }
+  return m(
+    'span.pf-tree-explorer__change',
+    {style: {backgroundColor: colors.background, color: colors.text}},
+    text,
+  );
+}
+
+// The diff columns of a row for a node's (or function's) values.
+function diffCells(
+  total: number,
+  self: number,
+  baselineTotal: number,
+  baselineSelf: number,
+): Row {
+  return {
+    baselineTotal,
+    totalDelta: total - baselineTotal,
+    totalDeltaPercent: relativeChange(baselineTotal, total) ?? Infinity,
+    baselineSelf,
+    selfDelta: self - baselineSelf,
+    selfDeltaPercent: relativeChange(baselineSelf, self) ?? Infinity,
+  };
+}
+
 // Tree-mode DataGrid source over resident tree explorer nodes. Children are
 // indexed once; useRows() walks only the expanded rows, sorting siblings by
 // the requested column (total descending by default).
@@ -138,10 +280,14 @@
   private readonly children = new Map<number, TreeExplorerNode[]>();
   private readonly roots: TreeExplorerNode[] = [];
   private readonly total: number;
+  private readonly baselineTotal: number;
+  private readonly isDiff: boolean;
 
   constructor(data: TreeExplorerData) {
     super([]);
     this.total = data.allRootsCumulativeValue;
+    this.baselineTotal = data.diff?.allRootsBaselineCumulativeValue ?? 0;
+    this.isDiff = data.diff !== undefined;
     const ids = new Set(data.nodes.map((n) => n.id));
     for (const n of data.nodes) {
       if (ids.has(n.parentId)) {
@@ -178,24 +324,28 @@
       collapsedIds !== undefined
         ? !collapsedIds.has(BigInt(id))
         : (expandedIds?.has(BigInt(id)) ?? false);
-    const cmp = this.comparator(model.sort);
+    // The grid reads cells by column alias, which is not the field for the
+    // columns the user adds.
+    const aliased = model.columns.filter((c) => c.alias !== c.field);
+    const sortField = model.columns.find(
+      (c) => c.alias === model.sort?.alias,
+    )?.field;
+    const cmp = rowComparator(
+      sortField,
+      model.sort?.direction,
+      this.isDiff ? 'totalDelta' : 'total',
+    );
     const rows: Row[] = [];
     const visit = (nodes: TreeExplorerNode[], depth: number) => {
-      for (const n of [...nodes].sort(cmp)) {
-        const children = this.children.get(n.id);
-        rows.push({
-          id: n.id,
-          parentId: n.parentId,
-          name: n.name,
-          total: n.cumulativeValue,
-          self: n.selfValue,
-          percent:
-            this.total === 0 ? 0 : (n.cumulativeValue / this.total) * 100,
-          __id: n.id,
-          __depth: depth,
-          __has_children: children === undefined ? 0 : 1,
-        });
-        if (children !== undefined && isExpanded(n.id)) {
+      const siblings = nodes.map((n) => ({node: n, row: this.row(n, depth)}));
+      siblings.sort((a, b) => cmp(a.row, b.row));
+      for (const {node, row} of siblings) {
+        for (const {field, alias} of aliased) {
+          row[alias] = row[field] ?? null;
+        }
+        rows.push(row);
+        const children = this.children.get(node.id);
+        if (children !== undefined && isExpanded(node.id)) {
           visit(children, depth + 1);
         }
       }
@@ -204,25 +354,61 @@
     return rows;
   }
 
-  private comparator(
-    sort: {alias: string; direction: 'ASC' | 'DESC'} | undefined,
-  ): (a: TreeExplorerNode, b: TreeExplorerNode) => number {
-    const dir = sort?.direction === 'ASC' ? 1 : -1;
-    switch (sort?.alias) {
-      case 'name':
-        return (a, b) => dir * a.name.localeCompare(b.name);
-      case 'self':
-        return (a, b) => dir * (a.selfValue - b.selfValue);
-      default: // 'total', 'percent' and the initial (unsorted) state.
-        return (a, b) => dir * (a.cumulativeValue - b.cumulativeValue);
-    }
+  private row(n: TreeExplorerNode, depth: number): Row {
+    const percent = pctOfAll(n.cumulativeValue, this.total);
+    const baselineCumulative = n.baselineCumulativeValue ?? 0;
+    const baselinePercent = pctOfAll(baselineCumulative, this.baselineTotal);
+    return {
+      id: n.id,
+      parentId: n.parentId,
+      name: n.name,
+      total: n.cumulativeValue,
+      self: n.selfValue,
+      percent,
+      ...(this.isDiff && {
+        ...diffCells(
+          n.cumulativeValue,
+          n.selfValue,
+          baselineCumulative,
+          n.baselineSelfValue ?? 0,
+        ),
+        baselinePercent,
+        percentDelta: percent - baselinePercent,
+      }),
+      __id: n.id,
+      __depth: depth,
+      __has_children: this.children.has(n.id) ? 1 : 0,
+    };
   }
 }
 
+// Sorts rows by the values in `field` (`defaultField` when the grid is not
+// sorted), or alphabetically by name.
+function rowComparator(
+  field: string | undefined,
+  direction: 'ASC' | 'DESC' | undefined,
+  defaultField: string,
+): (a: Row, b: Row) => number {
+  const dir = direction === 'ASC' ? 1 : -1;
+  if (field === 'name') {
+    return (a, b) => dir * String(a.name).localeCompare(String(b.name));
+  }
+  const key = field ?? defaultField;
+  return (a, b) => {
+    const av = Number(a[key]);
+    const bv = Number(b[key]);
+    if (av === bv) return 0;
+    return dir * (av - bv);
+  };
+}
+
 export interface TreeExplorerFlatFunction {
   readonly name: string;
   readonly self: number;
   readonly total: number;
+  // `self` and `total` in the baseline, when the tree is compared with one.
+  readonly baselineSelf?: number;
+  readonly baselineTotal?: number;
 }
 
 // Aggregates the tree per function name, pprof-style: `self` sums a
@@ -251,7 +437,10 @@
     }
   }
 
-  const functions = new Map<string, {self: number; total: number}>();
+  const functions = new Map<
+    string,
+    {self: number; total: number; baselineSelf: number; baselineTotal: number}
+  >();
   // Number of times each name occurs on the current root-to-node path.
   // Explicit stack with exit markers: call stacks can be deep.
   const onPath = new Map<string, number>();
@@ -268,13 +457,15 @@
       }
       let fn = functions.get(name);
       if (fn === undefined) {
-        fn = {self: 0, total: 0};
+        fn = {self: 0, total: 0, baselineSelf: 0, baselineTotal: 0};
         functions.set(name, fn);
       }
       fn.self += node.selfValue;
+      fn.baselineSelf += node.baselineSelfValue ?? 0;
       const occurrences = onPath.get(name) ?? 0;
       if (occurrences === 0) {
         fn.total += node.cumulativeValue;
+        fn.baselineTotal += node.baselineCumulativeValue ?? 0;
       }
       onPath.set(name, occurrences + 1);
       stack.push({node, exit: true});
@@ -283,7 +474,16 @@
       }
     }
   }
-  return [...functions].map(([name, {self, total}]) => ({name, self, total}));
+  const compared = data.diff !== undefined;
+  return [...functions].map(
+    ([name, {self, total, baselineSelf, baselineTotal}]) => ({
+      name,
+      self,
+      total,
+      baselineSelf: compared ? baselineSelf : undefined,
+      baselineTotal: compared ? baselineTotal : undefined,
+    }),
+  );
 }
 
 export interface TreeExplorerFlatViewAttrs {
@@ -297,18 +497,27 @@
 // Flat per-function table (pprof "Top"): Name, Self, Self %, Total, Total %.
 export class TreeExplorerFlatView implements m.ClassComponent<TreeExplorerFlatViewAttrs> {
   private rows?: readonly Row[];
+  private flatDiff?: TreeExplorerDiff;
   private rowsData?: TreeExplorerData;
   private nodesByName = new Map<string, TreeExplorerNode[]>();
 
   view({attrs}: m.CVnode<TreeExplorerFlatViewAttrs>): m.Children {
     if (this.rows === undefined || this.rowsData !== attrs.data) {
       this.rowsData = attrs.data;
-      this.rows = flatFunctionRows(attrs.data);
+      const functions = computeFlatFunctions(attrs.data);
+      this.rows = flatFunctionRows(attrs.data, functions);
+      this.flatDiff =
+        attrs.data.diff === undefined
+          ? undefined
+          : computeFlatDiff(attrs.data.diff, functions);
       this.nodesByName = nodesByName(attrs.data);
     }
     const fmtValue = (value: SqlValue) =>
       typeof value === 'number' ? displaySize(value, attrs.unit) : '';
-    return m(DataGrid, {
+    const diff = this.flatDiff;
+    // Keyed as in TreeExplorerTreeView.
+    const grid = m(DataGrid, {
+      key: String(diff !== undefined),
       className: 'pf-tree-explorer__grid',
       fillHeight: true,
       disableFilterControls: true,
@@ -335,35 +544,73 @@
           },
         },
         self: {
-          title: 'Self',
+          title: diff === undefined ? 'Self' : 'Current self',
           columnType: 'quantitative',
           cellRenderer: fmtValue,
         },
-        selfPercent: {
-          title: 'Self %',
-          columnType: 'quantitative',
-          cellRenderer: fmtPercent,
-        },
+        selfPercent:
+          diff === undefined
+            ? percentColumn('Self %')
+            : percentColumn(
+                'Current self (% of all)',
+                'Current self / all visible current values',
+              ),
+        ...(diff !== undefined && {
+          baselineSelfPercent: percentColumn(
+            'Baseline self (% of all)',
+            'Baseline self / all visible baseline values',
+          ),
+          selfPercentDelta: percentColumn(
+            'Self Δ (% of all)',
+            'Current self (% of all) − Baseline self (% of all), in percentage points',
+            fmtPercentPointDelta,
+          ),
+        }),
         total: {
-          title: 'Total',
+          title: diff === undefined ? 'Total' : 'Current total',
           columnType: 'quantitative',
           cellRenderer: fmtValue,
         },
-        totalPercent: {
-          title: 'Total %',
-          columnType: 'quantitative',
-          cellRenderer: fmtPercent,
-        },
+        totalPercent:
+          diff === undefined
+            ? percentColumn('Total %')
+            : percentColumn(
+                'Current total (% of all)',
+                'Current total / all visible current values',
+              ),
+        ...(diff !== undefined && {
+          baselineTotalPercent: percentColumn(
+            'Baseline total (% of all)',
+            'Baseline total / all visible baseline values',
+          ),
+          totalPercentDelta: percentColumn(
+            'Total Δ (% of all)',
+            'Current total (% of all) − Baseline total (% of all), in percentage points',
+            fmtPercentPointDelta,
+          ),
+          ...diffSchema(diff, attrs.unit, 'selfDelta'),
+        }),
       },
       data: this.rows,
-      initialColumns: [
-        {id: 'name', field: 'name'},
-        {id: 'self', field: 'self', sort: 'DESC'},
-        {id: 'selfPercent', field: 'selfPercent'},
-        {id: 'total', field: 'total'},
-        {id: 'totalPercent', field: 'totalPercent'},
-      ],
+      initialColumns:
+        diff === undefined
+          ? [
+              {id: 'name', field: 'name'},
+              {id: 'self', field: 'self', sort: 'DESC'},
+              {id: 'selfPercent', field: 'selfPercent'},
+              {id: 'total', field: 'total'},
+              {id: 'totalPercent', field: 'totalPercent'},
+            ]
+          : [
+              {id: 'name', field: 'name'},
+              {id: 'self', field: 'self'},
+              {id: 'baselineSelf', field: 'baselineSelf'},
+              {id: 'selfDelta', field: 'selfDelta', sort: 'DESC'},
+              {id: 'selfDeltaPercent', field: 'selfDeltaPercent'},
+              {id: 'totalDelta', field: 'totalDelta'},
+            ],
     });
+    return [grid];
   }
 }
 
@@ -407,22 +654,115 @@
   return result;
 }
 
-function flatFunctionRows(data: TreeExplorerData): readonly Row[] {
+function flatFunctionRows(
+  data: TreeExplorerData,
+  functions: ReadonlyArray<TreeExplorerFlatFunction>,
+): readonly Row[] {
   const total = data.allRootsCumulativeValue;
-  const pct = (value: number) => (total === 0 ? 0 : (value / total) * 100);
-  return computeFlatFunctions(data).map((fn) => ({
-    name: fn.name,
-    self: fn.self,
-    selfPercent: pct(fn.self),
-    total: fn.total,
-    totalPercent: pct(fn.total),
-  }));
+  const baselineTotal = data.diff?.allRootsBaselineCumulativeValue ?? 0;
+  return functions.map((fn) => {
+    const selfPercent = pctOfAll(fn.self, total);
+    const totalPercent = pctOfAll(fn.total, total);
+    if (fn.baselineTotal === undefined || fn.baselineSelf === undefined) {
+      return {
+        name: fn.name,
+        self: fn.self,
+        selfPercent,
+        total: fn.total,
+        totalPercent,
+      };
+    }
+    const baselineSelfPercent = pctOfAll(fn.baselineSelf, baselineTotal);
+    const baselineTotalPercent = pctOfAll(fn.baselineTotal, baselineTotal);
+    return {
+      name: fn.name,
+      self: fn.self,
+      selfPercent,
+      total: fn.total,
+      totalPercent,
+      ...diffCells(fn.total, fn.self, fn.baselineTotal, fn.baselineSelf),
+      baselineSelfPercent,
+      selfPercentDelta: selfPercent - baselineSelfPercent,
+      baselineTotalPercent,
+      totalPercentDelta: totalPercent - baselineTotalPercent,
+    };
+  });
+}
+
+function pctOfAll(value: number, root: number): number {
+  return root === 0 ? 0 : (value / root) * 100;
+}
+
+function percentColumn(
+  title: string,
+  info?: string,
+  cellRenderer: (value: SqlValue) => m.Children = fmtPercent,
+) {
+  return {
+    title: info === undefined ? title : renderInfoHeader(title, info),
+    titleString: title,
+    columnType: 'quantitative' as const,
+    cellRenderer,
+  };
+}
+
+function renderInfoHeader(label: string, info: string): m.Children {
+  return m(
+    'span.pf-tree-explorer__info',
+    label,
+    m(
+      Tooltip,
+      {
+        trigger: m(Icon, {
+          className: 'pf-tree-explorer__info-icon',
+          icon: 'help_outline',
+        }),
+      },
+      info,
+    ),
+  );
 }
 
 function fmtPercent(value: SqlValue): string {
   return typeof value === 'number' ? `${value.toFixed(1)}%` : '';
 }
 
+function renderSignedText(text: string, sign: -1 | 0 | 1): m.Children {
+  if (sign === 0) return text;
+  return m(
+    'span',
+    {
+      className:
+        sign > 0
+          ? 'pf-tree-explorer__delta--grew'
+          : 'pf-tree-explorer__delta--shrank',
+    },
+    text,
+  );
+}
+
+function fmtPercentPointDelta(value: SqlValue): m.Children {
+  if (typeof value !== 'number') return '';
+  return renderSignedText(
+    displayPercentPointDelta(value, 1),
+    roundedSign(value, 1),
+  );
+}
+
+function formatRelativeDeltaText(value: SqlValue): string {
+  if (typeof value !== 'number') return '';
+  if (!Number.isFinite(value)) return 'new';
+  const rounded = Number(value.toFixed(2));
+  if (rounded === 0) return '0.00%';
+  return `${rounded > 0 ? '+' : ''}${rounded.toFixed(2)}%`;
+}
+
+function fmtRelativeDelta(value: SqlValue): m.Children {
+  if (typeof value !== 'number') return '';
+  const sign = !Number.isFinite(value) ? 1 : roundedSign(value, 2);
+  return renderSignedText(formatRelativeDeltaText(value), sign);
+}
+
 // Export of the flat function table. Values are raw numbers in the metric's
 // unit so they can be aggregated in spreadsheets.
 export function buildFlatExportString(
@@ -430,26 +770,60 @@
   metric: TreeExplorerMetric,
   format: ExportFormat,
 ): string {
+  const {diff} = data;
   const unitDisplay = getUnitDisplayName(metric.unit);
-  const columns = ['name', 'self', 'selfPercent', 'total', 'totalPercent'];
+  const columns =
+    diff === undefined
+      ? ['name', 'self', 'selfPercent', 'total', 'totalPercent']
+      : [
+          'name',
+          'self',
+          'baselineSelf',
+          'selfDelta',
+          'selfDeltaPercent',
+          'total',
+          'baselineTotal',
+          'totalDelta',
+          'totalDeltaPercent',
+        ];
+  const metricUnit = `${metric.name} (${unitDisplay})`;
   const columnNames: Record<string, string> = {
     name: metric.nameColumnLabel ?? 'Name',
-    self: `Self ${metric.name} (${unitDisplay})`,
+    self: `${diff ? 'Current self' : 'Self'} ${metricUnit}`,
     selfPercent: 'Self %',
-    total: `Total ${metric.name} (${unitDisplay})`,
+    total: `${diff ? 'Current total' : 'Total'} ${metricUnit}`,
     totalPercent: 'Total %',
+    baselineSelf: `Baseline self ${metricUnit}`,
+    selfDelta: `Self delta ${metricUnit}`,
+    selfDeltaPercent: 'Self delta %',
+    baselineTotal: `Baseline total ${metricUnit}`,
+    totalDelta: `Total delta ${metricUnit}`,
+    totalDeltaPercent: 'Total delta %',
   };
   const total = data.allRootsCumulativeValue;
   const pct = (value: number) =>
     (total === 0 ? 0 : (value / total) * 100).toFixed(2);
+  // Sorted like the view: by self, or by its change in a diff.
+  const sortValue = (fn: TreeExplorerFlatFunction) =>
+    fn.self - (fn.baselineSelf ?? 0);
   const rows = computeFlatFunctions(data)
-    .sort((a, b) => b.self - a.self)
+    .sort((a, b) => sortValue(b) - sortValue(a))
     .map((fn) => ({
       name: fn.name,
       self: fn.self.toString(),
       selfPercent: pct(fn.self),
       total: fn.total.toString(),
       totalPercent: pct(fn.total),
+      ...(fn.baselineTotal === undefined || fn.baselineSelf === undefined
+        ? {}
+        : {
+            baselineSelf: fn.baselineSelf.toString(),
+            selfDelta: (fn.self - fn.baselineSelf).toString(),
+            selfDeltaPercent: exportRelativeChange(fn.baselineSelf, fn.self),
+            baselineTotal: fn.baselineTotal.toString(),
+            totalDelta: (fn.total - fn.baselineTotal).toString(),
+            totalDeltaPercent: exportRelativeChange(fn.baselineTotal, fn.total),
+          }),
     }));
   switch (format) {
     case 'tsv':
diff --git a/ui/src/components/tree_explorer_table_views_unittest.ts b/ui/src/components/tree_explorer_table_views_unittest.ts
index afc5d85..9f50992 100644
--- a/ui/src/components/tree_explorer_table_views_unittest.ts
+++ b/ui/src/components/tree_explorer_table_views_unittest.ts
@@ -12,7 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-import {computeFlatFunctions} from './tree_explorer_table_views';
+import {
+  computeFlatDiff,
+  computeFlatFunctions,
+} from './tree_explorer_table_views';
 import type {
   TreeExplorerData,
   TreeExplorerNode,
@@ -25,6 +28,7 @@
   readonly name: string;
   readonly selfValue: number;
   readonly cumulativeValue: number;
+  readonly baselineCumulativeValue?: number;
 }
 
 function makeData(nodes: ReadonlyArray<TestNode>): TreeExplorerData {
@@ -35,10 +39,19 @@
     xStart: 0,
     xEnd: 0,
   }));
+  const compared = nodes.some((n) => n.baselineCumulativeValue !== undefined);
   return {
     nodes: fullNodes,
     unfilteredCumulativeValue: 0,
     allRootsCumulativeValue: 0,
+    diff: compared
+      ? {
+          allRootsBaselineCumulativeValue: 0,
+          unfilteredBaselineCumulativeValue: 0,
+          maxGrowth: 0,
+          maxShrink: 0,
+        }
+      : undefined,
     minDepth: Math.min(0, ...nodes.map((n) => n.depth)),
     maxDepth: Math.max(0, ...nodes.map((n) => n.depth)),
     nodeActions: [],
@@ -89,7 +102,7 @@
 
 test('computeFlatFunctions counts recursive frames once per path', () => {
   // A -> B -> A: the inner A's cumulative value is already part of the outer
-  // A's, so A's total must be 10, not 17.
+  // A's, so A's total must be 10, not 17. The same goes for baselines.
   const fns = byName(
     computeFlatFunctions(
       makeData([
@@ -100,6 +113,7 @@
           name: 'A',
           selfValue: 1,
           cumulativeValue: 10,
+          baselineCumulativeValue: 4,
         },
         {
           id: 2,
@@ -108,6 +122,7 @@
           name: 'B',
           selfValue: 2,
           cumulativeValue: 9,
+          baselineCumulativeValue: 3,
         },
         {
           id: 3,
@@ -116,12 +131,13 @@
           name: 'A',
           selfValue: 7,
           cumulativeValue: 7,
+          baselineCumulativeValue: 1,
         },
       ]),
     ),
   );
-  expect(fns.get('A')).toEqual({name: 'A', self: 8, total: 10});
-  expect(fns.get('B')).toEqual({name: 'B', self: 2, total: 9});
+  expect(fns.get('A')).toMatchObject({self: 8, total: 10, baselineTotal: 4});
+  expect(fns.get('B')).toMatchObject({self: 2, total: 9, baselineTotal: 3});
 });
 
 test('computeFlatFunctions adds distinct paths through the same name', () => {
@@ -204,3 +220,36 @@
   expect(fns.get('Pivot')).toEqual({name: 'Pivot', self: 3, total: 10});
   expect(fns.get('Callee')).toEqual({name: 'Callee', self: 7, total: 7});
 });
+
+test('computeFlatDiff scales by merged self deltas only', () => {
+  const diff = computeFlatDiff(
+    {
+      allRootsBaselineCumulativeValue: 10,
+      unfilteredBaselineCumulativeValue: 10,
+      maxGrowth: 4,
+      maxShrink: 2,
+    },
+    [
+      {
+        name: 'merged',
+        self: 10,
+        total: 100,
+        baselineSelf: 2,
+        baselineTotal: 2,
+      },
+      {
+        name: 'shrunk',
+        self: 1,
+        total: 1,
+        baselineSelf: 6,
+        baselineTotal: 60,
+      },
+    ],
+  );
+  expect(diff).toEqual({
+    allRootsBaselineCumulativeValue: 10,
+    unfilteredBaselineCumulativeValue: 10,
+    maxGrowth: 8,
+    maxShrink: 5,
+  });
+});
diff --git a/ui/src/widgets/flamegraph.ts b/ui/src/widgets/flamegraph.ts
index 033ec4a..6d8dbab 100644
--- a/ui/src/widgets/flamegraph.ts
+++ b/ui/src/widgets/flamegraph.ts
@@ -55,6 +55,7 @@
   addFilter,
   displayPercentage,
   displaySize,
+  exportRelativeChange,
   getUnitDisplayName,
   metricId,
 } from './tree_explorer';
@@ -1193,11 +1194,14 @@
   metric: TreeExplorerMetric,
   format: ExportFormat,
 ): string {
-  const {nodes} = data;
+  const {nodes, diff} = data;
   const unitDisplay = getUnitDisplayName(metric.unit);
 
   const unaggKeys: string[] = [];
   const aggKeys: string[] = [];
+  // Properties with a baseline value, whose columns in a diff are their
+  // baseline and current values and the change.
+  const diffKeys = new Set<string>();
   const propDisplayNames = new Map<string, string>();
   for (const node of nodes) {
     for (const [key, prop] of node.properties) {
@@ -1206,6 +1210,9 @@
         keys.push(key);
         propDisplayNames.set(key, prop.displayName);
       }
+      if (diff !== undefined && prop.baselineValue !== undefined) {
+        diffKeys.add(key);
+      }
     }
   }
 
@@ -1215,19 +1222,44 @@
     'depth',
     'name',
     ...unaggKeys,
-    'cumulativeValue',
-    'selfValue',
-    ...aggKeys,
+    ...(diff === undefined
+      ? ['cumulativeValue', 'selfValue']
+      : [
+          'cumulativeValue',
+          'baselineCumulativeValue',
+          'cumulativeDelta',
+          'cumulativeDeltaPercent',
+          'selfValue',
+          'baselineSelfValue',
+          'selfDelta',
+          'selfDeltaPercent',
+        ]),
+    ...aggKeys.flatMap((key) =>
+      diffKeys.has(key) ? [key, `${key}:baseline`, `${key}:delta`] : [key],
+    ),
   ];
+  const metricUnit = `${metric.name} (${unitDisplay})`;
   const columnNames: Record<string, string> = {
     ...Object.fromEntries(propDisplayNames),
     id: 'Id',
     parentId: 'Parent Id',
     depth: 'Depth',
     name: metric.nameColumnLabel ?? 'Name',
-    cumulativeValue: `Cumulative ${metric.name} (${unitDisplay})`,
-    selfValue: `Self ${metric.name} (${unitDisplay})`,
+    cumulativeValue: `${diff ? 'Current cumulative' : 'Cumulative'} ${metricUnit}`,
+    selfValue: `${diff ? 'Current self' : 'Self'} ${metricUnit}`,
+    baselineCumulativeValue: `Baseline cumulative ${metricUnit}`,
+    cumulativeDelta: `Cumulative delta ${metricUnit}`,
+    cumulativeDeltaPercent: 'Cumulative delta %',
+    baselineSelfValue: `Baseline self ${metricUnit}`,
+    selfDelta: `Self delta ${metricUnit}`,
+    selfDeltaPercent: 'Self delta %',
   };
+  for (const key of diffKeys) {
+    const displayName = propDisplayNames.get(key);
+    columnNames[`${key}:baseline`] = `Baseline ${displayName}`;
+    columnNames[key] = `Current ${displayName}`;
+    columnNames[`${key}:delta`] = `${displayName} delta`;
+  }
   const rows = nodes.map((n) => {
     const row: Record<string, string> = {
       id: n.id.toString(),
@@ -1237,8 +1269,28 @@
       cumulativeValue: n.cumulativeValue.toString(),
       selfValue: n.selfValue.toString(),
     };
+    if (diff !== undefined) {
+      const baselineCumulative = n.baselineCumulativeValue ?? 0;
+      const baselineSelf = n.baselineSelfValue ?? 0;
+      row.baselineCumulativeValue = baselineCumulative.toString();
+      row.cumulativeDelta = (n.cumulativeValue - baselineCumulative).toString();
+      row.cumulativeDeltaPercent = exportRelativeChange(
+        baselineCumulative,
+        n.cumulativeValue,
+      );
+      row.baselineSelfValue = baselineSelf.toString();
+      row.selfDelta = (n.selfValue - baselineSelf).toString();
+      row.selfDeltaPercent = exportRelativeChange(baselineSelf, n.selfValue);
+    }
     for (const key of [...unaggKeys, ...aggKeys]) {
-      row[key] = n.properties.get(key)?.value ?? '';
+      const prop = n.properties.get(key);
+      row[key] = prop?.value ?? '';
+      if (diffKeys.has(key) && prop?.baselineValue !== undefined) {
+        row[`${key}:baseline`] = prop.baselineValue;
+        row[`${key}:delta`] = (
+          Number(prop.value) - Number(prop.baselineValue)
+        ).toString();
+      }
     }
     return row;
   });
@@ -1528,6 +1580,19 @@
   return scheme;
 }
 
+// The colors of a change, for the other views of a diff, or undefined for no
+// change.
+export function diffColors(
+  change: number,
+  diff: TreeExplorerDiff,
+): {readonly background: string; readonly text: string} | undefined {
+  if (change === 0) {
+    return undefined;
+  }
+  const {base, textBase} = getDiffColorScheme(change, diff, false);
+  return {background: base.cssString, text: textBase.cssString};
+}
+
 // 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) {
diff --git a/ui/src/widgets/tree_explorer.ts b/ui/src/widgets/tree_explorer.ts
index 94583d8..1e6956e 100644
--- a/ui/src/widgets/tree_explorer.ts
+++ b/ui/src/widgets/tree_explorer.ts
@@ -506,6 +506,14 @@
   return `${change > 0 ? '+' : ''}${change.toFixed(2)}%`;
 }
 
+// relativeChange for exports: a number with two decimals, or "new".
+export function exportRelativeChange(
+  baseline: number,
+  current: number,
+): string {
+  return relativeChange(baseline, current)?.toFixed(2) ?? 'new';
+}
+
 export function getUnitDisplayName(unit: string | undefined): string {
   if (unit === undefined || unit === '' || unit === 'count') {
     return 'count';