diff --git a/.changeset/dashboard-filter-all-option-sql-query.md b/.changeset/dashboard-filter-all-option-sql-query.md new file mode 100644 index 000000000..497c40266 --- /dev/null +++ b/.changeset/dashboard-filter-all-option-sql-query.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': minor +'@hyperdx/app': minor +'@hyperdx/common-utils': minor +--- + +feat: add an "All" option to SQL query dashboard filters. Turn on "Include "All" option" in the filter's settings, and "All" selects every option the query returns, up to 1,000; tiles show an error above that, so add a `LIMIT` if the query can return more. Tiles wait for the options to load before running. Other filters' queries see "All" as no constraint. The external API and MCP accept `allowAll` on SQL query filters, and MCP tile runs with "All" run the filter's query to fill in its options. diff --git a/packages/api/openapi.json b/packages/api/openapi.json index 63b0d8293..52f9992c4 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -4595,6 +4595,11 @@ "description": "Query whose first column populates the dropdown. May use the time\nmacros and other filters' variables. `$__sourceTable` and\n`$__filters` need a `sourceId`; `$__filters` expands to the\ndashboard's broadcast filter selections for that source.\n", "example": "SELECT DISTINCT env FROM default.envs ORDER BY env" }, + "allowAll": { + "type": "boolean", + "description": "Adds an \"All\" choice to the dropdown, which selects every option\nthe query returns, up to 1,000; tiles show an error above that, so\nadd a LIMIT if the query can return more. Only allowed on\nmulti-select filters (not with maxSelections 1). With \"All\"\nselected, `$variableName` and `$__filter` use every option, and\n`$__conditionalAll` expands to 1=1.\n", + "example": true + }, "isBroadcastEnabled": { "type": "boolean", "enum": [ diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts index 5042fc502..23c6782a8 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts @@ -1455,4 +1455,84 @@ describe('MCP Dashboard Tools - clickstack_query_tile', () => { expect(getFirstText(result)).toContain('$traces variable'); }); }); + + describe('"All" on a SQL query filter', () => { + const saveDashboard = async (filterSql: string) => { + const connectionId = ctx.connection._id.toString(); + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'SQL query "All"', + tiles: [ + { + name: 'Regions', + config: { + configType: 'sql', + displayType: 'table', + connectionId, + sqlTemplate: + "SELECT region FROM (SELECT arrayJoin(['us-east-1', 'us-west-1', 'eu-west-1']) AS region) " + + 'WHERE $__filter(region, $region) ORDER BY region', + }, + }, + ], + filters: [ + { + type: 'SQL_QUERY', + name: 'Region', + connectionId, + sqlTemplate: filterSql, + allowAll: true, + variableName: 'region', + }, + ], + }); + expect(result.isError).toBeFalsy(); + return JSON.parse(getFirstText(result)); + }; + + const queryAll = (dashboard: { id: string; tiles: { id: string }[] }) => + callTool(ctx.client!, 'clickstack_query_tile', { + dashboardId: dashboard.id, + tileId: dashboard.tiles[0].id, + variableValues: [{ name: 'region', values: [], all: true }], + }); + + it("expands to the options the filter's query returns", async () => { + const dashboard = await saveDashboard( + "SELECT arrayJoin(['us-west-1', 'us-east-1'])", + ); + + const result = await queryAll(dashboard); + + expect(result.isError).toBeFalsy(); + const rows = JSON.parse(getFirstText(result)).result.data; + expect(rows.map((row: { region: string }) => row.region)).toEqual([ + 'us-east-1', + 'us-west-1', + ]); + }); + + it('rejects more than 1,000 options', async () => { + const dashboard = await saveDashboard( + 'SELECT toString(number) FROM numbers(1001)', + ); + + const result = await queryAll(dashboard); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain('covers more than 1,000 options'); + }); + + it('reports a failing options query', async () => { + const dashboard = await saveDashboard( + 'SELECT region FROM default.no_such_table', + ); + + const result = await queryAll(dashboard); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain( + `Couldn't load the options for "All" on Region`, + ); + }); + }); }); diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index 3689c46ec..d8858dbf6 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -1215,11 +1215,12 @@ Example (static list): ] SQL query filter shape: - { type: "SQL_QUERY", name, connectionId, sourceId?, sqlTemplate, variableName? } + { type: "SQL_QUERY", name, connectionId, sourceId?, sqlTemplate, allowAll?, variableName? } connectionId ClickHouse connection the query runs on (from clickstack_list_sources), or a CONNECTION filter's "$variableName". sourceId Optional log, trace, session, or metric source on that connection, or a DATA_SOURCE filter's "$variableName". Needed for $__sourceTable and $__filters; $__filters expands to the dashboard's broadcast filter selections for that source. sqlTemplate SELECT whose FIRST column becomes the dropdown values, cast to string with nulls and duplicates dropped, in row order (add ORDER BY). May use the time macros and other filters' variables, plus $__sourceTable and $__filters when sourceId is set. + allowAll Set true to add an "All" choice that selects every option the query returns, up to 1,000; tiles show an error above that, so add a LIMIT if the query can return more. Multi-select filters only. Other filters' sqlTemplates see this filter's "All" as no constraint: $__filter and $__conditionalAll expand to 1=1 there and a bare $variableName to NULL, so reference it through the macros. Use it when the values live in a lookup table, dictionary, or join that no single source column covers; otherwise prefer QUERY_EXPRESSION. Like a static filter it is variable-only, so tiles pass the column explicitly: $__filter(, $). @@ -1352,7 +1353,7 @@ VALIDATING clickstack_query_tile and clickstack_query_tiles expand variables with an EMPTY selection by default, which is what a freshly-opened dashboard looks like. Optionally, pass variableValues to check that a tile narrows correctly once something is picked: variableValues: [{ name: "service", values: ["checkout"] }] For a STATIC_LIST filter's variable, every supplied value must be one of the filter's declared options; the dashboard UI can never select anything else, so other values are rejected. -For a filter with allowAll, simulate "All" with { name, values: [], all: true }. +For a filter with allowAll, simulate "All" with { name, values: [], all: true }. For a SQL_QUERY filter, the tools run the filter's query to fill in its options, as the dashboard does. Both tools report variable problems under "warnings". Alerts on a tile always evaluate with every variable empty, so a tile carrying an alert must stay correct with nothing selected. == TABLE TILE LINKING (config.onClick) == diff --git a/packages/api/src/mcp/tools/dashboards/queryTile.ts b/packages/api/src/mcp/tools/dashboards/queryTile.ts index 6d07d8e29..86fa818ca 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTile.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTile.ts @@ -9,6 +9,7 @@ import Dashboard from '@/models/dashboard'; import { convertToExternalDashboard } from '@/routers/external-api/v2/utils/dashboards'; import { objectIdSchema } from '@/utils/zod'; +import { expandSqlQueryAllVariables } from './sqlQueryAllValues'; import { getRawSqlTileMacroWarnings, getTileVariableWarnings, @@ -98,6 +99,18 @@ export function registerQueryTile({ if ('error' in resolvedVariables) { return mcpUserError(resolvedVariables.error); } + const expandedVariables = await expandSqlQueryAllVariables( + context, + externalDashboard, + { + variables: resolvedVariables.variables, + variableValues, + dateRange: [startDate, endDate], + }, + ); + if ('error' in expandedVariables) { + return mcpUserError(expandedVariables.error); + } const resolvedTile = resolveTileVariableReferences( storedTile, @@ -112,7 +125,7 @@ export function registerQueryTile({ const { tile } = resolvedTile; const result = await runConfigTile(context, tile, startDate, endDate, { - variables: resolvedVariables.variables, + variables: expandedVariables.variables, }); // Surface non-blocking missing macro and variable warnings alongside diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index b87293cc6..7b4ee004a 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -15,6 +15,7 @@ import { import type { ExternalDashboardTileWithId } from '@/utils/zod'; import { objectIdSchema } from '@/utils/zod'; +import { expandSqlQueryAllVariables } from './sqlQueryAllValues'; import { getRawSqlTileMacroWarnings, getTileVariableWarnings, @@ -222,7 +223,19 @@ export function registerQueryTiles({ if ('error' in resolved) { return mcpUserError(resolved.error); } - const { variables } = resolved; + const expanded = await expandSqlQueryAllVariables( + context, + externalDashboard, + { + variables: resolved.variables, + variableValues, + dateRange: [startDate, endDate], + }, + ); + if ('error' in expanded) { + return mcpUserError(expanded.error); + } + const { variables } = expanded; // Resolve the target tiles. An explicit `tileIds` array is honored // whenever the field is present — including an empty array, which diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index a59dfb3c6..cc2ff6fbb 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -1859,6 +1859,13 @@ const mcpSqlQueryFilterSchema = z "dashboard's broadcast filter selections for that source. Without a sourceId, " + 'name tables explicitly. Example: "SELECT DISTINCT env FROM default.envs ORDER BY env".', ), + allowAll: SqlQueryDashboardFilterSchema.shape.allowAll.describe( + 'Set true to add an "All" choice to the dropdown, which selects every ' + + 'option the query returns, up to 1,000; tiles show an error above that, ' + + 'so add a LIMIT if the query can return more. Multi-select filters only ' + + '(rejected with maxSelections: 1). With "All" selected, $variableName and ' + + '$__filter use every option, and $__conditionalAll expands to 1=1.', + ), }) .describe( 'A variable-only filter whose dropdown lists the first column of a ClickHouse ' + diff --git a/packages/api/src/mcp/tools/dashboards/sqlQueryAllValues.ts b/packages/api/src/mcp/tools/dashboards/sqlQueryAllValues.ts new file mode 100644 index 000000000..615abad15 --- /dev/null +++ b/packages/api/src/mcp/tools/dashboards/sqlQueryAllValues.ts @@ -0,0 +1,159 @@ +import { + getFilterVariableName, + isSqlQueryFilter, + renderSqlQueryFilterValuesQuery, + SQL_QUERY_FILTER_VALUES_SETTINGS, + toSqlQueryFilterValues, +} from '@hyperdx/common-utils/dist/filters'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; +import { + type ChartVariable, + SourceKind, +} from '@hyperdx/common-utils/dist/types'; +import { + ALL_SELECTION_MAX_OPTIONS, + expandAllSelections, + tooManyOptionsForAllMessage, +} from '@hyperdx/common-utils/dist/variableSelection'; + +import { + MCP_CLICKHOUSE_SETTINGS, + MCP_REQUEST_TIMEOUT, + toPlainMetricTables, +} from '@/mcp/tools/query/helpers'; +import type { McpContext } from '@/mcp/tools/types'; +import { + getMcpClickhouseClient, + McpConnectionNotFoundError, +} from '@/mcp/utils/clickhouse'; +import { getMcpSource } from '@/mcp/utils/sources'; +import type { ExternalDashboard } from '@/routers/external-api/v2/utils/dashboards'; +import type { + ExternalDashboardFilter, + ExternalDashboardFilterWithId, +} from '@/utils/zod'; + +import { getVariableSelections, type McpVariableValues } from './variables'; + +type ExternalFilter = ExternalDashboardFilter | ExternalDashboardFilterWithId; + +type DashboardState = { + variables: ChartVariable[]; + /** Selected values by variable name, for `$name` connection and source references. */ + selections: ReadonlyMap; + dateRange: [Date, Date]; +}; + +/** + * Expand "All" on SQL query filter variables by running each filter's values + * query, as the dashboard does. The queries see the variables with "All" + * unexpanded, as the dashboard's dropdowns do. + */ +export async function expandSqlQueryAllVariables( + context: McpContext, + dashboard: Pick, + { + variables, + variableValues, + dateRange, + }: { + /** From `resolveDashboardVariables`. */ + variables: ChartVariable[]; + variableValues: McpVariableValues | undefined; + dateRange: [Date, Date]; + }, +): Promise<{ variables: ChartVariable[] } | { error: string }> { + const allNames = new Set( + variables.filter(variable => variable.all).map(({ name }) => name), + ); + const state: DashboardState = { + variables, + selections: getVariableSelections( + dashboard.savedFilterValues, + variableValues, + ), + dateRange, + }; + const optionsByName = new Map(); + for (const filter of (dashboard.filters ?? []).filter(isSqlQueryFilter)) { + const name = getFilterVariableName(filter); + if (!name || !allNames.has(name)) continue; + const result = await loadOptions(context, filter, state); + if ('error' in result) { + return { + error: `Couldn't load the options for "All" on ${filter.name}: ${result.error}`, + }; + } + if (result.values.length > ALL_SELECTION_MAX_OPTIONS) { + return { error: tooManyOptionsForAllMessage(filter.name) }; + } + optionsByName.set(name, result.values); + } + return { variables: expandAllSelections(variables, optionsByName) }; +} + +async function loadOptions( + context: McpContext, + filter: Extract, + { variables, selections, dateRange }: DashboardState, +): Promise<{ values: string[] } | { error: string }> { + const resolve = (value: string | undefined) => { + const name = parseVariableReference(value); + return name == null ? value : selections.get(name)?.[0]; + }; + const noSelection = (reference: string) => ({ + error: `${reference} has no selection. Pass one ID for it in variableValues, or save a selection on the dashboard.`, + }); + const connectionId = resolve(filter.connectionId); + if (!connectionId) return noSelection(filter.connectionId); + const sourceId = resolve(filter.sourceId); + if (filter.sourceId && !sourceId) return noSelection(filter.sourceId); + + const source = sourceId ? await getMcpSource(context, sourceId) : undefined; + if (sourceId && !source) return { error: `source ${sourceId} not found` }; + if (source && source.connection.toString() !== connectionId) { + return { error: `source ${source.name} is not on the filter's connection` }; + } + + let rendered: ReturnType; + try { + rendered = renderSqlQueryFilterValuesQuery({ + sqlTemplate: filter.sqlTemplate, + variables, + dateRange, + sourceTables: source + ? { + from: source.from, + metricTables: + source.kind === SourceKind.Metric + ? toPlainMetricTables(source.metricTables) + : undefined, + } + : undefined, + }); + } catch (e) { + return { error: e instanceof Error ? e.message : String(e) }; + } + + try { + const client = await getMcpClickhouseClient(context, connectionId, { + requestTimeout: MCP_REQUEST_TIMEOUT, + }); + const response = await client.query<'JSON'>({ + query: rendered.sql, + query_params: rendered.params, + format: 'JSON', + clickhouse_settings: { + ...MCP_CLICKHOUSE_SETTINGS, + ...SQL_QUERY_FILTER_VALUES_SETTINGS, + }, + }); + const result = await response.json<{ value: string | null }>(); + return { values: toSqlQueryFilterValues(result.data ?? []) }; + } catch (e) { + if (e instanceof McpConnectionNotFoundError) { + return { error: `connection ${connectionId} not found` }; + } + return { error: e instanceof Error ? e.message : String(e) }; + } +} diff --git a/packages/api/src/mcp/tools/dashboards/variables.ts b/packages/api/src/mcp/tools/dashboards/variables.ts index 494052422..e8e5badaf 100644 --- a/packages/api/src/mcp/tools/dashboards/variables.ts +++ b/packages/api/src/mcp/tools/dashboards/variables.ts @@ -226,6 +226,25 @@ export async function getReferenceTargets( }; } +/** + * Each variable's selected values: the caller's variableValues, falling back + * to the dashboard's saved selection. + */ +export function getVariableSelections( + savedFilterValues: ExternalDashboard['savedFilterValues'] | undefined, + variableValues: McpVariableValues | undefined, +): Map { + const selections = new Map(); + for (const value of savedFilterValues ?? []) { + if (value.type === 'variable') selections.set(value.name, value.values); + } + // resolveDashboardVariables has already rejected unknown names + for (const { name, values } of variableValues ?? []) { + selections.set(name, values); + } + return selections; +} + /** * Replace a tile's `$name` sourceId / connectionId with the source or * connection its data source or connection variable selects: the caller's @@ -244,14 +263,7 @@ export function resolveTileVariableReferences< targets: ReferenceTargets, ): { tile: T } | { error: string } { if (!('config' in tile) || tile.config == null) return { tile }; - const selections = new Map(); - for (const value of savedFilterValues ?? []) { - if (value.type === 'variable') selections.set(value.name, value.values); - } - // resolveDashboardVariables has already rejected unknown names - for (const { name, values } of variableValues ?? []) { - selections.set(name, values); - } + const selections = getVariableSelections(savedFilterValues, variableValues); const sourceVariables = new Map( getReferenceVariableFilters(filters).flatMap(({ filter, name }) => isDataSourceFilter(filter) ? [[name, filter] as const] : [], diff --git a/packages/api/src/mcp/tools/query/helpers.ts b/packages/api/src/mcp/tools/query/helpers.ts index b722186c2..dc5016a93 100644 --- a/packages/api/src/mcp/tools/query/helpers.ts +++ b/packages/api/src/mcp/tools/query/helpers.ts @@ -482,7 +482,7 @@ export function assertSourceKindMatchesSelect( * subdocument and throws `DataCloneError: [object Array] could not be cloned`. * Materialize a plain object so the chart config is always structured-cloneable. */ -function toPlainMetricTables( +export function toPlainMetricTables( metricTables: MetricTable | undefined, ): MetricTable | undefined { if (metricTables == null) return undefined; 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 bcf763f92..a97879b93 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 @@ -6420,21 +6420,20 @@ describe('External API v2 Dashboards - new format', () => { ); }); - // Held back until SQL query filters expand "All". - it('rejects allowAll on a SQL query filter', async () => { - await expectFilters( - [ - { - id: new ObjectId().toString(), - type: 'SQL_QUERY' as const, - name: 'Environment', - connectionId: connection._id.toString(), - sqlTemplate: 'SELECT DISTINCT env FROM envs', - allowAll: true, - }, - ], - 400, - ); + it('accepts allowAll on a SQL query filter', async () => { + const response = await sendFilters([ + { + id: new ObjectId().toString(), + type: 'SQL_QUERY' as const, + name: 'Environment', + connectionId: connection._id.toString(), + sqlTemplate: 'SELECT DISTINCT env FROM envs', + allowAll: true, + }, + ]); + + expect(response.status).toBe(200); + expect(response.body.data.filters[0].allowAll).toBe(true); }); }); diff --git a/packages/api/src/routers/external-api/v2/dashboards.ts b/packages/api/src/routers/external-api/v2/dashboards.ts index a51794efd..cf4795dde 100644 --- a/packages/api/src/routers/external-api/v2/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/dashboards.ts @@ -2975,6 +2975,16 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * `$__filters` need a `sourceId`; `$__filters` expands to the * dashboard's broadcast filter selections for that source. * example: "SELECT DISTINCT env FROM default.envs ORDER BY env" + * allowAll: + * type: boolean + * description: | + * Adds an "All" choice to the dropdown, which selects every option + * the query returns, up to 1,000; tiles show an error above that, so + * add a LIMIT if the query can return more. Only allowed on + * multi-select filters (not with maxSelections 1). With "All" + * selected, `$variableName` and `$__filter` use every option, and + * `$__conditionalAll` expands to 1=1. + * example: true * isBroadcastEnabled: * type: boolean * enum: [false] diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index 576381a1d..3ab00b89f 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -215,11 +215,10 @@ const externalPromqlLabelFilterShape = PromqlLabelDashboardFilterSchema.omit({ }); // `connectionId`/`sourceId` rather than `connection`/`source`, matching raw SQL -// tiles. `allowAll` is held back until SQL query filters expand "All". +// tiles. const externalSqlQueryFilterShape = SqlQueryDashboardFilterSchema.omit({ connection: true, source: true, - allowAll: true, }).extend({ connectionId: objectIdOrVariableReferenceSchema, sourceId: objectIdOrVariableReferenceSchema.optional(), diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx index 5bb4b4ee9..f861f4525 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -213,6 +213,11 @@ import SearchWhereInput, { import { Tags } from './components/Tags'; import useDashboardFilters from './hooks/useDashboardFilters'; import { useDashboardRefresh } from './hooks/useDashboardRefresh'; +import { + getUnavailableVariablesMessage, + UnavailableVariable, + useExpandedSqlQueryVariables, +} from './hooks/useExpandedSqlQueryVariables'; import useTileSelection from './hooks/useTileSelection'; import { parseAsJsonEncoded, parseAsStringEncoded } from './utils/queryParsers'; import { usePageTitle } from './brand'; @@ -496,6 +501,7 @@ const Tile = ({ onTimeRangeSelect, filters, variables, + unavailableVariables, unsatisfiedRequiredFilters, referenceVariableNames, showAlertAnnotations, @@ -530,6 +536,8 @@ const Tile = ({ onTimeRangeSelect: (start: Date, end: Date) => void; filters?: BroadcastFilter[]; variables?: ChartVariable[]; + /** Variables whose "All" can't be expanded yet, keyed by variable name. */ + unavailableVariables?: ReadonlyMap; /** The dashboard's required filters that have nothing selected. */ unsatisfiedRequiredFilters?: DashboardFilter[]; /** @@ -736,6 +744,12 @@ const Tile = ({ const isBlockedByRequiredFilters = missingRequiredFilterNames.length > 0 && displayTypeRequiresSource(chart.config.displayType); + // Unlike required filters, also blocks markdown, which would render the + // variable empty + const unavailableVariablesMessage = useMemo( + () => getUnavailableVariablesMessage(tileVariables, unavailableVariables), + [tileVariables, unavailableVariables], + ); const sqlFilters = useMemo( () => (filters ? getSqlFilters(filters) : undefined), @@ -1274,11 +1288,12 @@ const Tile = ({ // The fullscreen view is always visible, so it should always load. // In the tile (grid) view, gate data fetching on viewport visibility. - const chartEnabled = isBlockedByRequiredFilters - ? false - : isFullscreenView - ? true - : hasBeenVisible; + const chartEnabled = + isBlockedByRequiredFilters || unavailableVariablesMessage + ? false + : isFullscreenView + ? true + : hasBeenVisible; // Use the fullscreen-local date range and granularity when rendering // inside the fullscreen modal so that changing them does not affect @@ -1319,6 +1334,14 @@ const Tile = ({ ', ', )}. Select a value for each to load this tile.`} + ) : unavailableVariablesMessage ? ( + + {unavailableVariablesMessage} + ) : isSourceMissing ? ( The data source for this tile no longer exists. Edit the tile to @@ -1579,6 +1602,7 @@ const Tile = ({ isSourceKindUnsupported, isBlockedByRequiredFilters, missingRequiredFilterNames, + unavailableVariablesMessage, hasBeenVisible, annotations, isLive, @@ -1699,6 +1723,7 @@ const EditTileModal = ({ isSaving, dateRange, variables, + unavailableVariables, getDashboardFilters, unsatisfiedRequiredFilters, }: { @@ -1709,6 +1734,7 @@ const EditTileModal = ({ isSaving?: boolean; onSave: (chart: Tile) => void; variables?: ChartVariable[]; + unavailableVariables?: ReadonlyMap; getDashboardFilters: (sourceId: string | undefined) => BroadcastFilter[]; unsatisfiedRequiredFilters?: DashboardFilter[]; }) => { @@ -1776,6 +1802,7 @@ const EditTileModal = ({ dashboardId={dashboardId} chartConfig={chart.config} variables={variables} + unavailableVariables={unavailableVariables} getDashboardFilters={getDashboardFilters} unsatisfiedRequiredFilters={unsatisfiedRequiredFilters} dateRange={dateRange} @@ -2172,6 +2199,16 @@ function DBDashboardPage({ setDisplayedTimeInputValue, }); + // Tiles get "All" on SQL query filters expanded; the filter bar keeps it as is + const { variables: expandedVariables, unavailableVariables } = + useExpandedSqlQueryVariables({ + filters: resolvedFilters, + unresolvedReferenceVariablesByFilterId, + variables, + dateRange: searchedTimeRange, + getDashboardFilters: getFilterQueriesForSource, + }); + const { granularityOverride, isRefreshEnabled, @@ -2549,7 +2586,8 @@ function DBDashboardPage({ } filters={getTileFilters(tileSourceId)} onFilter={tileFilterHandlers.get(chart.id)} - variables={variables} + variables={expandedVariables} + unavailableVariables={unavailableVariables} unsatisfiedRequiredFilters={unsatisfiedRequiredFilters} onTimeRangeSelect={onTimeRangeSelect} showAlertAnnotations={showAlertAnnotations} @@ -2654,7 +2692,8 @@ function DBDashboardPage({ showReleaseAnnotations, getTileFilters, tileFilterHandlers, - variables, + expandedVariables, + unavailableVariables, unsatisfiedRequiredFilters, moveTargetContainers, handleMoveTileToGroup, @@ -3375,7 +3414,8 @@ function DBDashboardPage({ if (!isSaving) setEditedTile(undefined); }} dateRange={searchedTimeRange} - variables={variables} + variables={expandedVariables} + unavailableVariables={unavailableVariables} getDashboardFilters={getTileFilters} unsatisfiedRequiredFilters={unsatisfiedRequiredFilters} isSaving={isSaving} diff --git a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx index dc5110b1b..e67a3121f 100644 --- a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx @@ -39,7 +39,10 @@ import { TILE_DESCRIPTION_MAX_LENGTH, TSource, } from '@hyperdx/common-utils/dist/types'; -import { getAlertVariableWarning } from '@hyperdx/common-utils/dist/variables'; +import { + getAlertVariableWarning, + getReferencedVariableNames, +} from '@hyperdx/common-utils/dist/variables'; import { Alert, Box, @@ -92,6 +95,7 @@ import { HEATMAP_DURATION_NUMBER_FORMAT, PROMQL_DEFAULT_HEATMAP_SCALE_TYPE, } from '@/components/DBHeatmapChart'; +import EmptyState from '@/components/EmptyState'; import { ErrorBoundary } from '@/components/Error/ErrorBoundary'; import { getExemplarToggleState } from '@/components/Exemplars'; import { InputControlled } from '@/components/InputControlled'; @@ -106,6 +110,10 @@ import { } from '@/components/sourceSelectUtils'; import { IS_EXEMPLARS_ENABLED, IS_PROMQL_ENABLED } from '@/config'; import HDXMarkdownChart from '@/HDXMarkdownChart'; +import { + getUnavailableVariablesMessage, + type UnavailableVariable, +} from '@/hooks/useExpandedSqlQueryVariables'; import { getDurationMsExpression, getFirstSeriesNumberFormat, @@ -138,6 +146,8 @@ type EditTimeChartFormProps = { chartConfig: SavedChartConfig; /** Variables and their selected values, from the parent dashboard (if one exists). */ variables?: ChartVariable[]; + /** Variables whose "All" options are loading or unavailable. */ + unavailableVariables?: ReadonlyMap; /** Function returning the dashboard's broadcast filters for the given source, if any. */ getDashboardFilters?: (sourceId: string | undefined) => BroadcastFilter[]; /** The dashboard's required filters that have nothing selected, if any */ @@ -254,6 +264,7 @@ export default function EditTimeChartForm({ dashboardId, chartConfig, variables, + unavailableVariables, getDashboardFilters, unsatisfiedRequiredFilters, displayedTimeInputValue, @@ -670,6 +681,32 @@ export default function EditTimeChartForm({ }; }, [queriedConfig, previewDashboardFilters]); + const previewUnavailableVariablesMessage = useMemo(() => { + let previewVariables = resolvedApplyFilters + ? previewDashboardFilters?.variables + : undefined; + // Markdown previews render the live text rather than a submitted query. + if (activeTab === 'markdown') { + const names = new Set( + getReferencedVariableNames(markdown ?? '', 'markdown'), + ); + previewVariables = variables?.filter(variable => + names.has(variable.name), + ); + } + return getUnavailableVariablesMessage( + previewVariables, + unavailableVariables, + ); + }, [ + activeTab, + markdown, + variables, + previewDashboardFilters, + resolvedApplyFilters, + unavailableVariables, + ]); + const debouncedForm = useDebouncedFormValues(watch, getValues, 300); // With no selection for a variable it references the tile has nothing to @@ -1467,12 +1504,21 @@ export default function EditTimeChartForm({ }} /> - + {previewUnavailableVariablesMessage ? ( + + ) : ( + + )} ) : isPromqlInput ? ( @@ -1586,7 +1632,9 @@ export default function EditTimeChartForm({ canPreviewWithoutFilters={ previewBlockingFilters?.canPreviewWithoutFilters } - blockedReason={previewBlockedReason} + blockedReason={ + previewBlockedReason ?? previewUnavailableVariablesMessage + } setValue={(name, value) => setValue(name, value)} setDisplayType={type => setValue('displayType', type, { shouldDirty: true }) diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx b/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx index 8b35f1ada..7c242e6c4 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx @@ -3,6 +3,7 @@ import React from 'react'; import { useController as mockUseController } from 'react-hook-form'; import { AlertThresholdType, + ChartVariable, DashboardFilter, DataSourceDashboardFilter, DisplayType, @@ -1386,6 +1387,171 @@ describe('DBEditTimeChartForm - dashboard filters', () => { ); }); + const sqlAllVariables: ChartVariable[] = [ + { name: 'service', values: [], all: true }, + ]; + const sqlAllConfig: SavedChartConfig = { + configType: 'sql', + displayType: DisplayType.Table, + name: 'SQL All', + source: 'log-source', + connection: 'default', + sqlTemplate: + 'SELECT count() FROM $__sourceTable WHERE $__filter(ServiceName, $service)', + }; + const unavailableVariables = new Map([ + [ + 'service', + { isLoading: true, message: 'Loading the options for Service…' }, + ], + ]); + + it.each([ + { isLoading: true, message: 'Loading the options for Service…' }, + { isLoading: false, message: "Couldn't load the options for Service." }, + { + isLoading: false, + message: '"All" on Service covers more than 1,000 options.', + }, + ])('blocks SQL All previews: $message', async unavailable => { + renderComponent({ + chartConfig: sqlAllConfig, + variables: sqlAllVariables, + unavailableVariables: new Map([['service', unavailable]]), + getDashboardFilters, + autoRun: true, + }); + + expect(await screen.findByTestId('preview-blocked')).toHaveTextContent( + unavailable.message, + ); + expect(screen.queryByText('Table Chart')).not.toBeInTheDocument(); + }); + + it('resumes SQL All previews when options become available', async () => { + const props = { + chartConfig: sqlAllConfig, + dateRange: [new Date('2024-01-01'), new Date('2024-01-02')], + variables: sqlAllVariables, + unavailableVariables, + getDashboardFilters, + autoRun: true, + } satisfies React.ComponentProps; + const { rerender } = renderComponent(props); + + await screen.findByTestId('preview-blocked'); + rerender( + + + + + , + ); + + expect(await screen.findByText('Table Chart')).toBeVisible(); + expect(screen.queryByTestId('preview-blocked')).not.toBeInTheDocument(); + }); + + it('blocks builder previews that reference unavailable SQL All options', async () => { + renderComponent({ + chartConfig: { + ...logTileConfig, + select: [ + { + aggFn: 'count', + valueExpression: '', + aggCondition: '$__filter(ServiceName, $service)', + aggConditionLanguage: 'sql', + }, + ], + }, + variables: sqlAllVariables, + unavailableVariables, + getDashboardFilters, + autoRun: true, + }); + + expect(await screen.findByTestId('preview-blocked')).toHaveTextContent( + 'Loading the options for Service…', + ); + expect(screen.queryByText('Time Chart')).not.toBeInTheDocument(); + }); + + it('does not block a preview on an unrelated unavailable variable', async () => { + renderComponent({ + chartConfig: { + ...sqlAllConfig, + sqlTemplate: 'SELECT count() FROM $__sourceTable', + }, + variables: sqlAllVariables, + unavailableVariables, + getDashboardFilters, + autoRun: true, + }); + + expect(await screen.findByText('Table Chart')).toBeVisible(); + expect(screen.queryByTestId('preview-blocked')).not.toBeInTheDocument(); + }); + + it('unblocks SQL All previews when filters are disabled and blocks them again when enabled', async () => { + renderComponent({ + chartConfig: sqlAllConfig, + variables: sqlAllVariables, + unavailableVariables, + getDashboardFilters, + autoRun: true, + }); + + await screen.findByTestId('preview-blocked'); + await userEvent.click(filterSwitch()); + expect(await screen.findByText('Table Chart')).toBeVisible(); + expect(screen.queryByTestId('preview-blocked')).not.toBeInTheDocument(); + + await userEvent.click(filterSwitch()); + expect(await screen.findByTestId('preview-blocked')).toBeVisible(); + expect(screen.queryByText('Table Chart')).not.toBeInTheDocument(); + }); + + it('does not block alert previews on unavailable SQL All options', async () => { + renderComponent({ + chartConfig: { + ...sqlAllConfig, + displayType: DisplayType.Number, + alert: configWithAlert.alert, + }, + variables: sqlAllVariables, + unavailableVariables, + getDashboardFilters, + autoRun: true, + }); + + expect(filterSwitch()).not.toBeChecked(); + expect(await screen.findByText('Number Chart')).toBeVisible(); + expect(screen.queryByTestId('preview-blocked')).not.toBeInTheDocument(); + }); + + it('blocks markdown previews that reference unavailable SQL All options', async () => { + renderComponent({ + chartConfig: { + ...logTileConfig, + displayType: DisplayType.Markdown, + markdown: 'Service: $service', + }, + variables: sqlAllVariables, + unavailableVariables, + getDashboardFilters, + }); + + expect(await screen.findByTestId('preview-blocked')).toHaveTextContent( + 'Loading the options for Service…', + ); + expect(screen.queryByText('Markdown Chart')).not.toBeInTheDocument(); + }); + it('cannot be turned on for a tile with an alert', () => { renderComponent({ getDashboardFilters, chartConfig: configWithAlert }); diff --git a/packages/app/src/components/DashboardFiltersModal/AllOptionCheckbox.tsx b/packages/app/src/components/DashboardFiltersModal/AllOptionCheckbox.tsx index 0c732163a..ca971ad9f 100644 --- a/packages/app/src/components/DashboardFiltersModal/AllOptionCheckbox.tsx +++ b/packages/app/src/components/DashboardFiltersModal/AllOptionCheckbox.tsx @@ -10,8 +10,10 @@ import { FilterFormControl } from './filterFormState'; */ export const AllOptionCheckbox = ({ control, + description, }: { control: FilterFormControl; + description: string; }) => { const isSingleSelect = useWatch({ control, name: 'isSingleSelect' }); if (isSingleSelect) return null; @@ -22,7 +24,7 @@ export const AllOptionCheckbox = ({ name="allowAll" size="xs" label='Include "All" option' - description="Selects every option at once. $variable references get every option, and $__conditionalAll expands to 1=1." + description={description} data-testid="filter-allow-all-checkbox" /> ); diff --git a/packages/app/src/components/DashboardFiltersModal/SqlQueryFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/SqlQueryFilterEditForm.tsx index 5cc0edd50..fc084119e 100644 --- a/packages/app/src/components/DashboardFiltersModal/SqlQueryFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/SqlQueryFilterEditForm.tsx @@ -16,7 +16,8 @@ import { BroadcastFilter, DashboardFilter, } from '@hyperdx/common-utils/dist/types'; -import { Alert, Button, Group, Loader, Stack, Text } from '@mantine/core'; +import { ALL_SELECTION_MAX_OPTIONS } from '@hyperdx/common-utils/dist/variableSelection'; +import { Alert, Button, Code, Group, Loader, Stack, Text } from '@mantine/core'; import { IconAlertTriangle, IconPlayerPlay } from '@tabler/icons-react'; import { useQueryClient } from '@tanstack/react-query'; @@ -44,6 +45,7 @@ import { } from '@/utils'; import { resolveConnectionSourceSync } from '@/utils/connectionSourceSync'; +import { AllOptionCheckbox } from './AllOptionCheckbox'; import { TOOLTIP_PORTAL_TARGET } from './constants'; import { CustomInputWrapper } from './CustomInputWrapper'; import { FilterFormControl, FilterFormValues } from './filterFormState'; @@ -307,6 +309,13 @@ export const SqlQueryFilterEditForm = ({ onSubmit={runPreview} parentRef={TOOLTIP_PORTAL_TARGET} /> + + In this options query, "All" on another SQL query filter means no + constraint: $__filter and{' '} + $__conditionalAll become 1=1, while a bare{' '} + $variable becomes NULL. Static-list "All" + still supplies its option values. + {unresolvedVariables.length > 0 && ( @@ -334,6 +343,11 @@ export const SqlQueryFilterEditForm = ({ + + ); diff --git a/packages/app/src/components/DashboardFiltersModal/StaticListFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/StaticListFilterEditForm.tsx index f1465ec15..f08ff02e7 100644 --- a/packages/app/src/components/DashboardFiltersModal/StaticListFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/StaticListFilterEditForm.tsx @@ -48,7 +48,10 @@ export const StaticListFilterEditForm = ({ /> - + diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/SqlQueryFilterEditForm.test.tsx b/packages/app/src/components/DashboardFiltersModal/__tests__/SqlQueryFilterEditForm.test.tsx index b283eda1b..29a1f218d 100644 --- a/packages/app/src/components/DashboardFiltersModal/__tests__/SqlQueryFilterEditForm.test.tsx +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/SqlQueryFilterEditForm.test.tsx @@ -187,6 +187,24 @@ describe('SqlQueryFilterEditForm', () => { mockUseSqlQueryFilterGeneratedSql.mockReturnValue({ data: undefined }); }); + it.each([false, true])( + 'explains SQL All dependencies with single-select=%s', + isSingleSelect => { + renderWithMantine( + , + ); + + const help = screen.getByText(/In this options query,/); + expect(help).toBeVisible(); + expect(help).toHaveTextContent( + '"All" on another SQL query filter means no constraint: $__filter and $__conditionalAll become 1=1, while a bare $variable becomes NULL.', + ); + expect(help).toHaveTextContent( + 'Static-list "All" still supplies its option values.', + ); + }, + ); + it('suggests time macros but not source or interval macros', () => { renderWithMantine(); diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts index 1bb87119d..4c95eb37d 100644 --- a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts @@ -640,26 +640,31 @@ describe('maxSelections', () => { }); describe('allowAll', () => { - it('round-trips allowAll on a static list filter', () => { - const saved = toSavedFilter( - formValues({ ...byType.STATIC_LIST, allowAll: true }), - ); + const allCapable = [ + ['STATIC_LIST', byType.STATIC_LIST], + ['SQL_QUERY', byType.SQL_QUERY], + ] as const; - expect(saved).toMatchObject({ allowAll: true }); - expect(toFormValues(saved).allowAll).toBe(true); - }); + it.each(allCapable)( + 'round-trips allowAll on a %s filter', + (_type, filter) => { + const saved = toSavedFilter(formValues({ ...filter, allowAll: true })); - it('stores nothing for allowAll on a single-select static list filter', () => { - const saved = toSavedFilter( - formValues({ - ...byType.STATIC_LIST, - allowAll: true, - isSingleSelect: true, - }), - ); + expect(saved).toMatchObject({ allowAll: true }); + expect(toFormValues(saved).allowAll).toBe(true); + }, + ); - expect(saved).toMatchObject({ allowAll: undefined }); - }); + it.each(allCapable)( + 'stores nothing for allowAll on a single-select %s filter', + (_type, filter) => { + const saved = toSavedFilter( + formValues({ ...filter, allowAll: true, isSingleSelect: true }), + ); + + expect(saved).toMatchObject({ allowAll: undefined }); + }, + ); it('stores nothing for allowAll when it is off', () => { const saved = toSavedFilter( @@ -669,17 +674,15 @@ describe('allowAll', () => { expect(saved).toMatchObject({ allowAll: undefined }); }); - // SQL query filters don't expand "All" yet - it('stores nothing for allowAll after switching a static list to a SQL query', () => { + it('stores nothing for allowAll on other filter types', () => { const saved = toSavedFilter( formValues({ ...byType.STATIC_LIST, allowAll: true, - ...byType.SQL_QUERY, + ...byType.QUERY_EXPRESSION, }), ); - expect(saved.type).toBe('SQL_QUERY'); expect(saved).not.toHaveProperty('allowAll'); }); }); diff --git a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts index c6d5cef4f..8e204d2a8 100644 --- a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts +++ b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts @@ -104,7 +104,9 @@ export const toFormValues = ( // STATIC_LIST fields options: staticList?.options ?? [], - allowAll: staticList?.allowAll ?? false, + + // STATIC_LIST and SQL_QUERY fields + allowAll: staticList?.allowAll ?? sqlQuery?.allowAll ?? false, // PROMETHEUS_LABEL fields label: promqlLabel?.label ?? '', @@ -140,12 +142,14 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { ...(isSingleSelect ? { maxSelections: 1 } : {}), }; + // Single-select filters don't offer "All", and false isn't stored + const allowAllValue = allowAll && !isSingleSelect ? true : undefined; + if (values.type === 'STATIC_LIST') { return DashboardFilterSchema.parse({ ...rest, options: values.options.map(option => option.trim()), - // Single-select filters don't offer "All", and false isn't stored - allowAll: allowAll && !isSingleSelect ? true : undefined, + allowAll: allowAllValue, isBroadcastEnabled: false, isVariableEnabled: true, variableName: getFilterVariableName(values), @@ -170,8 +174,7 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { ...rest, source: values.source || undefined, sqlTemplate: values.sqlTemplate.trim(), - // No allowAll until SQL query filters expand "All": a static list's - // checkbox value survives switching the type. + allowAll: allowAllValue, isBroadcastEnabled: false, isVariableEnabled: true, variableName: getFilterVariableName(values), diff --git a/packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx b/packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx new file mode 100644 index 000000000..16974dff5 --- /dev/null +++ b/packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx @@ -0,0 +1,177 @@ +import { + ChartVariable, + SqlQueryDashboardFilter, + StaticListDashboardFilter, +} from '@hyperdx/common-utils/dist/types'; +import { renderHook } from '@testing-library/react'; + +import { + getUnavailableVariablesMessage, + useExpandedSqlQueryVariables, +} from '@/hooks/useExpandedSqlQueryVariables'; +import { useSqlQueryFilterValues } from '@/hooks/useSqlQueryFilterValues'; + +jest.mock('@/hooks/useSqlQueryFilterValues', () => ({ + useSqlQueryFilterValues: jest.fn(), +})); + +const mockValues = jest.mocked(useSqlQueryFilterValues); + +const sqlFilter: SqlQueryDashboardFilter = { + id: 'region-filter', + type: 'SQL_QUERY', + name: 'Region', + connection: 'conn1', + sqlTemplate: 'SELECT region FROM regions', + allowAll: true, + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'region', +}; + +const staticFilter: StaticListDashboardFilter = { + id: 'env-filter', + type: 'STATIC_LIST', + name: 'Environment', + options: ['prod', 'dev'], + allowAll: true, + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'env', +}; + +const allRegion: ChartVariable = { name: 'region', values: [], all: true }; + +const mockResult = ( + result: { values: string[]; isLoading: boolean } | undefined, + error?: string, +) => + mockValues.mockReturnValue({ + data: new Map(result ? [[sqlFilter.id, result]] : []), + erroredFilterIds: new Set(error != null ? [sqlFilter.id] : []), + filterErrorMessages: new Map(error ? [[sqlFilter.id, error]] : []), + isLoading: false, + isFetching: false, + isError: error != null, + }); + +const render = ( + variables: ChartVariable[], + unresolvedReferenceVariablesByFilterId?: ReadonlyMap, +) => + renderHook(() => + useExpandedSqlQueryVariables({ + filters: [sqlFilter, staticFilter], + unresolvedReferenceVariablesByFilterId, + variables, + dateRange: [new Date(0), new Date(1000)], + }), + ).result.current; + +describe('useExpandedSqlQueryVariables', () => { + beforeEach(() => mockValues.mockReset()); + + it('expands "All" on a SQL query filter with its loaded options, sorted', () => { + mockResult({ values: ['us-west', 'eu-west'], isLoading: false }); + + const { variables, unavailableVariables } = render([allRegion]); + + expect(variables).toEqual([ + { name: 'region', values: ['eu-west', 'us-west'], all: true }, + ]); + expect(unavailableVariables.size).toBe(0); + }); + + it('queries only SQL query filters with "All" selected', () => { + mockResult(undefined); + + render([ + { name: 'region', values: ['eu-west'] }, + { name: 'env', values: ['dev', 'prod'], all: true }, + ]); + + expect(mockValues).toHaveBeenCalledWith( + expect.objectContaining({ filters: [] }), + ); + }); + + it('marks the variable loading until its options arrive', () => { + mockResult({ values: [], isLoading: true }); + + const { variables, unavailableVariables } = render([allRegion]); + + expect(variables).toEqual([allRegion]); + expect(unavailableVariables.get('region')).toEqual({ + isLoading: true, + message: 'Loading the options for Region…', + }); + }); + + it('reports a failed options query', () => { + mockResult({ values: [], isLoading: false }, 'Unknown table'); + + const { unavailableVariables } = render([allRegion]); + + expect(unavailableVariables.get('region')).toEqual({ + isLoading: false, + message: "Couldn't load the options for Region: Unknown table", + }); + }); + + it('refuses to expand more than 1,000 options', () => { + const values = Array.from({ length: 1001 }, (_, i) => `r${i}`); + mockResult({ values, isLoading: false }); + + const { variables, unavailableVariables } = render([allRegion]); + + expect(variables).toEqual([allRegion]); + expect(unavailableVariables.get('region')?.message).toContain( + 'covers more than 1,000 options', + ); + }); + + it('waits on an unselected connection variable without querying', () => { + mockResult(undefined); + + const { unavailableVariables } = render( + [allRegion], + new Map([[sqlFilter.id, ['conn']]]), + ); + + expect(mockValues).toHaveBeenCalledWith( + expect.objectContaining({ filters: [] }), + ); + expect(unavailableVariables.get('region')).toEqual({ + isLoading: false, + message: 'Select a value for $conn to load the options for Region.', + }); + }); +}); + +describe('getUnavailableVariablesMessage', () => { + const unavailable = new Map([ + ['a', { isLoading: true, message: 'Loading A.' }], + ['b', { isLoading: false, message: 'B failed.' }], + ]); + + it('is undefined when the tile references no unavailable variable', () => { + expect( + getUnavailableVariablesMessage([{ name: 'c', values: [] }], unavailable), + ).toBeUndefined(); + }); + + it('shows errors over loading', () => { + expect( + getUnavailableVariablesMessage( + [ + { name: 'a', values: [] }, + { name: 'b', values: [] }, + ], + unavailable, + ), + ).toBe('B failed.'); + expect( + getUnavailableVariablesMessage([{ name: 'a', values: [] }], unavailable), + ).toBe('Loading A.'); + }); +}); diff --git a/packages/app/src/hooks/__tests__/useSqlQueryFilterValues.test.tsx b/packages/app/src/hooks/__tests__/useSqlQueryFilterValues.test.tsx index e5e043112..69cd1d8ec 100644 --- a/packages/app/src/hooks/__tests__/useSqlQueryFilterValues.test.tsx +++ b/packages/app/src/hooks/__tests__/useSqlQueryFilterValues.test.tsx @@ -10,10 +10,7 @@ import { import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { renderHook, waitFor } from '@testing-library/react'; -import { - toFilterValues, - useSqlQueryFilterValues, -} from '@/hooks/useSqlQueryFilterValues'; +import { useSqlQueryFilterValues } from '@/hooks/useSqlQueryFilterValues'; const mockQuery = jest.fn(); const mockRenderSourceFiltersToSql = jest.fn(); @@ -292,17 +289,3 @@ describe('useSqlQueryFilterValues', () => { expect(mockQuery).toHaveBeenCalledTimes(2); }); }); - -describe('toFilterValues', () => { - it('drops nulls, empty strings, and repeats, keeping query order', () => { - expect( - toFilterValues([ - { value: 'b' }, - { value: null }, - { value: 'a' }, - { value: '' }, - { value: 'b' }, - ]), - ).toEqual(['b', 'a']); - }); -}); diff --git a/packages/app/src/hooks/useExpandedSqlQueryVariables.ts b/packages/app/src/hooks/useExpandedSqlQueryVariables.ts new file mode 100644 index 000000000..2bbe136fb --- /dev/null +++ b/packages/app/src/hooks/useExpandedSqlQueryVariables.ts @@ -0,0 +1,139 @@ +import { useMemo } from 'react'; +import { + getFilterVariableName, + isSqlQueryFilter, +} from '@hyperdx/common-utils/dist/filters'; +import { + BroadcastFilter, + ChartVariable, + DashboardFilter, +} from '@hyperdx/common-utils/dist/types'; +import { + ALL_SELECTION_MAX_OPTIONS, + expandAllSelections, + tooManyOptionsForAllMessage, +} from '@hyperdx/common-utils/dist/variableSelection'; + +import { useSqlQueryFilterValues } from './useSqlQueryFilterValues'; + +/** Why a variable's "All" can't be expanded, so tiles referencing it don't run. */ +export type UnavailableVariable = { + /** True while the options load, so tiles wait rather than show an error. */ + isLoading: boolean; + message: string; +}; + +/** + * The message a tile shows instead of running, or undefined when every + * variable it references is available. Errors win over loading. + */ +export function getUnavailableVariablesMessage( + tileVariables: ChartVariable[] | undefined, + unavailableVariables: ReadonlyMap | undefined, +): string | undefined { + const unavailable = (tileVariables ?? []).flatMap( + variable => unavailableVariables?.get(variable.name) ?? [], + ); + const errors = unavailable.filter(({ isLoading }) => !isLoading); + const shown = errors.length > 0 ? errors : unavailable; + return shown.map(({ message }) => message).join(' ') || undefined; +} + +/** + * Expand "All" on SQL query filter variables with the options each filter's + * query returns, for tiles. Dropdown queries keep "All" unexpanded, which the + * macros treat as no constraint, so filters that reference each other don't + * loop. Runs the same queries as the filter bar, so they share results, but + * doesn't depend on it, since kiosk mode hides it. + */ +export function useExpandedSqlQueryVariables({ + filters, + unresolvedReferenceVariablesByFilterId, + variables, + dateRange, + getDashboardFilters, +}: { + /** The dashboard's filters, with source and connection references resolved. */ + filters: DashboardFilter[]; + unresolvedReferenceVariablesByFilterId?: ReadonlyMap; + variables: ChartVariable[] | undefined; + dateRange: [Date, Date]; + getDashboardFilters?: (sourceId: string) => BroadcastFilter[]; +}): { + variables: ChartVariable[] | undefined; + /** Variables whose "All" can't be expanded, keyed by variable name. */ + unavailableVariables: ReadonlyMap; +} { + const allSelectedFilters = useMemo(() => { + const allNames = new Set( + variables?.filter(variable => variable.all).map(({ name }) => name), + ); + return filters + .filter(isSqlQueryFilter) + .filter(filter => allNames.has(getFilterVariableName(filter) ?? '')); + }, [filters, variables]); + + // A filter whose source or connection variable has no selection can't query + const queryableFilters = useMemo( + () => + allSelectedFilters.filter( + filter => !unresolvedReferenceVariablesByFilterId?.has(filter.id), + ), + [allSelectedFilters, unresolvedReferenceVariablesByFilterId], + ); + + const { data, erroredFilterIds, filterErrorMessages } = + useSqlQueryFilterValues({ + filters: queryableFilters, + dateRange, + variables, + getDashboardFilters, + }); + + return useMemo(() => { + const optionsByVariableName = new Map(); + const unavailableVariables = new Map(); + for (const filter of allSelectedFilters) { + const name = getFilterVariableName(filter) ?? ''; + const unresolved = unresolvedReferenceVariablesByFilterId?.get(filter.id); + const result = data.get(filter.id); + const error = filterErrorMessages.get(filter.id); + if (unresolved) { + const names = unresolved.map(variable => `$${variable}`).join(', '); + unavailableVariables.set(name, { + isLoading: false, + message: `Select a value for ${names} to load the options for ${filter.name}.`, + }); + } else if (erroredFilterIds.has(filter.id)) { + unavailableVariables.set(name, { + isLoading: false, + message: `Couldn't load the options for ${filter.name}${error ? `: ${error}` : '.'}`, + }); + } else if (!result || result.isLoading) { + unavailableVariables.set(name, { + isLoading: true, + message: `Loading the options for ${filter.name}…`, + }); + } else if (result.values.length > ALL_SELECTION_MAX_OPTIONS) { + unavailableVariables.set(name, { + isLoading: false, + message: tooManyOptionsForAllMessage(filter.name), + }); + } else { + optionsByVariableName.set(name, result.values); + } + } + return { + variables: + variables && expandAllSelections(variables, optionsByVariableName), + unavailableVariables, + }; + }, [ + allSelectedFilters, + unresolvedReferenceVariablesByFilterId, + data, + erroredFilterIds, + filterErrorMessages, + variables, + ]); +} diff --git a/packages/app/src/hooks/useSqlQueryFilterValues.tsx b/packages/app/src/hooks/useSqlQueryFilterValues.tsx index 21d74a78c..44db0af42 100644 --- a/packages/app/src/hooks/useSqlQueryFilterValues.tsx +++ b/packages/app/src/hooks/useSqlQueryFilterValues.tsx @@ -9,6 +9,8 @@ import { getSqlFilters, getSqlQueryFilterSourceTables, renderSqlQueryFilterValuesQuery, + SQL_QUERY_FILTER_VALUES_SETTINGS, + toSqlQueryFilterValues, } from '@hyperdx/common-utils/dist/filters'; import { hasMacro } from '@hyperdx/common-utils/dist/macros'; import { @@ -35,9 +37,6 @@ import { useMetadataWithSettings } from './useMetadata'; export const SQL_QUERY_FILTER_VALUES_QUERY_KEY = 'dashboard-filter-sql-query-values'; -/** Seconds a filter's values query may run before ClickHouse stops it. */ -const MAX_EXECUTION_SECONDS = 30; - type RenderedValuesQuery = ReturnType; type ValuesCall = RenderedValuesQuery & { @@ -57,14 +56,6 @@ export type DashboardState = { getDashboardFilters?: (sourceId: string) => BroadcastFilter[]; }; -/** Rows from the values query, without nulls or repeats, in query order. */ -export const toFilterValues = (rows: { value: string | null }[]): string[] => - Array.from( - new Set( - rows.map(row => row.value).filter((value): value is string => !!value), - ), - ); - /** * A filter's values query with every macro but `$__filters` expanded, since * that one needs the source's metadata. `{ error }` when the filter can't @@ -226,14 +217,10 @@ export function useSqlQueryFilterValues({ format: 'JSON', abort_signal: signal, connectionId: call.connection, - clickhouse_settings: { - max_execution_time: MAX_EXECUTION_SECONDS, - // On timeout, list the values read so far instead of failing. - timeout_overflow_mode: 'break', - }, + clickhouse_settings: SQL_QUERY_FILTER_VALUES_SETTINGS, }) .then(res => res.json())) as ResponseJSON<{ value: string | null }>; - return toFilterValues(result.data ?? []); + return toSqlQueryFilterValues(result.data ?? []); }, })), }); diff --git a/packages/app/tests/e2e/features/dashboard-all-option-filters.spec.ts b/packages/app/tests/e2e/features/dashboard-all-option-filters.spec.ts index e0af5a45a..c06651187 100644 --- a/packages/app/tests/e2e/features/dashboard-all-option-filters.spec.ts +++ b/packages/app/tests/e2e/features/dashboard-all-option-filters.spec.ts @@ -1,10 +1,11 @@ /** - * A static list filter with "Include "All" option" offers "All" in its - * dropdown. Picking it stores `all: true` in the `filters=` param and hands - * tiles every option. + * Static list and SQL query filters with "Include "All" option" offer "All" in + * their dropdown. Picking it stores `all: true` in the `filters=` param and + * hands tiles every option. */ import { DashboardPage } from '../page-objects/DashboardPage'; import { expect, test } from '../utils/base-test'; +import { DEFAULT_CONNECTION_NAME } from '../utils/constants'; import { expectFiltersParam } from '../utils/filters-param'; const ENVIRONMENTS = ['prod', 'staging', 'dev']; @@ -68,3 +69,68 @@ test.describe( }); }, ); + +test.describe( + 'Dashboard SQL query filter "All" option', + { tag: ['@dashboard', '@full-stack'] }, + () => { + const addRegionFilter = async ( + dashboardPage: DashboardPage, + sql: string, + ) => { + await dashboardPage.goto(); + await dashboardPage.createNewDashboard(); + await dashboardPage.addMarkdownTile('Regions', 'Regions: $region'); + await dashboardPage.openEditFiltersModal(); + await dashboardPage.addSqlQueryFilterToDashboard({ + name: 'Region', + connectionName: DEFAULT_CONNECTION_NAME, + sql, + variableName: 'region', + allowAll: true, + }); + await dashboardPage.closeFiltersModal(); + await dashboardPage.openFilterDropdown('Region'); + await dashboardPage.getFilterOption('All').click(); + }; + + test('selects every option the query returns for tiles', async ({ + page, + }) => { + const dashboardPage = new DashboardPage(page); + await addRegionFilter( + dashboardPage, + "SELECT arrayJoin(['us-west', 'eu-west'])", + ); + + await expectFiltersParam(page, [ + { type: 'variable', name: 'region', values: [], all: true }, + ]); + await expect(dashboardPage.getTile(0)).toContainText( + 'Regions: eu-west, us-west', + ); + await dashboardPage.editTile(0); + await expect(page.getByTestId('tile-editor-form')).toContainText( + 'Regions: eu-west, us-west', + ); + }); + + test('shows an error on tiles and editor previews when the query returns over 1,000 options', async ({ + page, + }) => { + const dashboardPage = new DashboardPage(page); + await addRegionFilter( + dashboardPage, + 'SELECT toString(number) FROM numbers(1001)', + ); + + await expect(dashboardPage.getTile(0)).toContainText( + 'covers more than 1,000 options', + ); + await dashboardPage.editTile(0); + await expect(page.getByTestId('preview-blocked')).toContainText( + 'covers more than 1,000 options', + ); + }); + }, +); diff --git a/packages/app/tests/e2e/page-objects/DashboardPage.ts b/packages/app/tests/e2e/page-objects/DashboardPage.ts index 074977458..55f9c72c9 100644 --- a/packages/app/tests/e2e/page-objects/DashboardPage.ts +++ b/packages/app/tests/e2e/page-objects/DashboardPage.ts @@ -1684,12 +1684,14 @@ export class DashboardPage { sourceName, sql, variableName, + allowAll, }: { name: string; connectionName: string; sourceName?: string; sql: string; variableName?: string; + allowAll?: boolean; }) { const form = this.getFilterForm(); await this.selectFilterType('SQL query values'); @@ -1723,6 +1725,9 @@ export class DashboardPage { if (variableName !== undefined) { await this.variableNameInput.fill(variableName); } + if (allowAll !== undefined) { + await this.allowAllCheckbox.setChecked(allowAll); + } } /** diff --git a/packages/common-utils/src/__tests__/filters.test.ts b/packages/common-utils/src/__tests__/filters.test.ts index 5fb4da606..035792789 100644 --- a/packages/common-utils/src/__tests__/filters.test.ts +++ b/packages/common-utils/src/__tests__/filters.test.ts @@ -33,6 +33,7 @@ import { resolvePromqlLabelFilterMatch, serializeFilterState, SQL_QUERY_FILTER_VALUES_LIMIT, + toSqlQueryFilterValues, validateDashboardFilterQueries, validateSavedFilterValues, validateSavedQuery, @@ -1422,6 +1423,20 @@ describe('filters', () => { }); }); + describe('toSqlQueryFilterValues', () => { + it('drops nulls, empty strings, and repeats, keeping query order', () => { + expect( + toSqlQueryFilterValues([ + { value: 'b' }, + { value: null }, + { value: 'a' }, + { value: '' }, + { value: 'b' }, + ]), + ).toEqual(['b', 'a']); + }); + }); + describe('getPendingFilterValuesVariables', () => { const svc = (values: string[]): ChartVariable => ({ name: 'svc', diff --git a/packages/common-utils/src/filters.ts b/packages/common-utils/src/filters.ts index 0e804715a..bb5d193ab 100644 --- a/packages/common-utils/src/filters.ts +++ b/packages/common-utils/src/filters.ts @@ -1,3 +1,4 @@ +import type { ClickHouseSettings } from '@clickhouse/client-common'; import * as SQLParser from 'node-sql-parser'; import { escapeSqlString, replaceJsonExpressions } from '@/core/utils'; @@ -1013,6 +1014,25 @@ export function renderSqlQueryFilterValuesQuery({ }; } +/** + * Settings a SQL query filter's values query runs with. On timeout it returns + * the values read so far instead of failing. + */ +export const SQL_QUERY_FILTER_VALUES_SETTINGS = { + max_execution_time: 30, + timeout_overflow_mode: 'break', +} satisfies ClickHouseSettings; + +/** Rows from the values query, without nulls or repeats, in query order. */ +export const toSqlQueryFilterValues = ( + rows: { value: string | null }[], +): string[] => + Array.from( + new Set( + rows.map(row => row.value).filter((value): value is string => !!value), + ), + ); + /** Derive the default `variableName` for a filter from its display name. */ export function deriveVariableName(filterName: string): string { const sanitized = filterName diff --git a/packages/common-utils/src/variableSelection.ts b/packages/common-utils/src/variableSelection.ts index 61ab72c5f..65d43b531 100644 --- a/packages/common-utils/src/variableSelection.ts +++ b/packages/common-utils/src/variableSelection.ts @@ -1,4 +1,7 @@ -import type { ChartVariable } from '@/types'; +import { + type ChartVariable, + DASHBOARD_STATIC_FILTER_MAX_OPTIONS, +} from '@/types'; /** * A dashboard variable's selection: an explicit list of values, or the @@ -44,3 +47,16 @@ export function expandAllSelections( return options ? { ...variable, values: [...options].sort() } : variable; }); } + +/** + * Most options "All" on a SQL query filter expands to, the same cap as a static + * list's options. Keeps the expanded `IN (...)` list well within ClickHouse's + * query size limit. + */ +export const ALL_SELECTION_MAX_OPTIONS = DASHBOARD_STATIC_FILTER_MAX_OPTIONS; + +/** Why "All" isn't expanded for a filter with more than the capped options. */ +export const tooManyOptionsForAllMessage = (filterName: string) => + `"All" on ${filterName} covers more than ` + + `${ALL_SELECTION_MAX_OPTIONS.toLocaleString('en-US')} options. Add a LIMIT ` + + `to the filter's query, or narrow it, to use "All".`;