diff --git a/.changeset/stacked-line-charts.md b/.changeset/stacked-line-charts.md new file mode 100644 index 0000000000..6392189e2a --- /dev/null +++ b/.changeset/stacked-line-charts.md @@ -0,0 +1,8 @@ +--- +'@hyperdx/common-utils': minor +'@hyperdx/app': minor +'@hyperdx/api': minor +'@hyperdx/cli': minor +--- + +feat: add stacked line (stacked area) time-series display type diff --git a/packages/api/openapi.json b/packages/api/openapi.json index fa589d62e1..3c23e41201 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -138,6 +138,16 @@ } ] }, + "AlertStackedLineChartConfig": { + "allOf": [ + { + "$ref": "#/components/schemas/StackedLineChartConfig" + }, + { + "$ref": "#/components/schemas/AlertChartConfigOverlay" + } + ] + }, "AlertNumberChartConfig": { "allOf": [ { @@ -149,7 +159,7 @@ ] }, "AlertChartConfig": { - "description": "The chart configuration an inline alert evaluates, in the same dialect as dashboard tile configs plus the alert-only fields in AlertChartConfigOverlay. Only the display types the alert evaluator supports are accepted: line, stacked_bar, and number, in both builder and Raw SQL (configType \"sql\") variants. Raw SQL templates must reference the evaluation window via the time-filter and interval macros (e.g. $__timeFilter and $__timeInterval), and the referenced source/connection must belong to the team.\n", + "description": "The chart configuration an inline alert evaluates, in the same dialect as dashboard tile configs plus the alert-only fields in AlertChartConfigOverlay. Only the display types the alert evaluator supports are accepted: line, stacked_bar, stacked_line, and number, in both builder and Raw SQL (configType \"sql\") variants. Raw SQL templates must reference the evaluation window via the time-filter and interval macros (e.g. $__timeFilter and $__timeInterval), and the referenced source/connection must belong to the team.\n", "oneOf": [ { "$ref": "#/components/schemas/AlertLineChartConfig" @@ -157,6 +167,9 @@ { "$ref": "#/components/schemas/AlertBarChartConfig" }, + { + "$ref": "#/components/schemas/AlertStackedLineChartConfig" + }, { "$ref": "#/components/schemas/AlertNumberChartConfig" } @@ -1031,6 +1044,7 @@ "type": "string", "enum": [ "stacked_bar", + "stacked_line", "line" ], "description": "Visual representation type for the time series." @@ -1940,6 +1954,83 @@ } } }, + "StackedLineBuilderChartConfig": { + "type": "object", + "required": [ + "displayType", + "sourceId", + "select" + ], + "description": "Builder configuration for a stacked-line time-series chart.", + "properties": { + "displayType": { + "type": "string", + "enum": [ + "stacked_line" + ], + "description": "Display type discriminator. Must be \"stacked_line\" for stacked-line charts.", + "example": "stacked_line" + }, + "sourceId": { + "type": "string", + "description": "ID of the data source to query.", + "example": "65f5e4a3b9e77c001a111111" + }, + "select": { + "type": "array", + "minItems": 1, + "maxItems": 20, + "description": "One or more aggregated values to plot. When asRatio is true, exactly two select items are required.\n", + "items": { + "$ref": "#/components/schemas/SelectItem" + } + }, + "groupBy": { + "type": "string", + "description": "Field expression to group results by (creates separate stacked bands per group value).", + "example": "service", + "maxLength": 10000 + }, + "asRatio": { + "type": "boolean", + "description": "Plot select[0] / select[1] as a ratio. Requires exactly two select items.", + "default": false + }, + "alignDateRangeToGranularity": { + "type": "boolean", + "description": "Align the date range boundaries to the query granularity interval.", + "default": true + }, + "fillNulls": { + "type": "boolean", + "description": "Fill missing time buckets with zero instead of leaving gaps.", + "default": true + }, + "numberFormat": { + "$ref": "#/components/schemas/NumberFormat", + "description": "Number formatting options for displayed values." + }, + "seriesLimit": { + "type": "integer", + "minimum": 0, + "description": "Maximum number of series rendered (top-N by value). Omit to use the default render cap, set 0 for unlimited, or a positive N to keep the top N series.", + "example": 5 + }, + "formulas": { + "type": "array", + "maxItems": 10, + "description": "Derived series computed from the select items via letter-ref arithmetic (\"A\" = select[0], \"B\" = select[1], ...). Metric, log, and trace sources only. Cannot be combined with asRatio.\n", + "items": { + "$ref": "#/components/schemas/Formula" + } + }, + "showOperandSeries": { + "type": "boolean", + "description": "Only meaningful with formulas. When false, only the formula series are returned; the raw operand series are hidden.\n", + "default": true + } + } + }, "TableBuilderChartConfig": { "type": "object", "required": [ @@ -2568,6 +2659,40 @@ } ] }, + "StackedLineRawSqlChartConfig": { + "description": "Raw SQL configuration for a stacked-line time-series chart.", + "allOf": [ + { + "$ref": "#/components/schemas/RawSqlChartConfigBase" + }, + { + "type": "object", + "required": [ + "displayType" + ], + "properties": { + "displayType": { + "type": "string", + "enum": [ + "stacked_line" + ], + "description": "Display as a stacked-line time-series chart.", + "example": "stacked_line" + }, + "fillNulls": { + "type": "boolean", + "description": "Fill missing time buckets with zero instead of leaving gaps.", + "default": true + }, + "alignDateRangeToGranularity": { + "type": "boolean", + "description": "Expand date range boundaries to the query granularity interval.", + "default": true + } + } + } + ] + }, "TableRawSqlChartConfig": { "description": "Raw SQL configuration for a table chart.", "allOf": [ @@ -2714,6 +2839,23 @@ } } }, + "StackedLineChartConfig": { + "description": "Stacked-line chart. Omit configType for the builder variant (requires sourceId and select). Set configType to \"sql\" for the Raw SQL variant (requires connectionId and sqlTemplate).\n", + "oneOf": [ + { + "$ref": "#/components/schemas/StackedLineBuilderChartConfig" + }, + { + "$ref": "#/components/schemas/StackedLineRawSqlChartConfig" + } + ], + "discriminator": { + "propertyName": "configType", + "mapping": { + "sql": "#/components/schemas/StackedLineRawSqlChartConfig" + } + } + }, "OnClickFilterTemplate": { "type": "object", "description": "A templated filter applied to the link-out destination. The rendered template value is combined with the expression as `expression IN (...)` on the destination search or dashboard. Multiple templates sharing the same expression are merged into a single IN clause.\n", @@ -2989,7 +3131,7 @@ } }, "TileConfig": { - "description": "Tile chart configuration. displayType is the primary discriminant and determines which variant group applies. For displayTypes that support both builder and Raw SQL modes (line, stacked_bar, table, number, pie, bar), configType is the secondary discriminant: omit it for the builder variant or set it to \"sql\" for the Raw SQL variant. The heatmap, search, event_patterns, and markdown displayTypes only have a builder variant.\n", + "description": "Tile chart configuration. displayType is the primary discriminant and determines which variant group applies. For displayTypes that support both builder and Raw SQL modes (line, stacked_bar, stacked_line, table, number, pie, bar), configType is the secondary discriminant: omit it for the builder variant or set it to \"sql\" for the Raw SQL variant. The heatmap, search, event_patterns, and markdown displayTypes only have a builder variant.\n", "oneOf": [ { "$ref": "#/components/schemas/LineChartConfig" @@ -2997,6 +3139,9 @@ { "$ref": "#/components/schemas/BarChartConfig" }, + { + "$ref": "#/components/schemas/StackedLineChartConfig" + }, { "$ref": "#/components/schemas/TableChartConfig" }, @@ -3027,6 +3172,7 @@ "mapping": { "line": "#/components/schemas/LineChartConfig", "stacked_bar": "#/components/schemas/BarChartConfig", + "stacked_line": "#/components/schemas/StackedLineChartConfig", "table": "#/components/schemas/TableChartConfig", "number": "#/components/schemas/NumberChartConfig", "pie": "#/components/schemas/PieChartConfig", diff --git a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts index 1eea009b2d..bf5d34f0ec 100644 --- a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts @@ -1006,6 +1006,10 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { numberFormat, seriesLimit: 3, }; + const stackedLineConfig = { + ...barConfig, + displayType: 'stacked_line' as const, + }; const tableConfig = { displayType: 'table' as const, sourceId, @@ -1053,6 +1057,7 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { const tiles = [ { name: 'Line', config: lineConfig }, { name: 'Bar', config: barConfig }, + { name: 'Stacked Line', config: stackedLineConfig }, { name: 'Table', config: tableConfig }, { name: 'Pie', config: pieConfig }, { name: 'Categorical Bar', config: categoricalBarConfig }, @@ -1061,6 +1066,7 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { const configByName: Record = { Line: lineConfig, Bar: barConfig, + 'Stacked Line': stackedLineConfig, Table: tableConfig, Pie: pieConfig, 'Categorical Bar': categoricalBarConfig, diff --git a/packages/api/src/mcp/__tests__/dashboards/validation.test.ts b/packages/api/src/mcp/__tests__/dashboards/validation.test.ts index 9532585409..f240bf13b5 100644 --- a/packages/api/src/mcp/__tests__/dashboards/validation.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/validation.test.ts @@ -80,6 +80,7 @@ describe('tile-level where rejection (builder tiles)', () => { const builderTypes = [ { displayType: 'line' }, { displayType: 'stacked_bar' }, + { displayType: 'stacked_line' }, { displayType: 'table', extra: { groupBy: 'SpanName' } }, { displayType: 'number' }, { displayType: 'pie', extra: { groupBy: 'SpanName' } }, @@ -384,6 +385,13 @@ describe('getRawSqlTileMacroHints', () => { 'SELECT $__timeInterval(Timestamp) AS ts, count() FROM $__sourceTable ' + 'WHERE $__timeFilter(Timestamp) AND $__filters GROUP BY ts', }), + makeSqlTile({ + displayType: 'stacked_line', + sourceId, + sqlTemplate: + 'SELECT $__timeInterval(Timestamp) AS ts, count() FROM $__sourceTable ' + + 'WHERE $__timeFilter(Timestamp) AND $__filters GROUP BY ts', + }), ]), ).toEqual([]); }); diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index 11a3130762..a35dfff614 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -57,6 +57,7 @@ Recommended pattern: Use BUILDER tiles (with sourceId) for most cases: line Time-series trends (error rate, request volume, latency over time). stacked_bar Compare categories over time (requests by service, errors by status code). + stacked_line Same as stacked_bar but as filled area bands (smooth cumulative totals). number Single KPI metric (total requests, current error rate, p99 latency). table Ranked lists (top endpoints by latency, error counts by service). Tables can wire row-click navigation via config.onClick to the /search page or another dashboard. See "TABLE TILE LINKING" below. pie Proportional breakdowns (traffic share by service, errors by type). Keep slice count under 8. @@ -67,7 +68,7 @@ Use BUILDER tiles (with sourceId) for most cases: markdown Use sparingly. The dashboard already shows its name in the title bar at the top; do NOT add a "About this dashboard" tile that repeats it. Markdown bodies render h1/h2/h3 headings at title-bar scale, so a single \`## Service Catalog\` line eats most of the tile and pushes real KPIs below the fold. Skip markdown tiles for starter dashboards. If you must add one, size it to fit the text (h: 2-3 for a line or two; h: 1 clips it), use plain prose, no \`#\`/\`##\`/\`###\` headings. Use containers/tabs for section grouping instead. Use RAW SQL tiles (with connectionId) only for queries the builder cannot express: - Requires configType: "sql" plus a displayType (line, stacked_bar, table, number, pie, bar). + Requires configType: "sql" plus a displayType (line, stacked_bar, stacked_line, table, number, pie, bar). Use when you need JOINs, sub-queries, CTEs, or expressions the builder does not generate. ALWAYS set sourceId on a raw SQL tile (in addition to connectionId) UNLESS the query reads from multiple tables (e.g. JOINs across sources). sourceId enables the $__filters and diff --git a/packages/api/src/mcp/tools/alerts/schemas.ts b/packages/api/src/mcp/tools/alerts/schemas.ts index a1258ff50b..d218390b08 100644 --- a/packages/api/src/mcp/tools/alerts/schemas.ts +++ b/packages/api/src/mcp/tools/alerts/schemas.ts @@ -15,6 +15,7 @@ import { mcpLineTileSchema, mcpNumberTileSchema, mcpSqlTileSchema, + mcpStackedLineTileSchema, } from '@/mcp/tools/dashboards/schemas'; // --------------------------------------------------------------------------- @@ -28,7 +29,8 @@ import { // Inline alerts carry their chart config in the same dialect as dashboard // tile configs, restricted to the display types the alert evaluator can run -// as a time series: line, stacked_bar, and number (builder or raw SQL). +// as a time series: line, stacked_bar, stacked_line, and number (builder or +// raw SQL). // Reuses the dashboard tile config shapes so agents author both from one // vocabulary; the raw SQL variant narrows displayType and drops the // tile-only onClick affordance. Full validation (formulas, number @@ -78,6 +80,11 @@ const mcpAlertChartConfigSchema = z where: mcpAlertChartLevelWhereSchema, whereLanguage: SearchConditionTrimmedLanguageSchema.optional(), }), + mcpStackedLineTileSchema.shape.config.extend({ + name: mcpAlertChartConfigNameSchema, + where: mcpAlertChartLevelWhereSchema, + whereLanguage: SearchConditionTrimmedLanguageSchema.optional(), + }), mcpNumberTileSchema.shape.config.extend({ name: mcpAlertChartConfigNameSchema, where: mcpAlertChartLevelWhereSchema, @@ -88,16 +95,16 @@ const mcpAlertChartConfigSchema = z where: rejectedRawSqlAlertWhereField, whereLanguage: rejectedRawSqlAlertWhereField, displayType: z - .enum(['line', 'stacked_bar', 'number']) + .enum(['line', 'stacked_bar', 'stacked_line', 'number']) .describe( - 'How to render the SQL results. Alerts evaluate line, stacked_bar, or number charts only.', + 'How to render the SQL results. Alerts evaluate line, stacked_bar, stacked_line, or number charts only.', ), }), ]) .describe( 'Chart configuration for inline alerts (required when source is "inline"). ' + 'Same shape as a dashboard tile config, limited to displayType line, ' + - 'stacked_bar, or number. Omit configType for the builder variant ' + + 'stacked_bar, stacked_line, or number. Omit configType for the builder variant ' + '(sourceId + select); set configType to "sql" for the Raw SQL variant ' + '(connectionId + sqlTemplate; the template must use the $__timeFilter ' + 'and $__timeInterval macros so each evaluation window can be queried).', diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index 5c3a211e9e..b0a2063e7a 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -710,24 +710,38 @@ export const mcpLineTileSchema = mcpTileLayoutSchema.extend({ }), }); +const mcpStackedTimeChartConfigFields = { + sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + select: z.array(mcpTileSelectItemSchema).min(1).max(20), + groupBy: z.string().optional(), + fillNulls: z.boolean().optional().default(true), + alignDateRangeToGranularity: z.boolean().optional(), + asRatio: z.boolean().optional(), + numberFormat: mcpNumberFormatSchema + .optional() + .describe(tileLevelNumberFormatDescription), + seriesLimit: seriesLimitSchema.describe(timeChartSeriesLimitDescription), + formulas: mcpTileFormulasSchema, + showOperandSeries: mcpShowOperandSeriesSchema, +}; + export const mcpBarTileSchema = mcpTileLayoutSchema.extend({ config: z.object({ ...rejectedTileWhereFields, displayType: z .literal('stacked_bar') .describe('Stacked bar chart over time'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), - select: z.array(mcpTileSelectItemSchema).min(1).max(20), - groupBy: z.string().optional(), - fillNulls: z.boolean().optional().default(true), - alignDateRangeToGranularity: z.boolean().optional(), - asRatio: z.boolean().optional(), - numberFormat: mcpNumberFormatSchema - .optional() - .describe(tileLevelNumberFormatDescription), - seriesLimit: seriesLimitSchema.describe(timeChartSeriesLimitDescription), - formulas: mcpTileFormulasSchema, - showOperandSeries: mcpShowOperandSeriesSchema, + ...mcpStackedTimeChartConfigFields, + }), +}); + +export const mcpStackedLineTileSchema = mcpTileLayoutSchema.extend({ + config: z.object({ + ...rejectedTileWhereFields, + displayType: z + .literal('stacked_line') + .describe('Stacked line (area) chart over time'), + ...mcpStackedTimeChartConfigFields, }), }); @@ -1075,7 +1089,15 @@ export const mcpSqlTileSchema = mcpTileLayoutSchema.extend({ 'ADVANCED: Only use raw SQL tiles when the builder tile types cannot express the query you need.', ), displayType: z - .enum(['line', 'stacked_bar', 'table', 'number', 'pie', 'bar']) + .enum([ + 'line', + 'stacked_bar', + 'stacked_line', + 'table', + 'number', + 'pie', + 'bar', + ]) .describe('How to render the SQL results'), connectionId: z .string() @@ -1154,6 +1176,7 @@ GROUP BY ServiceName, ts const mcpTileSchema = z.union([ mcpLineTileSchema, mcpBarTileSchema, + mcpStackedLineTileSchema, mcpTableTileSchema, mcpNumberTileSchema, mcpPieTileSchema, @@ -1189,6 +1212,9 @@ const mcpPatchTileLayoutSchema = z.object({ const mcpPatchTileSchema = z.union([ mcpPatchTileLayoutSchema.extend({ config: mcpLineTileSchema.shape.config }), mcpPatchTileLayoutSchema.extend({ config: mcpBarTileSchema.shape.config }), + mcpPatchTileLayoutSchema.extend({ + config: mcpStackedLineTileSchema.shape.config, + }), mcpPatchTileLayoutSchema.extend({ config: mcpTableTileSchema.shape.config }), mcpPatchTileLayoutSchema.extend({ config: mcpNumberTileSchema.shape.config, diff --git a/packages/api/src/mcp/tools/dashboards/validation.ts b/packages/api/src/mcp/tools/dashboards/validation.ts index 7d2eb818e7..b8d3274e72 100644 --- a/packages/api/src/mcp/tools/dashboards/validation.ts +++ b/packages/api/src/mcp/tools/dashboards/validation.ts @@ -1,3 +1,4 @@ +import { TIME_SERIES_DISPLAY_TYPE_BY_NAME } from '@hyperdx/common-utils/dist/core/utils'; import type { FilterForVariableDeclaration } from '@hyperdx/common-utils/dist/filters'; import { getDashboardVariableDeclarations, @@ -89,9 +90,6 @@ export function getRawSqlMissingSourceError( ); } -/** Raw SQL display types that plot a value over time. */ -const TIME_SERIES_DISPLAY_TYPES = ['line', 'stacked_bar']; - /** * Returns one advisory string per raw SQL tile that omits a strongly * recommended macro: @@ -121,7 +119,7 @@ export function getRawSqlTileMacroWarnings( ); } if ( - TIME_SERIES_DISPLAY_TYPES.includes(displayType) && + displayType in TIME_SERIES_DISPLAY_TYPE_BY_NAME && !INTERVAL_MACROS.some(macro => hasMacro(sqlTemplate, macro)) ) { missing.push( diff --git a/packages/api/src/mcp/tools/query/helpers.ts b/packages/api/src/mcp/tools/query/helpers.ts index 4848539693..513b0c576a 100644 --- a/packages/api/src/mcp/tools/query/helpers.ts +++ b/packages/api/src/mcp/tools/query/helpers.ts @@ -7,6 +7,7 @@ import { getMetadata } from '@hyperdx/common-utils/dist/core/metadata'; import { convertToCategoricalChartConfig, getFirstTimestampValueExpression, + isTimeSeriesDisplayType, splitAndTrimWithBracket, } from '@hyperdx/common-utils/dist/core/utils'; import { isBuilderSavedChartConfig } from '@hyperdx/common-utils/dist/guards'; @@ -562,9 +563,7 @@ export async function runConfigTile( getHeatmapMode(builderConfig) === 'series'; const granularityOverride = !isSearch && - (builderConfig.displayType === DisplayType.Line || - builderConfig.displayType === DisplayType.StackedBar || - isSeriesHeatmap) + (isTimeSeriesDisplayType(builderConfig.displayType) || isSeriesHeatmap) ? { granularity: options?.granularity ?? 'auto' } : {}; diff --git a/packages/api/src/mcp/tools/query/timeseries.ts b/packages/api/src/mcp/tools/query/timeseries.ts index 264b178ae5..f0b46b26fa 100644 --- a/packages/api/src/mcp/tools/query/timeseries.ts +++ b/packages/api/src/mcp/tools/query/timeseries.ts @@ -41,11 +41,11 @@ const timeseriesSchema = z.object({ 'Example: [{ aggFn: "count" }, { aggFn: "avg", valueExpression: "Duration" }]', ), shape: z - .enum(['line', 'stacked_bar']) + .enum(['line', 'stacked_bar', 'stacked_line']) .optional() .default('line') .describe( - 'Chart shape. "line" for line chart (default), "stacked_bar" for stacked bar chart.', + 'Chart shape. "line" for line chart (default), "stacked_bar" for stacked bar chart, "stacked_line" for stacked line (area) chart.', ), where: whereSchema.describe( 'Row filter applied to ALL select items. ' + diff --git a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts index 5e507a733e..59f5e2625c 100644 --- a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts @@ -2718,6 +2718,63 @@ describe('External API v2 Dashboards - new format', () => { expect(getResponse.body.data.tiles[1].config.seriesLimit).toBe(7); }); + it('round-trips a stacked_line builder tile through create and get', async () => { + const stackedLineChart: ExternalDashboardTile = { + name: 'Stacked line', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + displayType: 'stacked_line', + sourceId: traceSource._id.toString(), + select: [ + { + aggFn: 'count', + alias: 'Count', + where: '', + whereLanguage: 'sql', + }, + ], + groupBy: 'ServiceName', + seriesLimit: 5, + }, + }; + + const createResponse = await authRequest('post', BASE_URL) + .send({ + name: 'Dashboard with a stacked line tile', + tiles: [stackedLineChart], + }) + .expect(200); + + expect(createResponse.body.data.tiles[0].config.displayType).toBe( + 'stacked_line', + ); + + const { id } = createResponse.body.data; + const getResponse = await authRequest('get', `${BASE_URL}/${id}`).expect( + 200, + ); + expect(omit(getResponse.body.data.tiles[0], ['id'])).toEqual({ + ...stackedLineChart, + config: { + ...stackedLineChart.config, + asRatio: false, + fillNulls: true, + select: [ + { + aggFn: 'count', + alias: 'Count', + valueExpression: '', + where: '', + whereLanguage: 'sql', + }, + ], + }, + }); + }); + it('omits seriesLimit on line/stacked_bar tiles when it is not provided', async () => { const lineChart: ExternalDashboardTile = { name: 'Line without series limit', @@ -3396,6 +3453,24 @@ describe('External API v2 Dashboards - new format', () => { }, }; + const stackedLineRawSql: ExternalDashboardTile = { + name: 'Stacked Line Raw SQL', + x: 12, + y: 0, + w: 6, + h: 3, + config: { + configType: 'sql', + displayType: 'stacked_line', + connectionId, + sqlTemplate, + sourceId, + fillNulls: false, + alignDateRangeToGranularity: false, + numberFormat: { output: 'byte', decimalBytes: true }, + }, + }; + const tableRawSql: ExternalDashboardTile = { name: 'Table Raw SQL', x: 0, @@ -3475,6 +3550,7 @@ describe('External API v2 Dashboards - new format', () => { tiles: [ lineRawSql, barRawSql, + stackedLineRawSql, tableRawSql, numberRawSql, pieRawSql, @@ -3486,10 +3562,13 @@ describe('External API v2 Dashboards - new format', () => { expect(omit(response.body.data.tiles[0], ['id'])).toEqual(lineRawSql); expect(omit(response.body.data.tiles[1], ['id'])).toEqual(barRawSql); - expect(omit(response.body.data.tiles[2], ['id'])).toEqual(tableRawSql); - expect(omit(response.body.data.tiles[3], ['id'])).toEqual(numberRawSql); - expect(omit(response.body.data.tiles[4], ['id'])).toEqual(pieRawSql); - expect(omit(response.body.data.tiles[5], ['id'])).toEqual( + expect(omit(response.body.data.tiles[2], ['id'])).toEqual( + stackedLineRawSql, + ); + expect(omit(response.body.data.tiles[3], ['id'])).toEqual(tableRawSql); + expect(omit(response.body.data.tiles[4], ['id'])).toEqual(numberRawSql); + expect(omit(response.body.data.tiles[5], ['id'])).toEqual(pieRawSql); + expect(omit(response.body.data.tiles[6], ['id'])).toEqual( categoricalBarRawSql, ); }); diff --git a/packages/api/src/routers/external-api/v2/alerts.ts b/packages/api/src/routers/external-api/v2/alerts.ts index 5b42f81f2a..7a23df9d1a 100644 --- a/packages/api/src/routers/external-api/v2/alerts.ts +++ b/packages/api/src/routers/external-api/v2/alerts.ts @@ -110,6 +110,10 @@ function toInternalAlertInput(body: ExternalAlertInput): InternalAlertInput { * allOf: * - $ref: '#/components/schemas/BarChartConfig' * - $ref: '#/components/schemas/AlertChartConfigOverlay' + * AlertStackedLineChartConfig: + * allOf: + * - $ref: '#/components/schemas/StackedLineChartConfig' + * - $ref: '#/components/schemas/AlertChartConfigOverlay' * AlertNumberChartConfig: * allOf: * - $ref: '#/components/schemas/NumberChartConfig' @@ -119,14 +123,15 @@ function toInternalAlertInput(body: ExternalAlertInput): InternalAlertInput { * The chart configuration an inline alert evaluates, in the same * dialect as dashboard tile configs plus the alert-only fields in * AlertChartConfigOverlay. Only the display types the alert evaluator - * supports are accepted: line, stacked_bar, and number, in both - * builder and Raw SQL (configType "sql") variants. Raw SQL templates - * must reference the evaluation window via the time-filter and - * interval macros (e.g. $__timeFilter and $__timeInterval), and the + * supports are accepted: line, stacked_bar, stacked_line, and number, + * in both builder and Raw SQL (configType "sql") variants. Raw SQL + * templates must reference the evaluation window via the time-filter + * and interval macros (e.g. $__timeFilter and $__timeInterval), and the * referenced source/connection must belong to the team. * oneOf: * - $ref: '#/components/schemas/AlertLineChartConfig' * - $ref: '#/components/schemas/AlertBarChartConfig' + * - $ref: '#/components/schemas/AlertStackedLineChartConfig' * - $ref: '#/components/schemas/AlertNumberChartConfig' * AlertState: * type: string diff --git a/packages/api/src/routers/external-api/v2/dashboards.ts b/packages/api/src/routers/external-api/v2/dashboards.ts index 14f1e85741..01f40b632a 100644 --- a/packages/api/src/routers/external-api/v2/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/dashboards.ts @@ -108,7 +108,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * description: Metric data type, only for metrics data sources. * TimeSeriesDisplayType: * type: string - * enum: [stacked_bar, line] + * enum: [stacked_bar, stacked_line, line] * description: Visual representation type for the time series. * QuantileLevel: * type: number @@ -791,6 +791,76 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * series are returned; the raw operand series are hidden. * default: true * + * StackedLineBuilderChartConfig: + * type: object + * required: + * - displayType + * - sourceId + * - select + * description: Builder configuration for a stacked-line time-series chart. + * properties: + * displayType: + * type: string + * enum: [stacked_line] + * description: Display type discriminator. Must be "stacked_line" for stacked-line charts. + * example: "stacked_line" + * sourceId: + * type: string + * description: ID of the data source to query. + * example: "65f5e4a3b9e77c001a111111" + * select: + * type: array + * minItems: 1 + * maxItems: 20 + * description: > + * One or more aggregated values to plot. When asRatio is true, + * exactly two select items are required. + * items: + * $ref: '#/components/schemas/SelectItem' + * groupBy: + * type: string + * description: Field expression to group results by (creates separate stacked bands per group value). + * example: "service" + * maxLength: 10000 + * asRatio: + * type: boolean + * description: Plot select[0] / select[1] as a ratio. Requires exactly two select items. + * default: false + * alignDateRangeToGranularity: + * type: boolean + * description: Align the date range boundaries to the query granularity interval. + * default: true + * fillNulls: + * type: boolean + * description: Fill missing time buckets with zero instead of leaving gaps. + * default: true + * numberFormat: + * $ref: '#/components/schemas/NumberFormat' + * description: Number formatting options for displayed values. + * seriesLimit: + * type: integer + * minimum: 0 + * description: >- + * Maximum number of series rendered (top-N by value). Omit to use + * the default render cap, set 0 for unlimited, or a positive N to + * keep the top N series. + * example: 5 + * formulas: + * type: array + * maxItems: 10 + * description: > + * Derived series computed from the select items via letter-ref + * arithmetic ("A" = select[0], "B" = select[1], ...). Metric, + * log, and trace sources only. Cannot be combined with asRatio. + * items: + * $ref: '#/components/schemas/Formula' + * showOperandSeries: + * type: boolean + * description: > + * Only meaningful with formulas. When false, only the formula + * series are returned; the raw operand series are hidden. + * default: true + * * TableBuilderChartConfig: * type: object * required: @@ -1327,6 +1397,28 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * description: Expand date range boundaries to the query granularity interval. * default: true * + * StackedLineRawSqlChartConfig: + * description: Raw SQL configuration for a stacked-line time-series chart. + * allOf: + * - $ref: '#/components/schemas/RawSqlChartConfigBase' + * - type: object + * required: + * - displayType + * properties: + * displayType: + * type: string + * enum: [stacked_line] + * description: Display as a stacked-line time-series chart. + * example: "stacked_line" + * fillNulls: + * type: boolean + * description: Fill missing time buckets with zero instead of leaving gaps. + * default: true + * alignDateRangeToGranularity: + * type: boolean + * description: Expand date range boundaries to the query granularity interval. + * default: true + * * TableRawSqlChartConfig: * description: Raw SQL configuration for a table chart. * allOf: @@ -1424,6 +1516,19 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * mapping: * sql: '#/components/schemas/BarRawSqlChartConfig' * + * StackedLineChartConfig: + * description: > + * Stacked-line chart. Omit configType for the builder variant (requires + * sourceId and select). Set configType to "sql" for the Raw SQL variant + * (requires connectionId and sqlTemplate). + * oneOf: + * - $ref: '#/components/schemas/StackedLineBuilderChartConfig' + * - $ref: '#/components/schemas/StackedLineRawSqlChartConfig' + * discriminator: + * propertyName: configType + * mapping: + * sql: '#/components/schemas/StackedLineRawSqlChartConfig' + * * OnClickFilterTemplate: * type: object * description: > @@ -1634,13 +1739,14 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * description: > * Tile chart configuration. displayType is the primary discriminant and * determines which variant group applies. For displayTypes that support - * both builder and Raw SQL modes (line, stacked_bar, table, number, pie, - * bar), configType is the secondary discriminant: omit it for the builder - * variant or set it to "sql" for the Raw SQL variant. The heatmap, + * both builder and Raw SQL modes (line, stacked_bar, stacked_line, table, + * number, pie, bar), configType is the secondary discriminant: omit it for + * the builder variant or set it to "sql" for the Raw SQL variant. The heatmap, * search, event_patterns, and markdown displayTypes only have a builder variant. * oneOf: * - $ref: '#/components/schemas/LineChartConfig' * - $ref: '#/components/schemas/BarChartConfig' + * - $ref: '#/components/schemas/StackedLineChartConfig' * - $ref: '#/components/schemas/TableChartConfig' * - $ref: '#/components/schemas/NumberChartConfig' * - $ref: '#/components/schemas/PieChartConfig' @@ -1654,6 +1760,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * mapping: * line: '#/components/schemas/LineChartConfig' * stacked_bar: '#/components/schemas/BarChartConfig' + * stacked_line: '#/components/schemas/StackedLineChartConfig' * table: '#/components/schemas/TableChartConfig' * number: '#/components/schemas/NumberChartConfig' * pie: '#/components/schemas/PieChartConfig' diff --git a/packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts b/packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts index c4da87435f..0760ea36b8 100644 --- a/packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts +++ b/packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts @@ -247,6 +247,24 @@ describe('external <-> internal round-trip', () => { }); }); + it('round-trips a stacked_line alert chart config', () => { + const external: ExternalAlertChartConfig = { + displayType: DisplayType.StackedLine, + sourceId: SOURCE_ID, + groupBy: 'ServiceName', + seriesLimit: 5, + asRatio: false, + fillNulls: true, + select: [countItem()], + }; + + const roundTripped = convertAlertChartConfigToExternal( + convertExternalAlertChartConfigToInternal(external), + ); + + expect(roundTripped).toEqual(external); + }); + it('round-trips a raw SQL config', () => { const external = { configType: 'sql' as const, diff --git a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts index 3306ab728d..259a4a8313 100644 --- a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts +++ b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts @@ -407,47 +407,46 @@ describe('convertToExternalDashboard orphan-ref heal', () => { // default cap, 0 = unlimited, positive N = top-N. All three must survive a // GET->PUT round-trip: 0 and N pass through, null maps to absent (the // default-cap state). - describe.each([DisplayType.Line, DisplayType.StackedBar])( - 'seriesLimit serialization for %s tiles', - displayType => { - function readSeriesLimit(seriesLimit: number | null): unknown { - const doc = makeDoc({ - tiles: [ - makeTile({ - id: 'series-limit-tile', - config: { - displayType, - source: new mongoose.Types.ObjectId().toString(), - name: 'Series limit tile', - select: [{ aggFn: 'count', valueExpression: '' }], - where: '', - seriesLimit, - }, - }), - ], - }); - // Round-trip through JSON to observe what the wire body actually - // carries: `undefined` fields are dropped, so an omitted seriesLimit - // reads back as `undefined` here. - const wire = JSON.parse( - JSON.stringify(convertToExternalDashboard(doc)), - ); - return wire.tiles[0].config.seriesLimit; - } - - it('round-trips 0 (unlimited) rather than dropping it', () => { - expect(readSeriesLimit(0)).toBe(0); + describe.each([ + DisplayType.Line, + DisplayType.StackedBar, + DisplayType.StackedLine, + ])('seriesLimit serialization for %s tiles', displayType => { + function readSeriesLimit(seriesLimit: number | null): unknown { + const doc = makeDoc({ + tiles: [ + makeTile({ + id: 'series-limit-tile', + config: { + displayType, + source: new mongoose.Types.ObjectId().toString(), + name: 'Series limit tile', + select: [{ aggFn: 'count', valueExpression: '' }], + where: '', + seriesLimit, + }, + }), + ], }); + // Round-trip through JSON to observe what the wire body actually + // carries: `undefined` fields are dropped, so an omitted seriesLimit + // reads back as `undefined` here. + const wire = JSON.parse(JSON.stringify(convertToExternalDashboard(doc))); + return wire.tiles[0].config.seriesLimit; + } - it('emits seriesLimit as absent when stored as null (default cap)', () => { - expect(readSeriesLimit(null)).toBeUndefined(); - }); + it('round-trips 0 (unlimited) rather than dropping it', () => { + expect(readSeriesLimit(0)).toBe(0); + }); - it('passes a positive seriesLimit through unchanged', () => { - expect(readSeriesLimit(25)).toBe(25); - }); - }, - ); + it('emits seriesLimit as absent when stored as null (default cap)', () => { + expect(readSeriesLimit(null)).toBeUndefined(); + }); + + it('passes a positive seriesLimit through unchanged', () => { + expect(readSeriesLimit(25)).toBe(25); + }); + }); }); describe('convertToExternalDashboard stale aggregation params', () => { diff --git a/packages/api/src/routers/external-api/v2/utils/alertChartConfig.ts b/packages/api/src/routers/external-api/v2/utils/alertChartConfig.ts index a2f660a675..ee794963da 100644 --- a/packages/api/src/routers/external-api/v2/utils/alertChartConfig.ts +++ b/packages/api/src/routers/external-api/v2/utils/alertChartConfig.ts @@ -74,6 +74,7 @@ export function convertExternalAlertChartConfigToInternal( const EXTERNAL_ALERT_DISPLAY_TYPES = [ DisplayType.Line, DisplayType.StackedBar, + DisplayType.StackedLine, DisplayType.Number, ] as const; @@ -162,8 +163,8 @@ const REPRESENTABLE_SELECT_ITEM_KEYS: ReadonlySet = new Set([ ]); /** - * Select-item fields that are inert on line/stacked_bar/number charts - * (heatmap- or table-cell-only affordances) and may be dropped. + * Select-item fields that are inert on line/stacked_bar/stacked_line/number + * charts (heatmap- or table-cell-only affordances) and may be dropped. */ const EVALUATION_INERT_SELECT_ITEM_KEYS: ReadonlySet = new Set([ 'color', @@ -341,6 +342,7 @@ export function convertAlertChartConfigToExternal( switch (external?.displayType) { case DisplayType.Line: case DisplayType.StackedBar: + case DisplayType.StackedLine: case DisplayType.Number: { const name = config.name ? { name: config.name } : {}; const candidate = diff --git a/packages/api/src/routers/external-api/v2/utils/dashboards.ts b/packages/api/src/routers/external-api/v2/utils/dashboards.ts index 56a894efec..c535ae9a69 100644 --- a/packages/api/src/routers/external-api/v2/utils/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/utils/dashboards.ts @@ -3,6 +3,7 @@ import { displayTypeSupportsBuilderAlerts, displayTypeSupportsRawSqlAlerts, isFormulaSourceKind, + TIME_SERIES_DISPLAY_TYPE_BY_NAME, } from '@hyperdx/common-utils/dist/core/utils'; import { validateDashboardContainersStructure, @@ -244,9 +245,9 @@ export const convertToExternalTileChartConfig = ( seriesLimit: config.seriesLimit ?? undefined, }; case DisplayType.StackedBar: - return { - configType: 'sql', - displayType: config.displayType, + case DisplayType.StackedLine: { + const stacked = { + configType: 'sql' as const, connectionId: config.connection, sqlTemplate: config.sqlTemplate, sourceId: config.source, @@ -257,6 +258,11 @@ export const convertToExternalTileChartConfig = ( // null/undefined map to absent (the default-cap state). seriesLimit: config.seriesLimit ?? undefined, }; + // A union-typed displayType doesn't narrow to one union member. + return config.displayType === DisplayType.StackedLine + ? { displayType: DisplayType.StackedLine, ...stacked } + : { displayType: DisplayType.StackedBar, ...stacked }; + } case DisplayType.Table: return { configType: 'sql', @@ -362,8 +368,8 @@ export const convertToExternalTileChartConfig = ( ...externalShowOperandSeriesField, }; case DisplayType.StackedBar: - return { - displayType: DisplayType.StackedBar, + case DisplayType.StackedLine: { + const stacked = { sourceId, asRatio: config.seriesReturnType === 'ratio' && @@ -382,6 +388,10 @@ export const convertToExternalTileChartConfig = ( ...externalFormulaFields, ...externalShowOperandSeriesField, }; + return config.displayType === DisplayType.StackedLine + ? { displayType: DisplayType.StackedLine, ...stacked } + : { displayType: DisplayType.StackedBar, ...stacked }; + } case DisplayType.Number: return { displayType: config.displayType, @@ -723,6 +733,7 @@ export function convertToInternalTileConfig( switch (externalConfig.displayType) { case 'line': case 'stacked_bar': + case 'stacked_line': internalConfig = { configType: 'sql', ...pick(externalConfig, [ @@ -734,9 +745,7 @@ export function convertToInternalTileConfig( 'seriesLimit', ]), displayType: - externalConfig.displayType === 'stacked_bar' - ? DisplayType.StackedBar - : DisplayType.Line, + TIME_SERIES_DISPLAY_TYPE_BY_NAME[externalConfig.displayType], fillNulls: externalConfig.fillNulls === false ? false : undefined, name, connection: externalConfig.connectionId, @@ -789,6 +798,7 @@ export function convertToInternalTileConfig( switch (externalConfig.displayType) { case 'line': case 'stacked_bar': + case 'stacked_line': internalConfig = { ...pick(externalConfig, [ 'groupBy', @@ -802,9 +812,7 @@ export function convertToInternalTileConfig( 'showOperandSeries', ]), displayType: - externalConfig.displayType === 'stacked_bar' - ? DisplayType.StackedBar - : DisplayType.Line, + TIME_SERIES_DISPLAY_TYPE_BY_NAME[externalConfig.displayType], select: externalConfig.select.map(convertToInternalSelectItem), source: externalConfig.sourceId, where: '', diff --git a/packages/api/src/tasks/checkAlerts/index.ts b/packages/api/src/tasks/checkAlerts/index.ts index 73e8cace9a..1b481f789d 100644 --- a/packages/api/src/tasks/checkAlerts/index.ts +++ b/packages/api/src/tasks/checkAlerts/index.ts @@ -24,6 +24,7 @@ import { } from '@hyperdx/common-utils/dist/core/searchChartConfig'; import { aliasMapToWithClauses, + displayTypeSupportsBuilderAlerts, displayTypeSupportsRawSqlAlerts, isTimeSeriesDisplayType, } from '@hyperdx/common-utils/dist/core/utils'; @@ -731,11 +732,7 @@ const buildAlertChartConfigFromSavedConfig = ({ return undefined; } - if ( - savedConfig.displayType === DisplayType.Line || - savedConfig.displayType === DisplayType.StackedBar || - savedConfig.displayType === DisplayType.Number - ) { + if (displayTypeSupportsBuilderAlerts(savedConfig.displayType)) { // Alerts can use Log, Trace, or Metric sources. // implicitColumnExpression+useTextIndexForImplicitColumn exist on Log and Trace sources; // metricTables exists on Metric sources. diff --git a/packages/api/src/utils/externalApi.ts b/packages/api/src/utils/externalApi.ts index 79de4ec472..be0b3e0d1b 100644 --- a/packages/api/src/utils/externalApi.ts +++ b/packages/api/src/utils/externalApi.ts @@ -1,3 +1,4 @@ +import { TIME_SERIES_DISPLAY_TYPE_BY_NAME } from '@hyperdx/common-utils/dist/core/utils'; import { isFilterBroadcastEnabled, isFilterRequired, @@ -74,9 +75,9 @@ export function translateExternalChartToTileConfig( switch (firstSeries.type) { case 'time': { displayType = - firstSeries.displayType === 'stacked_bar' - ? DisplayType.StackedBar - : DisplayType.Line; + (firstSeries.displayType && + TIME_SERIES_DISPLAY_TYPE_BY_NAME[firstSeries.displayType]) ?? + DisplayType.Line; // Convert time series to select array select = series.map(s => { diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index c3dd169e8d..c126dfb313 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -77,7 +77,11 @@ const timeChartSeriesSchema = z.object({ metricDataType: z.optional(z.nativeEnum(MetricsDataType)), metricName: z.string().optional(), displayType: z - .union([z.literal('stacked_bar'), z.literal('line')]) + .union([ + z.literal('stacked_bar'), + z.literal('stacked_line'), + z.literal('line'), + ]) .optional(), }); @@ -390,6 +394,16 @@ const externalDashboardBarRawSqlChartConfigSchema = seriesLimit: z.number().int().nonnegative().optional(), }); +const externalDashboardStackedLineChartConfigSchema = + externalDashboardBarChartConfigSchema.extend({ + displayType: z.literal('stacked_line'), + }); + +const externalDashboardStackedLineRawSqlChartConfigSchema = + externalDashboardBarRawSqlChartConfigSchema.extend({ + displayType: z.literal('stacked_line'), + }); + const externalDashboardTableChartConfigSchema = z.object({ displayType: z.literal('table'), sourceId: objectIdSchema, @@ -577,6 +591,7 @@ const externalDashboardBuilderTileConfigSchema = z.discriminatedUnion( [ externalDashboardLineChartConfigSchema, externalDashboardBarChartConfigSchema, + externalDashboardStackedLineChartConfigSchema, externalDashboardTableChartConfigSchema, externalDashboardNumberChartConfigSchema, externalDashboardPieChartConfigSchema, @@ -613,6 +628,7 @@ const externalDashboardRawSqlTileConfigSchema = z.discriminatedUnion( [ externalDashboardLineRawSqlChartConfigSchema, externalDashboardBarRawSqlChartConfigSchema, + externalDashboardStackedLineRawSqlChartConfigSchema, externalDashboardTableRawSqlChartConfigSchema, externalDashboardNumberRawSqlChartConfigSchema, externalDashboardPieRawSqlChartConfigSchema, @@ -944,6 +960,11 @@ export const externalAlertBuilderChartConfigSchema = z.discriminatedUnion( where: z.string().max(10000).optional(), whereLanguage: whereLanguageSchema, }), + externalDashboardStackedLineChartConfigSchema.extend({ + name: alertChartConfigNameSchema, + where: z.string().max(10000).optional(), + whereLanguage: whereLanguageSchema, + }), externalDashboardNumberChartConfigSchema.extend({ name: alertChartConfigNameSchema, where: z.string().max(10000).optional(), @@ -965,6 +986,11 @@ export const externalAlertRawSqlChartConfigSchema = z.discriminatedUnion( where: rejectedAlertRawSqlWhereField, whereLanguage: rejectedAlertRawSqlWhereField, }), + externalDashboardStackedLineRawSqlChartConfigSchema.extend({ + name: alertChartConfigNameSchema, + where: rejectedAlertRawSqlWhereField, + whereLanguage: rejectedAlertRawSqlWhereField, + }), externalDashboardNumberRawSqlChartConfigSchema.extend({ name: alertChartConfigNameSchema, where: rejectedAlertRawSqlWhereField, diff --git a/packages/app/src/ChartUtils.tsx b/packages/app/src/ChartUtils.tsx index 9868c778aa..6e41d4846c 100644 --- a/packages/app/src/ChartUtils.tsx +++ b/packages/app/src/ChartUtils.tsx @@ -25,6 +25,7 @@ import { getAlignedDateRange, Granularity, hasPositiveSeriesLimit, + TIME_SERIES_DISPLAY_TYPE_BY_NAME, } from '@hyperdx/common-utils/dist/core/utils'; import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; import { @@ -1166,7 +1167,7 @@ export const convertV1ChartConfigToV2 = ( granularity?: Granularity; dateRange: [Date, Date]; seriesReturnType: 'ratio' | 'column'; - displayType?: 'stacked_bar' | 'line'; + displayType?: 'stacked_bar' | 'stacked_line' | 'line'; name?: string; fillNulls?: number | false; sortOrder?: SortOrder; @@ -1190,8 +1191,7 @@ export const convertV1ChartConfigToV2 = ( } const firstSeries = series[0]; - const convertedDisplayType = - displayType === 'stacked_bar' ? DisplayType.StackedBar : DisplayType.Line; + const convertedDisplayType = TIME_SERIES_DISPLAY_TYPE_BY_NAME[displayType]; if (firstSeries.table === 'logs') { // TODO: this might not work properly since logs + traces are mixed in v1 diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx index 41e19d39b9..4f5f3c490a 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -1283,41 +1283,40 @@ const Tile = ({ ) : ( <> - {(effectiveQueriedConfig?.displayType === DisplayType.Line || - effectiveQueriedConfig?.displayType === - DisplayType.StackedBar) && ( - setFullscreenDateRange([start, end]) - : onTimeRangeSelect - } - setDisplayType={ - readOnly - ? undefined - : displayType => { - onUpdateChart?.({ - ...chart, - config: { - ...chart.config, - displayType, - }, - }); - } - } - /> - )} + {effectiveQueriedConfig && + isTimeSeriesDisplayType(effectiveQueriedConfig.displayType) && ( + setFullscreenDateRange([start, end]) + : onTimeRangeSelect + } + setDisplayType={ + readOnly + ? undefined + : displayType => { + onUpdateChart?.({ + ...chart, + config: { + ...chart.config, + displayType, + }, + }); + } + } + /> + )} {effectiveQueriedConfig?.displayType === DisplayType.Table && ( { + const isStackedLine = displayType === DisplayType.StackedLine; return visibleLineData.map(ld => { const key = ld.dataKey; const color = ld.color; @@ -1418,18 +1422,28 @@ export const MemoChart = memo(function MemoChart({ on hover. className={seriesClassName(id, key)} activeDot={} - // Fill is always the gradient. Hiding it on hover is a CSS class - // toggle (styles.chartHovered), not a prop swap — swapping it here + // Stacked bands get a flat fill; the gradient fades out within the + // top 10% of the chart, which leaves stacked bands looking like + // bare lines. Hiding the fill on hover is a CSS class toggle + // (styles.chartHovered), not a prop swap — swapping it here // re-created every on each hover enter/leave (hover churn). - fill={`url(#time-chart-lin-grad-${id}-${color?.replace('#', '').toLowerCase()})`} + fill={ + isStackedLine + ? color + : `url(#time-chart-lin-grad-${id}-${color?.replace('#', '').toLowerCase()})` + } strokeDasharray={strokeDasharray} name={seriesName} isAnimationActive={false} @@ -1956,6 +1970,11 @@ export const MemoChart = memo(function MemoChart({ )} // Scopes nearestSeriesStyle to this chart instance. data-chart-id={id} + // Stacked lines are read by their filled bands, so keep the fill on + // hover; the chartHovered fill-hiding rule opts out via this attribute. + data-stacked-fill={ + displayType === DisplayType.StackedLine ? 'true' : undefined + } style={{ position: 'relative', width: '100%', height: '100%' }} > {nearestSeriesStyle} diff --git a/packages/app/src/__tests__/HDXMultiSeriesTimeChart.test.ts b/packages/app/src/__tests__/HDXMultiSeriesTimeChart.test.ts index 32db9d90f2..2375405659 100644 --- a/packages/app/src/__tests__/HDXMultiSeriesTimeChart.test.ts +++ b/packages/app/src/__tests__/HDXMultiSeriesTimeChart.test.ts @@ -542,6 +542,23 @@ describe('computeYAxisBounds', () => { } }); + it('leaves a stacked line`s max to Recharts, selection or not', () => { + const lineData = [series('a'), series('b')]; + const graphResults = [{ a: 60, b: 40 }]; + for (const hasSelection of [false, true]) { + expect( + computeYAxisBounds( + graphResults, + lineData, + hasSelection, + false, + DisplayType.StackedLine, + [], + ), + ).toEqual({ domain: [0, 'auto'], ticks: undefined }); + } + }); + it('falls back to auto when there is no numeric data', () => { const bounds = computeYAxisBounds( [], diff --git a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx index 2f868cc124..6be88f101e 100644 --- a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx +++ b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx @@ -4,6 +4,7 @@ import { UnknownTemplateHelperError, validateTemplate, } from '@hyperdx/common-utils/dist/core/handlebarsEnv'; +import { isTimeSeriesDisplayType } from '@hyperdx/common-utils/dist/core/utils'; import { ChartConfigWithDateRange, DisplayType, @@ -200,8 +201,7 @@ export default function ChartDisplaySettingsDrawer({ ); }, [reset, defaultNumberFormat]); - const isTimeChart = - displayType === DisplayType.Line || displayType === DisplayType.StackedBar; + const isTimeChart = isTimeSeriesDisplayType(displayType); // Series Limit applies to every time chart. On builder group-by charts a // positive value drives the __hdx_series_limit SQL CTE (trimming what's diff --git a/packages/app/src/components/ChartEditor/constants.tsx b/packages/app/src/components/ChartEditor/constants.tsx index 73b3adcfd1..557bc99379 100644 --- a/packages/app/src/components/ChartEditor/constants.tsx +++ b/packages/app/src/components/ChartEditor/constants.tsx @@ -27,6 +27,7 @@ GROUP BY ServiceName;`; export const SQL_PLACEHOLDERS: Record = { [DisplayType.Line]: TIMESERIES_PLACEHOLDER_SQL, [DisplayType.StackedBar]: TIMESERIES_PLACEHOLDER_SQL, + [DisplayType.StackedLine]: TIMESERIES_PLACEHOLDER_SQL, [DisplayType.Table]: `SELECT count() FROM @@ -98,6 +99,7 @@ export const DISPLAY_TYPE_INSTRUCTIONS: Partial< > = { [DisplayType.Line]: TIMESERIES_INSTRUCTIONS, [DisplayType.StackedBar]: TIMESERIES_INSTRUCTIONS, + [DisplayType.StackedLine]: TIMESERIES_INSTRUCTIONS, [DisplayType.Pie]: ( <> diff --git a/packages/app/src/components/ChartEditor/utils.ts b/packages/app/src/components/ChartEditor/utils.ts index d0740b93c7..9d26e1e050 100644 --- a/packages/app/src/components/ChartEditor/utils.ts +++ b/packages/app/src/components/ChartEditor/utils.ts @@ -164,12 +164,14 @@ export const isRawSqlDisplayType = ( | DisplayType.Table | DisplayType.Line | DisplayType.StackedBar + | DisplayType.StackedLine | DisplayType.Pie | DisplayType.Bar | DisplayType.Number => displayType === DisplayType.Table || displayType === DisplayType.Line || displayType === DisplayType.StackedBar || + displayType === DisplayType.StackedLine || displayType === DisplayType.Pie || displayType === DisplayType.Bar || displayType === DisplayType.Number; @@ -185,21 +187,7 @@ export const isStringSelectDisplayType = ( displayType === DisplayType.Search || displayType === DisplayType.EventPatterns; -export const isPromqlDisplayType = ( - displayType: DisplayType | undefined, -): displayType is - | DisplayType.Table - | DisplayType.Line - | DisplayType.StackedBar - | DisplayType.Pie - | DisplayType.Bar - | DisplayType.Number => - displayType === DisplayType.Table || - displayType === DisplayType.Line || - displayType === DisplayType.StackedBar || - displayType === DisplayType.Pie || - displayType === DisplayType.Bar || - displayType === DisplayType.Number; +export const isPromqlDisplayType = isRawSqlDisplayType; const NON_PROMQL_SOURCE_KINDS = Object.values(SourceKind).filter( kind => kind !== SourceKind.Promql, diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx index 963f3c2df1..6e597d06ae 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx @@ -9,6 +9,7 @@ import { useWatch, } from 'react-hook-form'; import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; +import { displayTypeSupportsBuilderAlerts } from '@hyperdx/common-utils/dist/core/utils'; import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; import { ChartConfigWithOptTimestamp, @@ -498,9 +499,7 @@ export function ChartEditorControls({ checked={ratioMode === 'share_of_total'} /> )} - {(displayType === DisplayType.Line || - displayType === DisplayType.StackedBar || - displayType === DisplayType.Number) && + {displayTypeSupportsBuilderAlerts(displayType) && alertsEnabled && !alert && !IS_LOCAL_MODE && ( diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts b/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts index a71218d755..79ae683035 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts @@ -494,6 +494,8 @@ describe('displayTypeToActiveTab', () => { [DisplayType.Bar, 'bar'], [DisplayType.Number, 'number'], [DisplayType.Line, 'time'], + [DisplayType.StackedBar, 'time'], + [DisplayType.StackedLine, 'time'], ])('maps %s to %s', (displayType, expected) => { expect(displayTypeToActiveTab(displayType)).toBe(expected); }); diff --git a/packages/app/src/components/DBTimeChart.tsx b/packages/app/src/components/DBTimeChart.tsx index be4a8f1bb7..a25412777c 100644 --- a/packages/app/src/components/DBTimeChart.tsx +++ b/packages/app/src/components/DBTimeChart.tsx @@ -23,7 +23,11 @@ import { DisplayType, } from '@hyperdx/common-utils/dist/types'; import { Popover, Portal } from '@mantine/core'; -import { IconChartBar, IconChartLine } from '@tabler/icons-react'; +import { + IconChartAreaLine, + IconChartBar, + IconChartLine, +} from '@tabler/icons-react'; import api from '@/api'; import { @@ -930,17 +934,25 @@ function DBTimeChartComponent({ options={[ { value: DisplayType.Line, - label: 'Display as Line Chart', + label: 'Display as line chart', icon: , }, { value: DisplayType.StackedBar, label: config.compareToPreviousPeriod - ? 'Bar Chart Unavailable When Comparing to Previous Period' - : 'Display as Bar Chart', + ? 'Stacked bar chart unavailable when comparing to previous period' + : 'Display as stacked bar chart', icon: , disabled: config.compareToPreviousPeriod, }, + { + value: DisplayType.StackedLine, + label: config.compareToPreviousPeriod + ? 'Stacked line chart unavailable when comparing to previous period' + : 'Display as stacked line chart', + icon: , + disabled: config.compareToPreviousPeriod, + }, ]} />, ); diff --git a/packages/app/src/components/charts/DisplaySwitcher.tsx b/packages/app/src/components/charts/DisplaySwitcher.tsx index 7b59e58267..13b58c6954 100644 --- a/packages/app/src/components/charts/DisplaySwitcher.tsx +++ b/packages/app/src/components/charts/DisplaySwitcher.tsx @@ -29,6 +29,8 @@ function DisplaySwitcher({ 's fill prop (which // re-created every Area). `!important` beats recharts' inline fill. -.chartHovered :global(.recharts-area .recharts-area-area) { +.chartHovered:not([data-stacked-fill]) + :global(.recharts-area .recharts-area-area) { fill: none !important; } diff --git a/packages/app/tests/e2e/components/ChartEditorComponent.ts b/packages/app/tests/e2e/components/ChartEditorComponent.ts index c9532e0248..87cc7a271e 100644 --- a/packages/app/tests/e2e/components/ChartEditorComponent.ts +++ b/packages/app/tests/e2e/components/ChartEditorComponent.ts @@ -59,11 +59,13 @@ export class ChartEditorComponent { * Set chart type */ async setChartType(name: DisplayType) { - // Line and StackedBar share the "Time Series" tab, and EventPatterns' tab - // is labelled just "Patterns"; the rest match their tab label by name - // (case-insensitive substring). + // Line, StackedBar, and StackedLine share the "Time Series" tab, and + // EventPatterns' tab is labelled just "Patterns"; the rest match their tab + // label by name (case-insensitive substring). const tabName = - name === DisplayType.Line || name === DisplayType.StackedBar + name === DisplayType.Line || + name === DisplayType.StackedBar || + name === DisplayType.StackedLine ? 'Time Series' : name === DisplayType.EventPatterns ? 'Patterns' diff --git a/packages/app/tests/e2e/features/dashboard.spec.ts b/packages/app/tests/e2e/features/dashboard.spec.ts index 306c8efb9d..467879f9d8 100644 --- a/packages/app/tests/e2e/features/dashboard.spec.ts +++ b/packages/app/tests/e2e/features/dashboard.spec.ts @@ -124,6 +124,44 @@ test.describe('Dashboard', { tag: ['@dashboard'] }, () => { }); }); + test('persists a stacked line display type across a reload', async () => { + const uniqueDashboardName = `Stacked Line Dashboard ${Date.now()}`; + + await test.step('Create a dashboard with a time-series tile', async () => { + await expect(dashboardPage.createButton).toBeVisible(); + await dashboardPage.createNewDashboard(); + await dashboardPage.editDashboardName(uniqueDashboardName); + + await dashboardPage.addTile(); + await expect(dashboardPage.chartEditor.nameInput).toBeVisible(); + await dashboardPage.chartEditor.createBasicChart('Stacked line tile'); + + await expect(dashboardPage.getTiles()).toHaveCount(1, { timeout: 10000 }); + await expect(dashboardPage.getChartContainers()).toHaveCount(1, { + timeout: 10000, + }); + }); + + await test.step('Switch the tile to stacked line via the switcher', async () => { + await expect( + dashboardPage.getTileDisplaySwitcherOption('line'), + ).toHaveAttribute('data-active', 'true'); + + await dashboardPage.getTileDisplaySwitcherOption('stacked_line').click(); + await expect( + dashboardPage.getTileDisplaySwitcherOption('stacked_line'), + ).toHaveAttribute('data-active', 'true'); + }); + + await test.step('Reload and confirm the stacked line shape persisted', async () => { + await dashboardPage.page.reload(); + await expect(dashboardPage.getChartContainers().first()).toBeVisible(); + await expect( + dashboardPage.getTileDisplaySwitcherOption('stacked_line'), + ).toHaveAttribute('data-active', 'true'); + }); + }); + test('Comprehensive dashboard workflow - create, add tiles, configure, and test', async () => { test.setTimeout(60000); diff --git a/packages/app/tests/e2e/page-objects/DashboardPage.ts b/packages/app/tests/e2e/page-objects/DashboardPage.ts index 35bca0b325..18083a67a3 100644 --- a/packages/app/tests/e2e/page-objects/DashboardPage.ts +++ b/packages/app/tests/e2e/page-objects/DashboardPage.ts @@ -72,7 +72,7 @@ export type SeriesData = { whereLanguage?: 'sql' | 'lucene'; groupBy?: string[]; alias?: string; - displayType?: 'line' | 'stacked_bar'; + displayType?: 'line' | 'stacked_bar' | 'stacked_line'; sortOrder?: 'desc' | 'asc'; fields?: string[]; // For search type content?: string; // For markdown type @@ -808,6 +808,16 @@ export class DashboardPage { return this.page.locator('.recharts-responsive-container'); } + /** A time-chart display-switcher option in a tile's toolbar. */ + getTileDisplaySwitcherOption( + displayType: 'line' | 'stacked_bar' | 'stacked_line', + tileIndex = 0, + ) { + return this.getTile(tileIndex).getByTestId( + `display-switcher-${displayType}`, + ); + } + /** * Read the trimmed text of all th cells in the first thead tr of the * given tile's rendered table. Waits for the table to be visible first. @@ -1581,7 +1591,9 @@ export class DashboardPage { } const type: SeriesData['type'] = - config.displayType === 'line' || config.displayType === 'stacked_bar' + config.displayType === 'line' || + config.displayType === 'stacked_bar' || + config.displayType === 'stacked_line' ? 'time' : config.displayType; diff --git a/packages/cli/src/__tests__/tileRender.test.ts b/packages/cli/src/__tests__/tileRender.test.ts index db80bc9e85..5a015d7cd9 100644 --- a/packages/cli/src/__tests__/tileRender.test.ts +++ b/packages/cli/src/__tests__/tileRender.test.ts @@ -5,6 +5,7 @@ import { DisplayType } from '@hyperdx/common-utils/dist/types'; import { renderTileContent } from '@/shared/tileRender'; import type { TileQueryResult } from '@/shared/tileQuery'; +import { stripAnsi } from '@/termchart'; const dateRange: [Date, Date] = [ new Date('2026-07-10T00:00:00Z'), @@ -38,4 +39,51 @@ describe('renderTileContent', () => { renderTileContent({ result, source: undefined, width: 80, height: 12 }), ).toThrow(/No timestamp column/); }); + + it('renders a stacked line as a stacked bar', () => { + const render = (displayType: DisplayType) => + stripAnsi( + renderTileContent({ + result: { + status: 'ok', + queriedConfig: { + configType: 'sql', + displayType, + sqlTemplate: '', + connection: '', + dateRange, + granularity: '1 minute', + }, + data: { + meta: [ + { name: 'ts', type: 'DateTime' }, + { name: 'ServiceName', type: 'String' }, + { name: 'count()', type: 'UInt64' }, + ], + data: [0, 1, 2].flatMap(minute => [ + { + ts: `2026-07-10 00:0${minute}:00`, + ServiceName: 'api', + 'count()': 100, + }, + { + ts: `2026-07-10 00:0${minute}:00`, + ServiceName: 'web', + 'count()': 200, + }, + ]), + rows: 6, + }, + }, + source: undefined, + width: 60, + height: 12, + }), + ); + + expect(render(DisplayType.StackedLine)).toBe( + render(DisplayType.StackedBar), + ); + expect(render(DisplayType.StackedLine)).not.toBe(render(DisplayType.Line)); + }); }); diff --git a/packages/cli/src/shared/tileConfig.ts b/packages/cli/src/shared/tileConfig.ts index d94fbefa70..b8b1fea940 100644 --- a/packages/cli/src/shared/tileConfig.ts +++ b/packages/cli/src/shared/tileConfig.ts @@ -360,7 +360,7 @@ export function convertToTableChartConfig( * Apply the per-displayType config transform the matching web chart * component would apply before querying: * - * - line / stacked_bar → DBTimeChart → convertToTimeChartConfig + * - line / stacked_bar / stacked_line → DBTimeChart → convertToTimeChartConfig * - number → DBNumberChart → convertToNumberChartConfig * - table → DBTableChart → convertToTableChartConfig * - pie / bar → CategoricalChart → convertToCategoricalChartConfig @@ -372,6 +372,7 @@ export function convertTileConfigForQuery( switch (config.displayType) { case DisplayType.Line: case DisplayType.StackedBar: + case DisplayType.StackedLine: return convertToTimeChartConfig(config, maxTimeBuckets); case DisplayType.Number: return convertToNumberChartConfig(config); @@ -395,6 +396,7 @@ export function convertTileConfigForQuery( export const CLI_SUPPORTED_DISPLAY_TYPES: ReadonlySet = new Set([ DisplayType.Line, DisplayType.StackedBar, + DisplayType.StackedLine, DisplayType.Number, DisplayType.Table, DisplayType.Pie, diff --git a/packages/cli/src/shared/tileRender.ts b/packages/cli/src/shared/tileRender.ts index c22940b746..4b62c77ab7 100644 --- a/packages/cli/src/shared/tileRender.ts +++ b/packages/cli/src/shared/tileRender.ts @@ -72,7 +72,8 @@ export function renderTileContent({ switch (displayType) { case DisplayType.Line: - case DisplayType.StackedBar: { + case DisplayType.StackedBar: + case DisplayType.StackedLine: { const timeChartData = formatResponseForTimeChart({ response: data, dateRange: queriedConfig.dateRange, @@ -85,10 +86,12 @@ export function renderTileContent({ source, data.meta, ); + // Stacked lines render as stacked bars: the terminal has no filled + // areas, and stacked series drawn as bare lines are hard to read. const renderFn = - displayType === DisplayType.StackedBar - ? renderStackedBarChart - : renderLineChart; + displayType === DisplayType.Line + ? renderLineChart + : renderStackedBarChart; const chart = renderFn({ data: timeChartData, width, diff --git a/packages/common-utils/src/__tests__/__snapshots__/builderToRawSql.test.ts.snap b/packages/common-utils/src/__tests__/__snapshots__/builderToRawSql.test.ts.snap index cb0158401c..c1103639d1 100644 --- a/packages/common-utils/src/__tests__/__snapshots__/builderToRawSql.test.ts.snap +++ b/packages/common-utils/src/__tests__/__snapshots__/builderToRawSql.test.ts.snap @@ -174,6 +174,65 @@ ORDER BY $__timeInterval(timestamp) AS \`__hdx_time_bucket\`" `; +exports[`renderBuilderConfigAsSqlTemplate full SQL output per display type generates the full macro-based SQL for a stacked_line chart 1`] = ` +"WITH + \`__hdx_series_limit\` AS ( + SELECT + \`group\` + FROM + ( + SELECT + tuple(ServiceName) AS \`group\`, + count() AS \`__hdx_series_rank\` + FROM + $__sourceTable + WHERE + ( + timestamp >= $__fromTime_ms + AND timestamp <= $__toTime_ms + ) + AND ((ServiceName ILIKE '%api%')) + AND $__filters + AND ServiceName IS NOT NULL + GROUP BY + ServiceName, + $__timeInterval(timestamp) AS \`__hdx_time_bucket\` + ) + GROUP BY + \`group\` + ORDER BY + max(\`__hdx_series_rank\`) DESC, + \`group\` + LIMIT + 10 + ) +SELECT + count(), + AVG(toFloat64OrDefault(toString(Duration))), + ServiceName, + $__timeInterval(timestamp) AS \`__hdx_time_bucket\` +FROM + $__sourceTable +WHERE + ( + timestamp >= $__fromTime_ms + AND timestamp <= $__toTime_ms + ) + AND ((ServiceName ILIKE '%api%')) + AND $__filters + AND tuple(ServiceName) IN ( + SELECT + \`group\` + FROM + \`__hdx_series_limit\` + ) +GROUP BY + ServiceName, + $__timeInterval(timestamp) AS \`__hdx_time_bucket\` +ORDER BY + $__timeInterval(timestamp) AS \`__hdx_time_bucket\`" +`; + exports[`renderBuilderConfigAsSqlTemplate full SQL output per display type generates the full macro-based SQL for a table chart 1`] = ` "SELECT count(), diff --git a/packages/common-utils/src/__tests__/builderToRawSql.test.ts b/packages/common-utils/src/__tests__/builderToRawSql.test.ts index 60f9868dfb..8cc8138f2e 100644 --- a/packages/common-utils/src/__tests__/builderToRawSql.test.ts +++ b/packages/common-utils/src/__tests__/builderToRawSql.test.ts @@ -752,6 +752,14 @@ describe('renderBuilderConfigAsSqlTemplate', () => { granularity: '5 minute', seriesLimit: 10, }, + [DisplayType.StackedLine]: { + ...sourceFields, + displayType: DisplayType.StackedLine, + select: twoSeries, + groupBy, + granularity: '5 minute', + seriesLimit: 10, + }, // Table: multi-series + group by + having + order by (no time bucket). [DisplayType.Table]: { ...sourceFields, diff --git a/packages/common-utils/src/__tests__/guards.test.ts b/packages/common-utils/src/__tests__/guards.test.ts index 0e04ca17bd..e7789a0c96 100644 --- a/packages/common-utils/src/__tests__/guards.test.ts +++ b/packages/common-utils/src/__tests__/guards.test.ts @@ -109,6 +109,10 @@ describe('displayTypeRequiresSource', () => { expect(displayTypeRequiresSource(DisplayType.StackedBar)).toBe(true); }); + it('returns true for StackedLine', () => { + expect(displayTypeRequiresSource(DisplayType.StackedLine)).toBe(true); + }); + it('returns true for Pie', () => { expect(displayTypeRequiresSource(DisplayType.Pie)).toBe(true); }); diff --git a/packages/common-utils/src/__tests__/iac.test.ts b/packages/common-utils/src/__tests__/iac.test.ts index 13b43865ea..896e311b9e 100644 --- a/packages/common-utils/src/__tests__/iac.test.ts +++ b/packages/common-utils/src/__tests__/iac.test.ts @@ -289,6 +289,7 @@ describe('dashboard tile exportability', () => { it.each([ DisplayType.Line, DisplayType.StackedBar, + DisplayType.StackedLine, DisplayType.Table, DisplayType.Number, DisplayType.Pie, diff --git a/packages/common-utils/src/core/__tests__/promql.test.ts b/packages/common-utils/src/core/__tests__/promql.test.ts index 9499ca9104..a0c1c8a6cf 100644 --- a/packages/common-utils/src/core/__tests__/promql.test.ts +++ b/packages/common-utils/src/core/__tests__/promql.test.ts @@ -45,7 +45,11 @@ describe('getQueriedPromqlSeries', () => { ]; it('keeps every expression for a time series chart', () => { - for (const displayType of [DisplayType.Line, DisplayType.StackedBar]) { + for (const displayType of [ + DisplayType.Line, + DisplayType.StackedBar, + DisplayType.StackedLine, + ]) { expect(getQueriedPromqlSeries({ promqlExpression, displayType })).toEqual( promqlExpression, ); @@ -118,7 +122,7 @@ describe('displayTypeSupportsInstantQuery', () => { expect(displayTypeSupportsInstantQuery({ displayType })).toBe(true); }); - it.each([DisplayType.Line, DisplayType.StackedBar])( + it.each([DisplayType.Line, DisplayType.StackedBar, DisplayType.StackedLine])( 'always range-queries %s tiles', displayType => { expect(displayTypeSupportsInstantQuery({ displayType })).toBe(false); diff --git a/packages/common-utils/src/core/builderToRawSql.ts b/packages/common-utils/src/core/builderToRawSql.ts index fe90e7babe..ce3320fe77 100644 --- a/packages/common-utils/src/core/builderToRawSql.ts +++ b/packages/common-utils/src/core/builderToRawSql.ts @@ -6,6 +6,7 @@ import { convertToCategoricalChartConfig, convertToNumberChartConfig, convertToTableChartConfig, + isTimeSeriesDisplayType, } from '@/core/utils'; import { isBuilderChartConfig } from '@/guards'; import { format } from '@/sqlFormatter'; @@ -20,6 +21,7 @@ const RAW_SQL_DISPLAY_TYPES = new Set([ DisplayType.Table, DisplayType.Line, DisplayType.StackedBar, + DisplayType.StackedLine, DisplayType.Pie, DisplayType.Bar, DisplayType.Number, @@ -114,8 +116,7 @@ export async function renderBuilderConfigAsSqlTemplate( // The intervalSeconds param behind $__timeInterval is only bound for // time-series display types (QUERY_PARAMS_BY_DISPLAY_TYPE), so only those // keep a granularity; its concrete value is resolved at query time. - const isTimeSeries = - displayType === DisplayType.Line || displayType === DisplayType.StackedBar; + const isTimeSeries = isTimeSeriesDisplayType(displayType); // Metric queries time-bucket inside their CTEs and therefore need the // interval macros that only time-series display types bind, so metric diff --git a/packages/common-utils/src/core/utils.ts b/packages/common-utils/src/core/utils.ts index cbce10b168..e0a05c46ef 100644 --- a/packages/common-utils/src/core/utils.ts +++ b/packages/common-utils/src/core/utils.ts @@ -1537,9 +1537,7 @@ export function displayTypeSupportsRawSqlAlerts( displayType: DisplayType | undefined, ): boolean { return ( - displayType === DisplayType.Line || - displayType === DisplayType.StackedBar || - displayType === DisplayType.Number + isTimeSeriesDisplayType(displayType) || displayType === DisplayType.Number ); } @@ -1547,9 +1545,7 @@ export function displayTypeSupportsBuilderAlerts( displayType: DisplayType | undefined, ): boolean { return ( - displayType === DisplayType.Line || - displayType === DisplayType.StackedBar || - displayType === DisplayType.Number + isTimeSeriesDisplayType(displayType) || displayType === DisplayType.Number ); } @@ -1564,10 +1560,12 @@ export const isFormulaDisplayType = ( ): displayType is | DisplayType.Line | DisplayType.StackedBar + | DisplayType.StackedLine | DisplayType.Table | DisplayType.Number => displayType === DisplayType.Line || displayType === DisplayType.StackedBar || + displayType === DisplayType.StackedLine || displayType === DisplayType.Table || displayType === DisplayType.Number; @@ -1800,11 +1798,20 @@ export function validateRawSqlChartConfig( return { errors, warnings }; } +/** Maps the time-series display type names used by the external API and v1 chart configs. */ +export const TIME_SERIES_DISPLAY_TYPE_BY_NAME = { + line: DisplayType.Line, + stacked_bar: DisplayType.StackedBar, + stacked_line: DisplayType.StackedLine, +} as const satisfies Record; + export const isTimeSeriesDisplayType = ( displayType: DisplayType | undefined, ): boolean => { return ( - displayType === DisplayType.Line || displayType === DisplayType.StackedBar + displayType === DisplayType.Line || + displayType === DisplayType.StackedBar || + displayType === DisplayType.StackedLine ); }; diff --git a/packages/common-utils/src/iacEligibility.ts b/packages/common-utils/src/iacEligibility.ts index ea61bc2d3b..54a7b7bd79 100644 --- a/packages/common-utils/src/iacEligibility.ts +++ b/packages/common-utils/src/iacEligibility.ts @@ -122,6 +122,7 @@ export function isTileAlertUnaddressable( const RAW_SQL_EXPORTABLE_DISPLAY_TYPES: ReadonlySet = new Set([ DisplayType.Line, DisplayType.StackedBar, + DisplayType.StackedLine, DisplayType.Table, DisplayType.Number, DisplayType.Pie, diff --git a/packages/common-utils/src/rawSqlParams.ts b/packages/common-utils/src/rawSqlParams.ts index 6c136cd03b..91fd1eaf23 100644 --- a/packages/common-utils/src/rawSqlParams.ts +++ b/packages/common-utils/src/rawSqlParams.ts @@ -64,22 +64,20 @@ export const QUERY_PARAMS: Record = { }, }; +const TIME_SERIES_QUERY_PARAMS = [ + QUERY_PARAMS.startDateMilliseconds, + QUERY_PARAMS.endDateMilliseconds, + QUERY_PARAMS.intervalSeconds, + QUERY_PARAMS.intervalMilliseconds, +]; + export const QUERY_PARAMS_BY_DISPLAY_TYPE: Record< DisplayType, QueryParamDefinition[] > = { - [DisplayType.Line]: [ - QUERY_PARAMS.startDateMilliseconds, - QUERY_PARAMS.endDateMilliseconds, - QUERY_PARAMS.intervalSeconds, - QUERY_PARAMS.intervalMilliseconds, - ], - [DisplayType.StackedBar]: [ - QUERY_PARAMS.startDateMilliseconds, - QUERY_PARAMS.endDateMilliseconds, - QUERY_PARAMS.intervalSeconds, - QUERY_PARAMS.intervalMilliseconds, - ], + [DisplayType.Line]: TIME_SERIES_QUERY_PARAMS, + [DisplayType.StackedBar]: TIME_SERIES_QUERY_PARAMS, + [DisplayType.StackedLine]: TIME_SERIES_QUERY_PARAMS, [DisplayType.Table]: [ QUERY_PARAMS.startDateMilliseconds, QUERY_PARAMS.endDateMilliseconds, @@ -119,6 +117,7 @@ export const DATE_RANGE_WHERE_EXAMPLE_SQL = `WHERE TimestampTime >= fromUnixTime export const QUERY_PARAM_EXAMPLES: Record = { [DisplayType.Line]: TIME_CHART_EXAMPLE_SQL, [DisplayType.StackedBar]: TIME_CHART_EXAMPLE_SQL, + [DisplayType.StackedLine]: TIME_CHART_EXAMPLE_SQL, [DisplayType.Table]: DATE_RANGE_WHERE_EXAMPLE_SQL, [DisplayType.Pie]: DATE_RANGE_WHERE_EXAMPLE_SQL, [DisplayType.Bar]: DATE_RANGE_WHERE_EXAMPLE_SQL, diff --git a/packages/common-utils/src/types.ts b/packages/common-utils/src/types.ts index 88e6cf9fe3..f895e15a37 100644 --- a/packages/common-utils/src/types.ts +++ b/packages/common-utils/src/types.ts @@ -34,6 +34,7 @@ export const UseTextIndexSchema = z.nativeEnum(UseTextIndex); export enum DisplayType { Line = 'line', StackedBar = 'stacked_bar', + StackedLine = 'stacked_line', Table = 'table', Pie = 'pie', Bar = 'bar',