From 8341f0900e868c6b69b2712f1793079f426c6bb1 Mon Sep 17 00:00:00 2001 From: Tyagiquamar Date: Wed, 2 Dec 2026 12:21:13 +0530 Subject: [PATCH] fix(common-utils): query every expression of a PromQL table tile Table tiles kept only the first PromQL expression and silently dropped the rest. They now query every expression and join the results into one value column per expression (named after the expression's alias), the way a builder table gives one column per select item. Instant queries join on the label set, range queries on the label set and timestamp. The chart editor also offers multi-expression editing for table tiles, matching what the query path already supports for time series charts. --- .changeset/promql-table-multi-expression.md | 7 ++ .../mcp/prompts/dashboards/promqlContent.ts | 2 +- .../api/src/mcp/tools/dashboards/schemas.ts | 5 +- .../tools/query/__tests__/promqlTile.test.ts | 49 ++++++++ .../ChartEditor/PromqlChartEditor.tsx | 2 +- .../src/core/__tests__/promql.test.ts | 4 +- .../src/core/__tests__/promqlChart.test.ts | 110 +++++++++++++++++- packages/common-utils/src/core/promql.ts | 11 +- packages/common-utils/src/core/promqlChart.ts | 106 ++++++++++++----- 9 files changed, 253 insertions(+), 43 deletions(-) create mode 100644 .changeset/promql-table-multi-expression.md diff --git a/.changeset/promql-table-multi-expression.md b/.changeset/promql-table-multi-expression.md new file mode 100644 index 0000000000..f02efcd44f --- /dev/null +++ b/.changeset/promql-table-multi-expression.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/app': patch +'@hyperdx/api': patch +--- + +fix: query every expression of a PromQL table tile. Table tiles used to run only the first expression and drop the rest without warning; they now return one value column per expression, joined on the label set (and timestamp for range queries), and the editor offers multi-expression editing for table tiles. diff --git a/packages/api/src/mcp/prompts/dashboards/promqlContent.ts b/packages/api/src/mcp/prompts/dashboards/promqlContent.ts index 6944947af3..beb8f114f3 100644 --- a/packages/api/src/mcp/prompts/dashboards/promqlContent.ts +++ b/packages/api/src/mcp/prompts/dashboards/promqlContent.ts @@ -46,7 +46,7 @@ export const PROMQL_DASHBOARD_SECTION = `== PROMQL TILES == Sources with kind "promql" hold Prometheus metrics. Chart them with PROMQL tiles, not builder or raw SQL tiles: { "name": "Request rate", "config": { "configType": "promql", "displayType": "line", "sourceId": "", "expressions": [{ "expression": "sum by (job) (rate(http_requests_total{job=~\\"$job\\"}[$__rate_interval]))" }], "legendTemplate": "{{job}}" } } - - displayType works as for builder tiles. line, stacked_bar and stacked_line plot every expression; number, table, pie and bar query only the first and can set queryType "instant" to evaluate once at the end of the range. + - displayType works as for builder tiles. line, stacked_bar, stacked_line and table plot every expression (a table joins them into one value column per expression); number, pie and bar query only the first and can set queryType "instant" to evaluate once at the end of the range. - legendTemplate names each series from its labels, e.g. "{{job}} / {{instance}}". - Filter with a PROMETHEUS_LABEL dashboard filter: { "type": "PROMETHEUS_LABEL", "name": "Job", "sourceId": "", "label": "job", "variableName": "job" }. Tiles reference it in a matcher: {job=~"$job"} (multi-select) or {job="$job"} with maxSelections: 1. clickstack_describe_source with metricName lists a metric's label names. - For free-form label conditions, use an ADHOC filter with sourceType "promql": { "type": "ADHOC", "name": "Labels", "sourceType": "promql", "sources": [""] }. Its conditions are added as label matchers to every selector in the PromQL tiles on those sources, with no tile wiring. Operators: =, !=, =~, !~, and IN (shown as =| in the filter bar); IN conditions on the same label are ORed into one =~"a|b" matcher. Seed them via savedFilterValues as for sql ad hoc filters. diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index 916db33d71..3ee8705fbf 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -1456,8 +1456,9 @@ const mcpPromqlTileSchema = mcpTileLayoutSchema.extend({ .min(1) .max(MAX_PROMQL_EXPRESSIONS) .describe( - 'PromQL queries. Line and stacked charts plot every expression; ' + - 'other display types query only the first.', + 'PromQL queries. Line, stacked and table charts plot every ' + + 'expression (a table joins them into one value column per ' + + 'expression); number, pie and bar query only the first.', ), granularity: mcpUnion([SQLIntervalSchema, z.literal('auto')]) .optional() diff --git a/packages/api/src/mcp/tools/query/__tests__/promqlTile.test.ts b/packages/api/src/mcp/tools/query/__tests__/promqlTile.test.ts index dcc916cfcb..ecdb452bb1 100644 --- a/packages/api/src/mcp/tools/query/__tests__/promqlTile.test.ts +++ b/packages/api/src/mcp/tools/query/__tests__/promqlTile.test.ts @@ -105,6 +105,22 @@ describe('buildPromqlTileQueries', () => { expect(queries.map(q => q.expression)).toEqual(['sum(up)']); }); + it('queries every expression of a table tile', () => { + const queries = buildPromqlTileQueries({ + config: { + displayType: DisplayType.Table, + promqlExpression: [ + { expression: 'sum(up)', queryType: 'instant' }, + { expression: 'up', queryType: 'instant' }, + ], + }, + dateRange, + }); + + expect(queries.map(q => q.expression)).toEqual(['sum(up)', 'up']); + expect(queries.map(q => q.query.kind)).toEqual(['instant', 'instant']); + }); + it('expands dashboard variables', () => { const [{ query }] = buildPromqlTileQueries({ config: { @@ -288,6 +304,39 @@ describe('toPromqlTileResult', () => { expect(result).not.toHaveProperty('seriesLabels'); }); + it("joins a table tile's expressions into one value column each", () => { + const result = toPromqlTileResult( + { + displayType: DisplayType.Table, + promqlExpression: [ + { expression: 'requests', alias: 'requests', queryType: 'instant' }, + { expression: 'errors', alias: 'errors', queryType: 'instant' }, + ], + }, + [ + { + expression: 'requests', + alias: 'requests', + isBucketed: false, + result: [{ metric: { service: 'api' }, values: [[t0, 10]] }], + }, + { + expression: 'errors', + alias: 'errors', + isBucketed: false, + result: [{ metric: { service: 'api' }, values: [[t0, 2]] }], + }, + ], + ); + + expect(result.data).toEqual([{ service: 'api', requests: 10, errors: 2 }]); + expect(result.meta.map(m => m.name)).toEqual([ + 'service', + 'requests', + 'errors', + ]); + }); + it('keys a histogram heatmap by bucket', () => { const result = toPromqlTileResult( { diff --git a/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx b/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx index 9a7942579e..de32f984ca 100644 --- a/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx +++ b/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx @@ -91,7 +91,7 @@ export default function PromqlChartEditor({ const { data: metricNames } = usePromqlMetricNames(promqlSource?.id); const displayTypeSupportsMultiExpression = - isTimeSeriesDisplayType(displayType); + isTimeSeriesDisplayType(displayType) || displayType === DisplayType.Table; const canAddExpression = displayTypeSupportsMultiExpression && expressions.length < MAX_PROMQL_EXPRESSIONS; diff --git a/packages/common-utils/src/core/__tests__/promql.test.ts b/packages/common-utils/src/core/__tests__/promql.test.ts index f27262ec6c..81a1d10df5 100644 --- a/packages/common-utils/src/core/__tests__/promql.test.ts +++ b/packages/common-utils/src/core/__tests__/promql.test.ts @@ -62,11 +62,12 @@ describe('getQueriedPromqlSeries', () => { { expression: 'rate(errors[5m])' }, ]; - it('keeps every expression for a time series chart', () => { + it('keeps every expression for charts that plot several result sets', () => { for (const displayType of [ DisplayType.Line, DisplayType.StackedBar, DisplayType.StackedLine, + DisplayType.Table, ]) { expect(getQueriedPromqlSeries({ promqlExpression, displayType })).toEqual( promqlExpression, @@ -77,7 +78,6 @@ describe('getQueriedPromqlSeries', () => { it('keeps only the first expression for other display types', () => { for (const displayType of [ DisplayType.Number, - DisplayType.Table, DisplayType.Pie, DisplayType.Bar, undefined, diff --git a/packages/common-utils/src/core/__tests__/promqlChart.test.ts b/packages/common-utils/src/core/__tests__/promqlChart.test.ts index 67b0b669db..e30a6fd7f4 100644 --- a/packages/common-utils/src/core/__tests__/promqlChart.test.ts +++ b/packages/common-utils/src/core/__tests__/promqlChart.test.ts @@ -390,12 +390,107 @@ describe('toPromqlTableRows', () => { it('unions the labels across expressions', () => { const result = toPromqlTableRows([ instantResult({ service: 'accounting' }, 1, 1), - instantResult({ pod: 'a' }, 1, 2), + { + ...instantResult({ pod: 'a' }, 1, 2), + expression: 'up{pod="a"}', + }, + ]); + + expect(result.data).toEqual([ + { pod: '', service: 'accounting', Value_1: 1, Value_2: null }, + { pod: 'a', service: '', Value_1: null, Value_2: 2 }, + ]); + expect(result.meta).toEqual([ + { name: 'pod', type: 'String' }, + { name: 'service', type: 'String' }, + { name: 'Value_1', type: 'Float64' }, + { name: 'Value_2', type: 'Float64' }, + ]); + }); + + it('joins expressions on the label set, one value column per expression', () => { + const result = toPromqlTableRows([ + { + expression: 'max by (service) (requests)', + alias: 'requests', + isBucketed: false, + result: [ + { metric: { service: 'api' }, values: [[1, 10]] }, + { metric: { service: 'web' }, values: [[1, 20]] }, + ], + }, + { + expression: 'max by (service) (errors)', + alias: 'errors', + isBucketed: false, + result: [ + { metric: { service: 'api' }, values: [[1, 2]] }, + { metric: { service: 'db' }, values: [[1, 3]] }, + ], + }, + ]); + + expect(result.data).toEqual([ + { service: 'api', requests: 10, errors: 2 }, + { service: 'web', requests: 20, errors: null }, + { service: 'db', requests: null, errors: 3 }, + ]); + expect(result.meta).toEqual([ + { name: 'service', type: 'String' }, + { name: 'requests', type: 'Float64' }, + { name: 'errors', type: 'Float64' }, + ]); + }); + + it('joins range queries on the label set and timestamp', () => { + const result = toPromqlTableRows([ + { + expression: 'requests', + isBucketed: true, + result: [ + { + metric: { service: 'api' }, + values: [ + [1700000000, 1], + [1700000060, 2], + ], + }, + ], + }, + { + expression: 'errors', + isBucketed: true, + result: [ + { + metric: { service: 'api' }, + values: [ + [1700000000, 0], + [1700000120, 4], + ], + }, + ], + }, ]); expect(result.data).toEqual([ - { pod: '', service: 'accounting', Value: 1 }, - { pod: 'a', service: '', Value: 2 }, + { + Timestamp: '2023-11-14T22:13:20.000Z', + service: 'api', + Value_1: 1, + Value_2: 0, + }, + { + Timestamp: '2023-11-14T22:14:20.000Z', + service: 'api', + Value_1: 2, + Value_2: null, + }, + { + Timestamp: '2023-11-14T22:15:20.000Z', + service: 'api', + Value_1: null, + Value_2: 4, + }, ]); }); @@ -447,19 +542,22 @@ describe('toPromqlTableRows', () => { '__proto__', 'constructor', 'pod', - 'Value', + 'Value_1', + 'Value_2', ]); expect(Object.entries(result.data[0])).toEqual([ ['__proto__', 'b'], ['constructor', 'a'], ['pod', ''], - ['Value', 1], + ['Value_1', 1], + ['Value_2', null], ]); expect(Object.entries(result.data[1])).toEqual([ ['__proto__', ''], ['constructor', ''], ['pod', 'x'], - ['Value', 2], + ['Value_1', null], + ['Value_2', 2], ]); }); }); diff --git a/packages/common-utils/src/core/promql.ts b/packages/common-utils/src/core/promql.ts index 669c532cbf..f06f2f3c45 100644 --- a/packages/common-utils/src/core/promql.ts +++ b/packages/common-utils/src/core/promql.ts @@ -43,16 +43,19 @@ export function getExemplarPromqlExpression( /** * The expressions a PromQL config actually queries. Blank rows are skipped so * an unfinished one the editor is still holding never reaches Prometheus. Only - * time series charts plot several result sets. + * time series charts and tables plot several result sets; number, pie and bar + * tiles show one value per series and keep the first expression. */ export function getQueriedPromqlSeries(config: { promqlExpression?: PromqlExpressionList; displayType?: DisplayType; }): PromqlSeries[] { const series = getPromqlSeries(config); - const queried = isTimeSeriesDisplayType(config.displayType) - ? series - : series.slice(0, 1); + const queried = + isTimeSeriesDisplayType(config.displayType) || + config.displayType === DisplayType.Table + ? series + : series.slice(0, 1); return queried.filter(({ expression }) => expression.trim()); } diff --git a/packages/common-utils/src/core/promqlChart.ts b/packages/common-utils/src/core/promqlChart.ts index 6c6829e8cf..0709ef55d6 100644 --- a/packages/common-utils/src/core/promqlChart.ts +++ b/packages/common-utils/src/core/promqlChart.ts @@ -198,7 +198,7 @@ export function toPromqlSamples( /** Chart rows, shaped like a ClickHouse response. */ export type PromqlChartRows = { - data: Record[]; + data: Record[]; meta: { name: string; type: string }[]; rows: number; /** Time series only: each series' labels, by series name. */ @@ -279,20 +279,14 @@ function labelColumns(expressions: PromqlExpressionSamples[]): string[] { return [...(hasName ? ['__name__'] : []), ...[...keys].sort()]; } -/** Every sample of every series, lazily, so a capped caller stops reading early. */ -function* samples(expressions: PromqlExpressionSamples[]) { - for (const { result } of expressions) { - for (const { metric, values } of result) { - const labelValues = new Map(Object.entries(metric)); - for (const [ts, value] of values) yield { labelValues, ts, value }; - } - } -} - /** - * Rows for a table tile: one per sample, with a column per Prometheus label, - * including __name__, plus Timestamp and Value column. Every row carries the - * same keys in the same order. + * Rows for a table tile: one per series for an instant query, one per sample + * for a range query, with a column per Prometheus label, including __name__, + * plus Timestamp and Value column(s). A tile with several expressions gets one + * value column per expression, joined on the label set (and timestamp for + * range queries) the way a builder table gives one column per select item; + * series that share a key get one row and the expressions they miss stay + * null. Every row carries the same keys in the same order. */ export function toPromqlTableRows( expressions: PromqlExpressionSamples[], @@ -300,31 +294,89 @@ export function toPromqlTableRows( ): PromqlChartRows { const labels = labelColumns(expressions); const taken = new Set(labels); - const timeColumn = expressions.some(({ isBucketed }) => isBucketed) + const isBucketed = expressions.some(({ isBucketed }) => isBucketed); + const timeColumn = isBucketed ? uniqueColumnName('Timestamp', taken) : undefined; if (timeColumn) taken.add(timeColumn); - const valueColumn = uniqueColumnName('Value', taken); + const namedExpressions = expressions.map((expression, index) => { + // A lone expression keeps the plain "Value" column tiles already have; + // several are named after their alias, falling back to Value_1, Value_2… + const column = uniqueColumnName( + expressions.length <= 1 + ? 'Value' + : expression.alias?.trim() || `Value_${index + 1}`, + taken, + ); + taken.add(column); + return { expression, column }; + }); + // An empty result still describes the table it would have filled. + const valueColumns = + namedExpressions.length > 0 + ? namedExpressions.map(({ column }) => column) + : ['Value']; - // Cap the rows here, before the caller holds every sample. - const data: Record[] = []; - for (const { labelValues, ts, value } of samples(expressions)) { - if (data.length >= maxRows) break; - const row: [string, string | number][] = []; - if (timeColumn) row.push([timeColumn, new Date(ts * 1000).toISOString()]); - for (const label of labels) { - row.push([label, labelValues.get(label) ?? '']); + // defineProperty, not row[key] = value: a "__proto__" label would otherwise + // replace the row's prototype instead of becoming an own property. + const setCell = ( + row: Record, + column: string, + cell: string | number | null, + ) => { + Object.defineProperty(row, column, { + value: cell, + writable: true, + enumerable: true, + configurable: true, + }); + }; + + // Cap the rows here, before the caller holds every sample. The cap counts + // joined rows, so a series shared by several expressions counts once. + const rowsByKey = new Map>(); + let capped = false; + for (const { expression, column } of namedExpressions) { + for (const { metric, values } of expression.result) { + // A Map, not metric[label]: label keys like "__proto__" would otherwise + // read Object.prototype instead of the series' own value. + const labelValues = new Map(Object.entries(metric)); + const labelKey = JSON.stringify( + labels.map(label => labelValues.get(label) ?? ''), + ); + for (const [ts, value] of values) { + const key = isBucketed ? `${ts} ${labelKey}` : labelKey; + let row = rowsByKey.get(key); + if (row == null) { + if (rowsByKey.size >= maxRows) { + capped = true; + break; + } + row = {}; + if (timeColumn) { + setCell(row, timeColumn, new Date(ts * 1000).toISOString()); + } + for (const label of labels) { + setCell(row, label, labelValues.get(label) ?? ''); + } + for (const valueColumn of valueColumns) + setCell(row, valueColumn, null); + rowsByKey.set(key, row); + } + setCell(row, column, value); + } + if (capped) break; } - row.push([valueColumn, value]); - data.push(Object.fromEntries(row)); + if (capped) break; } + const data = [...rowsByKey.values()]; return { data, meta: [ ...(timeColumn ? [{ name: timeColumn, type: 'DateTime64(3)' }] : []), ...labels.map(name => ({ name, type: 'String' })), - { name: valueColumn, type: 'Float64' }, + ...valueColumns.map(name => ({ name, type: 'Float64' })), ], rows: data.length, };