Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 16 additions & 26 deletions packages/explain/src/components/ExplainTableView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
formatRatio,
formatRows,
formatTime,
getRowEstimateRatio,
getExplainTableRow,
} from '../plan';
import {ExplainDiagnosticChips} from './ExplainDiagnosticChips';
import {ExplainNodeDetails} from './ExplainNodeDetails';
Expand Down Expand Up @@ -173,28 +173,20 @@ function TreeRows({
const nodeMetrics: ExplainNodeMetrics | undefined = metrics.byId.get(node.id);
const nodeDiagnostics = diagnostics.get(node.id) ?? [];

const row = getExplainTableRow(node, hasAnalyzeData, nodeMetrics);

const costStr =
node.startup_cost != null && node.total_cost != null
? `${formatCost(node.startup_cost)} - ${formatCost(node.total_cost)}`
: node.total_cost != null
? formatCost(node.total_cost)
row.startupCost != null && row.totalCost != null
? `${formatCost(row.startupCost)} - ${formatCost(row.totalCost)}`
: row.totalCost != null
? formatCost(row.totalCost)
: '-';

const timeStr =
hasAnalyzeData && nodeMetrics?.exclusiveTimeMs != null
? formatTime(nodeMetrics.exclusiveTimeMs)
: '-';
const timeStr = row.exclusiveTimeMs != null ? formatTime(row.exclusiveTimeMs) : '-';

const rowsStr = node.plan_rows != null ? formatRows(node.plan_rows) : '-';
const actualRowsStr =
hasAnalyzeData && node.actual_rows != null ? formatRows(node.actual_rows) : '-';
const rowRatio = getRowEstimateRatio(node);
const ratioStr =
rowRatio != null
? rowRatio >= 1
? formatRatio(rowRatio)
: formatRatio(1 / rowRatio)
: '-';
const rowsStr = row.planRows != null ? formatRows(row.planRows) : '-';
const actualRowsStr = row.actualRows != null ? formatRows(row.actualRows) : '-';
const ratioStr = row.estimateGap != null ? formatRatio(row.estimateGap) : '-';

return (
<>
Expand Down Expand Up @@ -237,7 +229,7 @@ function TreeRows({
</div>
</td>
<td className="px-3 py-1.5 text-secondary whitespace-nowrap">
{node.relation ?? ''}
{row.relation ?? ''}
</td>
<td className="px-3 py-1.5 text-right text-secondary font-mono whitespace-nowrap">
{costStr}
Expand All @@ -257,18 +249,16 @@ function TreeRows({
<span
className={clsx(
'font-mono',
rowRatio == null
? 'text-secondary'
: rowRatio >= 4 || rowRatio <= 0.25
? 'text-amber-300'
: 'text-secondary',
row.estimateGap != null && row.estimateGap >= 4
? 'text-amber-300'
: 'text-secondary',
)}
>
{ratioStr}
</span>
</td>
<td className="px-3 py-1.5 text-muted truncate max-w-[200px]">
{node.filter ?? ''}
{row.filter ?? ''}
</td>
</tr>
{isExpanded &&
Expand Down
78 changes: 42 additions & 36 deletions packages/explain/src/plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* produced the plan.
*/
import type {ExplainNode, ExplainPlan} from './types';
import type {ExplainMetrics} from './metrics';
import type {ExplainMetrics, ExplainNodeMetrics} from './metrics';
import {computeExplainMetrics} from './metrics';

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -158,7 +158,11 @@ export function getRowEstimateRatio(node: ExplainNode): number | null {
return node.actual_rows / node.plan_rows;
}

function getMismatchMagnitude(node: ExplainNode): number | null {
/**
* How far the row estimate was off, as a factor of at least 1 whichever way it
* missed: 3 means three times more or three times fewer rows than estimated.
*/
export function getRowEstimateGap(node: ExplainNode): number | null {
const ratio = getRowEstimateRatio(node);
if (ratio == null) {
return null;
Expand Down Expand Up @@ -244,7 +248,7 @@ export function getExplainPlanSummary(
}

const ratio = getRowEstimateRatio(node);
const magnitude = getMismatchMagnitude(node);
const magnitude = getRowEstimateGap(node);
if (
ratio != null &&
magnitude != null &&
Expand Down Expand Up @@ -311,52 +315,54 @@ export interface ExplainTableRowData {
depth: number;
nodeType: string;
relation: string | null;
cost: string | null;
startupCost: number | null;
totalCost: number | null;
planRows: number | null;
actualRows: number | null;
exclusiveTimeMs: number | null;
/** See {@link getRowEstimateGap}. */
estimateGap: number | null;
filter: string | null;
}

/**
* Flatten an ExplainPlan tree into presentation-ready rows for tabular display and export.
* Preserves tree pre-order, computes depth, and extracts key metrics.
* Leaves unavailable metrics null rather than converting them to zero.
* The values shown for one node in the table view and written to its CSV
* export, so both always agree. Values stay raw numbers: each consumer formats
* them (abbreviated on screen, plain in the CSV). Unavailable metrics are null,
* never zero, and measured values are null unless the plan has ANALYZE data.
*/
export function getExplainTableRow(
node: ExplainNode,
hasAnalyzeData: boolean,
nodeMetrics?: ExplainNodeMetrics,
fallbackIndex = 1,
): ExplainTableRowData {
return {
index: nodeMetrics?.index ?? fallbackIndex,
depth: nodeMetrics?.depth ?? 0,
nodeType: node.node_type,
relation: node.relation ?? null,
startupCost: node.startup_cost ?? null,
totalCost: node.total_cost ?? null,
planRows: node.plan_rows ?? null,
actualRows: hasAnalyzeData ? (node.actual_rows ?? null) : null,
exclusiveTimeMs: hasAnalyzeData ? (nodeMetrics?.exclusiveTimeMs ?? null) : null,
estimateGap: getRowEstimateGap(node),
filter: node.filter ?? null,
};
}

/**
* Flatten an ExplainPlan tree into table rows, in tree pre-order, collapsed
* branches included. See {@link getExplainTableRow} for the row values.
*/
export function getExplainTableRows(
plan: ExplainPlan,
metrics?: ExplainMetrics,
): ExplainTableRowData[] {
const nodes = flattenExplainNodes(plan.root);
const planMetrics = metrics ?? computeExplainMetrics(plan);

return nodes.map((node, i) => {
const nodeMetrics = planMetrics.byId.get(node.id);
const index = nodeMetrics?.index ?? i + 1;
const depth = nodeMetrics?.depth ?? 0;

let cost: string | null = null;
if (node.startup_cost != null && node.total_cost != null) {
cost = `${node.startup_cost} - ${node.total_cost}`;
} else if (node.total_cost != null) {
cost = `${node.total_cost}`;
}

const rowRatio = getRowEstimateRatio(node);
const estimateGap = rowRatio != null ? (rowRatio >= 1 ? rowRatio : 1 / rowRatio) : null;

return {
index,
depth,
nodeType: node.node_type,
relation: node.relation ?? null,
cost,
planRows: node.plan_rows ?? null,
actualRows: plan.has_analyze_data ? (node.actual_rows ?? null) : null,
exclusiveTimeMs: plan.has_analyze_data ? (nodeMetrics?.exclusiveTimeMs ?? null) : null,
estimateGap,
filter: node.filter ?? null,
};
});
return flattenExplainNodes(plan.root).map((node, i) =>
getExplainTableRow(node, plan.has_analyze_data, planMetrics.byId.get(node.id), i + 1),
);
}
81 changes: 80 additions & 1 deletion packages/explain/tests/plan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ import {
getMaxCost,
getMaxTime,
getRowEstimateRatio,
getRowEstimateGap,
getExplainTableRow,
getExplainTableRows,
} from '../src/plan';
import {computeExplainMetrics} from '../src/metrics';
import type {ExplainNode, ExplainPlan} from '../src/types';

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -258,6 +261,22 @@ describe('plan', () => {
});
});

describe('getRowEstimateGap', () => {
it('should return the ratio when more rows came back than estimated', () => {
expect(getRowEstimateGap(makeNode({plan_rows: 10, actual_rows: 40}))).toBe(4);
});

it('should return the inverse ratio when fewer rows came back than estimated', () => {
expect(getRowEstimateGap(makeNode({plan_rows: 40, actual_rows: 10}))).toBe(4);
});

it('should return null when either side is missing or zero', () => {
expect(getRowEstimateGap(makeNode({plan_rows: null, actual_rows: 10}))).toBeNull();
expect(getRowEstimateGap(makeNode({plan_rows: 10, actual_rows: null}))).toBeNull();
expect(getRowEstimateGap(makeNode({plan_rows: 10, actual_rows: 0}))).toBeNull();
});
});

describe('getExplainPlanSummary', () => {
it('should compute highest cost, slowest node, mismatch, and operation counts', () => {
const child = makeNode({
Expand Down Expand Up @@ -390,7 +409,8 @@ describe('plan', () => {
expect(rows).toHaveLength(1);
const row = rows[0];

expect(row.cost).toBe('10.5 - 25');
expect(row.startupCost).toBe(10.5);
expect(row.totalCost).toBe(25);
expect(row.planRows).toBe(1000);
expect(row.actualRows).toBeNull();
expect(row.exclusiveTimeMs).toBeNull();
Expand Down Expand Up @@ -436,4 +456,63 @@ describe('plan', () => {
expect(rows[1].estimateGap).toBe(5);
});
});
describe('getExplainTableRow', () => {
it('should keep costs as raw numbers, null when not reported', () => {
const row = getExplainTableRow(
makeNode({startup_cost: null, total_cost: 12.75}),
false,
);

expect(row.startupCost).toBeNull();
expect(row.totalCost).toBe(12.75);
});

it('should hide measured values when the plan has no ANALYZE data', () => {
const node = makeNode({actual_rows: 5, actual_time_ms: 3, actual_loops: 1});
const plan = makePlan({root: node, has_analyze_data: true});
const nodeMetrics = computeExplainMetrics(plan).byId.get(node.id);

const estimated = getExplainTableRow(node, false, nodeMetrics);
const analyzed = getExplainTableRow(node, true, nodeMetrics);

expect(estimated.actualRows).toBeNull();
expect(estimated.exclusiveTimeMs).toBeNull();
expect(analyzed.actualRows).toBe(5);
expect(analyzed.exclusiveTimeMs).toBe(3);
});

it('should take index and depth from metrics and fall back without them', () => {
const child = makeNode({id: 'child'});
const plan = makePlan({root: makeNode({id: 'root', children: [child]})});
const nodeMetrics = computeExplainMetrics(plan).byId.get('child');

expect(getExplainTableRow(child, false, nodeMetrics)).toMatchObject({
index: 2,
depth: 1,
});
expect(getExplainTableRow(child, false, undefined, 7)).toMatchObject({
index: 7,
depth: 0,
});
});

it('should match the row getExplainTableRows builds for the same node', () => {
const child = makeNode({
id: 'child',
plan_rows: 50,
actual_rows: 10,
total_cost: 4,
filter: 'id > 1',
});
const plan = makePlan({
root: makeNode({id: 'root', children: [child]}),
has_analyze_data: true,
});
const metrics = computeExplainMetrics(plan);

expect(getExplainTableRows(plan, metrics)[1]).toEqual(
getExplainTableRow(child, true, metrics.byId.get('child')),
);
});
});
});
22 changes: 15 additions & 7 deletions packages/web-ui/src/components/explain/VisualExplainView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
import {useEditorTheme} from '@/hooks/useEditorTheme';
import {useAlert} from '@/hooks/useAlert';
import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities';
import {useToast} from '@/hooks/useToast';
import {loadMonacoTheme} from '@/themes/themeUtils';
import {getMonacoThemeId} from '@/themes/themeRuntime';
import {
Expand All @@ -27,6 +28,7 @@ import {
saveRawExplainOutput,
} from '@/utils/explainRaw';
import {saveExplainTableCsv} from '@/utils/explainTableExport';
import {toErrorMessage} from '@/utils/errors';
import {ExplainAiAnalysis} from '@/components/modals/visual-explain/ExplainAiAnalysis';

export interface VisualExplainViewProps {
Expand Down Expand Up @@ -73,6 +75,7 @@ export const VisualExplainView = ({

const {showAlert} = useAlert();
const platform = usePlatformCapabilities();
const {showToast} = useToast();
const [isSaving, setIsSaving] = useState(false);

const rawLanguage = useMemo(
Expand Down Expand Up @@ -125,21 +128,26 @@ export const VisualExplainView = ({
try {
const saved = await saveExplainTableCsv(platform, plan, metrics);
if (saved) {
showAlert(
showToast(
t('editor.visualExplain.exportCsvSuccess', 'Explain table exported as CSV'),
{kind: 'info'},
{kind: 'success'},
);
}
} catch (err) {
console.error('Failed to export EXPLAIN table CSV:', err);
showAlert(
t('editor.visualExplain.exportCsvError', 'Failed to export EXPLAIN table as CSV'),
{kind: 'error'},
);
// Kept until dismissed so the reason can be read and reported.
showToast(toErrorMessage(err), {
title: t(
'editor.visualExplain.exportCsvError',
'Failed to export EXPLAIN table as CSV',
),
kind: 'error',
duration: 0,
});
} finally {
setIsExportingCsv(false);
}
}, [plan, metrics, platform, showAlert, t]);
}, [plan, metrics, platform, showToast, t]);

return (
<div className="flex flex-col h-full min-h-0">
Expand Down
2 changes: 1 addition & 1 deletion packages/web-ui/src/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -1708,7 +1708,7 @@
"close": "閉じる",
"graphView": "グラフ",
"tableView": "テーブル",
"tableTitle": "ツリー計画",
"tableTitle": "実行計画ツリー",
"exportCsv": "CSVエクスポート",
"exportingCsv": "エクスポート中...",
"exportCsvSuccess": "ExplainテーブルをCSVとしてエクスポートしました",
Expand Down
Loading