Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

fix(dashboard): pie panel collapses multi-column ClickHouse query to a single slice (#11919)

Abhi kumar13812fac62f5
diff --git a/frontend/src/components/YAxisUnitSelector/__tests__/formatter.test.tsx b/frontend/src/components/YAxisUnitSelector/__tests__/formatter.test.tsx
index 140b1cd77d..f0d16d81ed 100644
--- a/frontend/src/components/YAxisUnitSelector/__tests__/formatter.test.tsx
+++ b/frontend/src/components/YAxisUnitSelector/__tests__/formatter.test.tsx
@@ -680,6 +680,13 @@ describe('formatUniversalUnit', () => {
});
describe('Datetime', () => {
+ beforeAll(() => {
+ jest.useFakeTimers().setSystemTime(new Date('2026-01-01T00:00:00Z'));
+ });
+ afterAll(() => {
+ jest.useRealTimers();
+ });
+
it('formats datetime units', () => {
expect(formatUniversalUnit(900, UniversalYAxisUnit.DATETIME_FROM_NOW)).toBe(
'56 years ago',
diff --git a/frontend/src/container/PanelWrapper/PiePanelWrapper.tsx b/frontend/src/container/PanelWrapper/PiePanelWrapper.tsx
index ad60cfe661..d772e3275e 100644
--- a/frontend/src/container/PanelWrapper/PiePanelWrapper.tsx
+++ b/frontend/src/container/PanelWrapper/PiePanelWrapper.tsx
@@ -1,4 +1,4 @@
-import { useRef, useState } from 'react';
+import { useMemo, useRef, useState } from 'react';
import { Color } from '@signozhq/design-tokens';
import { Group } from '@visx/group';
import { Pie } from '@visx/shape';
@@ -8,12 +8,10 @@ import { themeColors } from 'constants/theme';
import { getPieChartClickData } from 'container/QueryTable/Drilldown/drilldownUtils';
import useGraphContextMenu from 'container/QueryTable/Drilldown/useGraphContextMenu';
import { useIsDarkMode } from 'hooks/useDarkMode';
-import getLabelName from 'lib/getLabelName';
-import { generateColor } from 'lib/uPlotLib/utils/generateColor';
-import { isNaN } from 'lodash-es';
import ContextMenu, { useCoordinates } from 'periscope/components/ContextMenu';
import { PanelWrapperProps, TooltipData } from './panelWrapper.types';
+import { preparePieChartData } from './preparePieChartData';
import { lightenColor, tooltipStyles } from './utils';
import './PiePanelWrapper.styles.scss';
@@ -44,37 +42,15 @@ function PiePanelWrapper({
detectBounds: true,
});
- const panelData = queryResponse.data?.payload?.data?.result || [];
-
const isDarkMode = useIsDarkMode();
- let pieChartData: {
- label: string;
- value: string;
- color: string;
- record: any;
- }[] = [].concat(
- ...(panelData
- .map((d) => {
- const label = getLabelName(d.metric, d.queryName || '', d.legend || '');
- return {
- label,
- value: d?.values?.[0]?.[1],
- record: d,
- color:
- widget?.customLegendColors?.[label] ||
- generateColor(
- label,
- isDarkMode ? themeColors.chartcolors : themeColors.lightModeColor,
- ),
- };
- })
- .filter((d) => d !== undefined) as never[]),
- );
-
- pieChartData = pieChartData.filter(
- (arc) =>
- arc.value && !isNaN(parseFloat(arc.value)) && parseFloat(arc.value) > 0,
+ const pieChartData = useMemo(
+ () =>
+ preparePieChartData(queryResponse.data?.payload, {
+ customLegendColors: widget?.customLegendColors,
+ colorMap: isDarkMode ? themeColors.chartcolors : themeColors.lightModeColor,
+ }),
+ [queryResponse.data?.payload, widget?.customLegendColors, isDarkMode],
);
let size = 0;
diff --git a/frontend/src/container/PanelWrapper/__tests__/preparePieChartData.test.ts b/frontend/src/container/PanelWrapper/__tests__/preparePieChartData.test.ts
new file mode 100644
index 0000000000..cfe8c01978
--- /dev/null
+++ b/frontend/src/container/PanelWrapper/__tests__/preparePieChartData.test.ts
@@ -0,0 +1,185 @@
+import { themeColors } from 'constants/theme';
+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
+import { QueryData, QueryDataV3 } from 'types/api/widgets/getQuery';
+
+import { preparePieChartData } from '../preparePieChartData';
+
+const options = { colorMap: themeColors.chartcolors };
+
+/**
+ * Mirrors a query-range payload: the (possibly collapsed) time-series `result`
+ * plus the scalar table nested under `newResult` (as getQueryResults produces it).
+ */
+function makePayload(
+ result: QueryData[],
+ tables: QueryDataV3[],
+): MetricRangePayloadProps {
+ return {
+ data: {
+ result,
+ resultType: 'scalar',
+ newResult: { data: { result: tables, resultType: 'scalar' } },
+ },
+ } as MetricRangePayloadProps;
+}
+
+function tableEntry(
+ columns: NonNullable<QueryDataV3['table']>['columns'],
+ rows: NonNullable<QueryDataV3['table']>['rows'],
+ overrides: Partial<QueryDataV3> = {},
+): QueryDataV3 {
+ return {
+ queryName: 'A',
+ legend: '',
+ series: null,
+ list: null,
+ table: { columns, rows },
+ ...overrides,
+ } as QueryDataV3;
+}
+
+describe('preparePieChartData', () => {
+ it('renders a slice per value column for a multi-column ClickHouse scalar', () => {
+ // SELECT count() AS col1, sum(value) AS col2 — the backend collapses the
+ // time-series result onto col1; the full data lives in the scalar table.
+ const payload = makePayload(
+ [
+ {
+ metric: {},
+ queryName: 'A',
+ legend: '',
+ values: [[0, '23399927']],
+ } as QueryData,
+ ],
+ [
+ tableEntry(
+ [
+ { name: 'col1', queryName: 'A', isValueColumn: true, id: 'col1' },
+ { name: 'col2', queryName: 'A', isValueColumn: true, id: 'col2' },
+ ],
+ [{ data: { col1: 23399927, col2: 588691297 } }],
+ ),
+ ],
+ );
+
+ const slices = preparePieChartData(payload, options);
+
+ expect(slices).toHaveLength(2);
+ expect(slices.map((s) => [s.label, s.value])).toStrictEqual([
+ ['col1', '23399927'],
+ ['col2', '588691297'],
+ ]);
+ });
+
+ it('prefixes the group when multiple value columns are grouped', () => {
+ const payload = makePayload(
+ [],
+ [
+ tableEntry(
+ [
+ { name: 'env', queryName: 'A', isValueColumn: false, id: 'env' },
+ { name: 'col1', queryName: 'A', isValueColumn: true, id: 'col1' },
+ { name: 'col2', queryName: 'A', isValueColumn: true, id: 'col2' },
+ ],
+ [{ data: { env: 'prod', col1: 10, col2: 20 } }],
+ ),
+ ],
+ );
+
+ const slices = preparePieChartData(payload, options);
+
+ expect(slices.map((s) => s.label)).toStrictEqual([
+ 'prod · col1',
+ 'prod · col2',
+ ]);
+ expect(slices[0].record.metric).toStrictEqual({ env: 'prod' });
+ });
+
+ it('drops non-positive and non-numeric values', () => {
+ const payload = makePayload(
+ [],
+ [
+ tableEntry(
+ [
+ { name: 'col1', queryName: 'A', isValueColumn: true, id: 'col1' },
+ { name: 'col2', queryName: 'A', isValueColumn: true, id: 'col2' },
+ { name: 'col3', queryName: 'A', isValueColumn: true, id: 'col3' },
+ ],
+ [{ data: { col1: 5, col2: 0, col3: 'n/a' } }],
+ ),
+ ],
+ );
+
+ const slices = preparePieChartData(payload, options);
+
+ expect(slices.map((s) => s.label)).toStrictEqual(['col1']);
+ });
+
+ it('keeps the series path for a single value column (grouped panel)', () => {
+ // One value column → the time-series result is authoritative (one slice per
+ // group), so existing behaviour is preserved.
+ const payload = makePayload(
+ [
+ {
+ metric: { 'service.name': 'adservice' },
+ queryName: 'A',
+ legend: 'adservice',
+ values: [[0, '100']],
+ } as QueryData,
+ {
+ metric: { 'service.name': 'cartservice' },
+ queryName: 'A',
+ legend: 'cartservice',
+ values: [[0, '200']],
+ } as QueryData,
+ ],
+ [
+ tableEntry(
+ [
+ {
+ name: 'service.name',
+ queryName: 'A',
+ isValueColumn: false,
+ id: 'service.name',
+ },
+ { name: 'count', queryName: 'A', isValueColumn: true, id: 'A' },
+ ],
+ [
+ { data: { 'service.name': 'adservice', A: 100 } },
+ { data: { 'service.name': 'cartservice', A: 200 } },
+ ],
+ ),
+ ],
+ );
+
+ const slices = preparePieChartData(payload, options);
+
+ expect(slices.map((s) => [s.label, s.value])).toStrictEqual([
+ ['adservice', '100'],
+ ['cartservice', '200'],
+ ]);
+ });
+
+ it('uses the legacy series result when there is no scalar table', () => {
+ const payload = makePayload(
+ [
+ {
+ metric: { 'service.name': 'adservice' },
+ queryName: 'A',
+ legend: '{{service.name}}',
+ values: [[1000, '42']],
+ } as QueryData,
+ ],
+ [],
+ );
+
+ const slices = preparePieChartData(payload, options);
+
+ expect(slices).toHaveLength(1);
+ expect(slices[0].value).toBe('42');
+ });
+
+ it('returns no slices for an empty payload', () => {
+ expect(preparePieChartData(undefined, options)).toStrictEqual([]);
+ });
+});
diff --git a/frontend/src/container/PanelWrapper/preparePieChartData.ts b/frontend/src/container/PanelWrapper/preparePieChartData.ts
new file mode 100644
index 0000000000..6455a1f006
--- /dev/null
+++ b/frontend/src/container/PanelWrapper/preparePieChartData.ts
@@ -0,0 +1,144 @@
+import getLabelName from 'lib/getLabelName';
+import { generateColor } from 'lib/uPlotLib/utils/generateColor';
+import { isNaN } from 'lodash-es';
+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
+import { QueryData, QueryDataV3 } from 'types/api/widgets/getQuery';
+
+export interface PieChartSlice {
+ label: string;
+ value: string;
+ color: string;
+ record: {
+ queryName: string;
+ legend?: string;
+ /** Group-by labels, used for drilldown; absent when the slice has no group. */
+ metric?: QueryData['metric'];
+ };
+}
+
+interface PreparePieChartDataOptions {
+ customLegendColors?: Record<string, string>;
+ colorMap: Record<string, string>;
+}
+
+const colorFor = (
+ label: string,
+ { customLegendColors, colorMap }: PreparePieChartDataOptions,
+): string => customLegendColors?.[label] || generateColor(label, colorMap);
+
+const isPositive = (value: string): boolean =>
+ !!value && !isNaN(parseFloat(value)) && parseFloat(value) > 0;
+
+/**
+ * Time-series result: one slice per series, value = first datapoint. This is the
+ * original pie behaviour — kept verbatim (same label/value/colour/record) so
+ * single-value and grouped panels are unaffected.
+ */
+function slicesFromSeries(
+ result: QueryData[],
+ options: PreparePieChartDataOptions,
+): PieChartSlice[] {
+ return result
+ .filter((d) => d?.values?.[0]?.[1] !== undefined)
+ .map((d) => {
+ const label = getLabelName(d.metric, d.queryName || '', d.legend || '');
+ return {
+ label,
+ value: d.values[0][1],
+ color: colorFor(label, options),
+ record: d,
+ };
+ });
+}
+
+/**
+ * V5 scalar table: one slice per (row × value column). With more than one value
+ * column the column name keeps the slices distinct, so a ClickHouse query like
+ * `count() AS col1, sum() AS col2` renders a slice per column instead of
+ * collapsing onto the first; group-by columns become the slice label.
+ */
+function slicesFromTables(
+ tables: QueryDataV3[],
+ options: PreparePieChartDataOptions,
+): PieChartSlice[] {
+ const slices: PieChartSlice[] = [];
+
+ tables.forEach((entry) => {
+ const { table } = entry;
+ if (!table?.columns?.length || !table?.rows?.length) {
+ return;
+ }
+
+ const valueColumns = table.columns.filter((column) => column.isValueColumn);
+ if (valueColumns.length === 0) {
+ return;
+ }
+ const labelColumns = table.columns.filter((column) => !column.isValueColumn);
+ const hasMultipleValueColumns = valueColumns.length > 1;
+
+ table.rows.forEach((row) => {
+ const groupLabel = labelColumns
+ .map((column) => row.data[column.id || column.name])
+ .filter((part) => part != null)
+ .map(String)
+ .join(', ');
+ // Drilldown filters by group-by labels; leave it undefined when there
+ // are none (e.g. a ClickHouse query) so no filterless menu is offered.
+ const metric = labelColumns.length
+ ? labelColumns.reduce<Record<string, string>>((acc, column) => {
+ acc[column.name] = String(row.data[column.id || column.name]);
+ return acc;
+ }, {})
+ : undefined;
+
+ valueColumns.forEach((column) => {
+ let label: string;
+ if (hasMultipleValueColumns) {
+ label = groupLabel ? `${groupLabel} · ${column.name}` : column.name;
+ } else {
+ label = groupLabel || entry.legend || entry.queryName || '';
+ }
+
+ slices.push({
+ label,
+ value: String(row.data[column.id || column.name]),
+ color: colorFor(label, options),
+ record: { queryName: entry.queryName, legend: entry.legend, metric },
+ });
+ });
+ });
+ });
+
+ return slices;
+}
+
+/**
+ * Builds pie slices from a query-range payload, dropping non-positive/non-numeric
+ * values.
+ *
+ * A scalar response with several value columns (e.g. a ClickHouse
+ * `count() AS col1, sum() AS col2`) collapses to a single series in
+ * `data.result` — only the first value column survives. The full data is kept in
+ * the scalar table under `newResult`, so in that case slices are built from the
+ * table (one per value column). Otherwise the legacy time-series result is used,
+ * preserving existing behaviour for single-value and grouped panels.
+ */
+export function preparePieChartData(
+ payload: MetricRangePayloadProps | undefined,
+ options: PreparePieChartDataOptions,
+): PieChartSlice[] {
+ const tables = (payload?.data?.newResult?.data?.result || []).filter(
+ (entry) => entry?.table?.rows?.length,
+ );
+ const hasMultipleValueColumns = tables.some(
+ (entry) =>
+ (entry.table?.columns || []).filter((column) => column.isValueColumn)
+ .length > 1,
+ );
+
+ const slices = hasMultipleValueColumns
+ ? slicesFromTables(tables, options)
+ : slicesFromSeries(payload?.data?.result || [], options);
+
+ return slices.filter((slice) => isPositive(slice.value));
+}