From 2b1ad4847f0934b724250c38bec7b7da735f842b Mon Sep 17 00:00:00 2001 From: Karl Power Date: Fri, 27 Nov 2026 16:30:17 +0100 Subject: [PATCH 1/2] feat: add an "All" option to SQL query dashboard filters --- .../dashboard-filter-all-option-sql-query.md | 7 + packages/api/openapi.json | 5 + .../dashboards/queryTile.int.test.ts | 80 ++++++++ .../api/src/mcp/prompts/dashboards/content.ts | 5 +- .../api/src/mcp/tools/dashboards/queryTile.ts | 15 +- .../src/mcp/tools/dashboards/queryTiles.ts | 15 +- .../api/src/mcp/tools/dashboards/schemas.ts | 7 + .../mcp/tools/dashboards/sqlQueryAllValues.ts | 159 ++++++++++++++++ .../api/src/mcp/tools/dashboards/variables.ts | 28 ++- packages/api/src/mcp/tools/query/helpers.ts | 2 +- .../__tests__/dashboards.int.test.ts | 29 ++- .../src/routers/external-api/v2/dashboards.ts | 10 + packages/api/src/utils/zod.ts | 3 +- packages/app/src/DBDashboardPage.tsx | 56 +++++- .../DBEditTimeChartForm/EditTimeChartForm.tsx | 66 ++++++- .../__tests__/DBEditTimeChartForm.test.tsx | 166 ++++++++++++++++ .../AllOptionCheckbox.tsx | 4 +- .../SqlQueryFilterEditForm.tsx | 16 +- .../StaticListFilterEditForm.tsx | 5 +- .../__tests__/SqlQueryFilterEditForm.test.tsx | 18 ++ .../__tests__/filterFormState.test.ts | 45 ++--- .../DashboardFiltersModal/filterFormState.ts | 13 +- .../useExpandedSqlQueryVariables.test.tsx | 177 ++++++++++++++++++ .../useSqlQueryFilterValues.test.tsx | 19 +- .../src/hooks/useExpandedSqlQueryVariables.ts | 139 ++++++++++++++ .../app/src/hooks/useSqlQueryFilterValues.tsx | 21 +-- .../dashboard-all-option-filters.spec.ts | 72 ++++++- .../tests/e2e/page-objects/DashboardPage.ts | 5 + .../src/__tests__/filters.test.ts | 15 ++ packages/common-utils/src/filters.ts | 20 ++ .../common-utils/src/variableSelection.ts | 18 +- 31 files changed, 1125 insertions(+), 115 deletions(-) create mode 100644 .changeset/dashboard-filter-all-option-sql-query.md create mode 100644 packages/api/src/mcp/tools/dashboards/sqlQueryAllValues.ts create mode 100644 packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx create mode 100644 packages/app/src/hooks/useExpandedSqlQueryVariables.ts 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 0000000000..497c402669 --- /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 ac148b849c..f89d771fba 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -4652,6 +4652,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 5042fc502c..23c6782a8b 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 0e9c455fdb..9138d2c1ce 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 6d07d8e299..86fa818ca4 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 b87293cc68..7b4ee004a5 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 d2b89241f6..20ae606c14 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -1913,6 +1913,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 0000000000..615abad154 --- /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 4940524222..e8e5badafc 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 b722186c29..dc5016a93c 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 bcf763f923..a97879b93f 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 ec79c4b77e..a09ef06263 100644 --- a/packages/api/src/routers/external-api/v2/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/dashboards.ts @@ -3017,6 +3017,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 5e69ab1400..94390f3718 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -216,11 +216,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 a532c598ba..430f981e54 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -214,6 +214,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'; @@ -497,6 +502,7 @@ const Tile = ({ onTimeRangeSelect, filters, variables, + unavailableVariables, unsatisfiedRequiredFilters, referenceVariableNames, showAlertAnnotations, @@ -531,6 +537,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[]; /** @@ -737,6 +745,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), @@ -1275,11 +1289,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 @@ -1320,6 +1335,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 @@ -1581,6 +1604,7 @@ const Tile = ({ isSourceKindUnsupported, isBlockedByRequiredFilters, missingRequiredFilterNames, + unavailableVariablesMessage, hasBeenVisible, annotations, isLive, @@ -1701,6 +1725,7 @@ const EditTileModal = ({ isSaving, dateRange, variables, + unavailableVariables, getDashboardFilters, unsatisfiedRequiredFilters, }: { @@ -1711,6 +1736,7 @@ const EditTileModal = ({ isSaving?: boolean; onSave: (chart: Tile) => void; variables?: ChartVariable[]; + unavailableVariables?: ReadonlyMap; getDashboardFilters: (sourceId: string | undefined) => BroadcastFilter[]; unsatisfiedRequiredFilters?: DashboardFilter[]; }) => { @@ -1778,6 +1804,7 @@ const EditTileModal = ({ dashboardId={dashboardId} chartConfig={chart.config} variables={variables} + unavailableVariables={unavailableVariables} getDashboardFilters={getDashboardFilters} unsatisfiedRequiredFilters={unsatisfiedRequiredFilters} dateRange={dateRange} @@ -2187,6 +2214,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, @@ -2564,7 +2601,8 @@ function DBDashboardPage({ } filters={getTileFilters(tileSourceId)} onFilter={tileFilterHandlers.get(chart.id)} - variables={variables} + variables={expandedVariables} + unavailableVariables={unavailableVariables} unsatisfiedRequiredFilters={unsatisfiedRequiredFilters} onTimeRangeSelect={onTimeRangeSelect} showAlertAnnotations={showAlertAnnotations} @@ -2669,7 +2707,8 @@ function DBDashboardPage({ showReleaseAnnotations, getTileFilters, tileFilterHandlers, - variables, + expandedVariables, + unavailableVariables, unsatisfiedRequiredFilters, moveTargetContainers, handleMoveTileToGroup, @@ -3390,7 +3429,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 50640e07f3..5b8522936d 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,13 +1504,22 @@ export default function EditTimeChartForm({ }} /> - + {previewUnavailableVariablesMessage ? ( + + ) : ( + + )} ) : isPromqlInput ? ( @@ -1587,7 +1633,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 8b35f1adaf..7c242e6c4a 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 0c732163ae..ca971ad9fa 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 5cc0edd507..fc084119e4 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 f1465ec158..f08ff02e77 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 b283eda1b9..29a1f218d8 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 1bb87119d6..4c95eb37de 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 c6d5cef4f8..8e204d2a81 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 0000000000..16974dff5e --- /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 e5e043112d..69cd1d8ecb 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 0000000000..2bbe136fb8 --- /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 21d74a78c6..44db0af423 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 e0af5a45a7..c06651187a 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 48a6cc31f7..aaf765a417 100644 --- a/packages/app/tests/e2e/page-objects/DashboardPage.ts +++ b/packages/app/tests/e2e/page-objects/DashboardPage.ts @@ -1721,12 +1721,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'); @@ -1760,6 +1762,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 5fb4da6065..035792789d 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 0e804715ae..bb5d193ab9 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 61ab72c5f5..65d43b5316 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".`; From d7aee3ed379f3f4728ed26b88cb882890cfdc846 Mon Sep 17 00:00:00 2001 From: Karl Power Date: Wed, 2 Dec 2026 11:21:34 +0100 Subject: [PATCH 2/2] feat: warn when a SQL query filter's options query is cut off at 30 s --- .../dashboard-filter-all-option-sql-query.md | 2 +- .../dashboards/sqlQueryAllValues.test.ts | 122 ++++++++++++++++++ .../api/src/mcp/prompts/dashboards/content.ts | 2 +- .../api/src/mcp/tools/dashboards/queryTile.ts | 10 +- .../src/mcp/tools/dashboards/queryTiles.ts | 6 +- .../mcp/tools/dashboards/sqlQueryAllValues.ts | 54 +++++++- packages/app/src/DBDashboardPage.tsx | 51 ++++++-- packages/app/src/DashboardFilters.tsx | 14 ++ .../src/components/DashboardFilterLabel.tsx | 4 + .../SqlQueryFilterEditForm.tsx | 10 ++ .../useExpandedSqlQueryVariables.test.tsx | 43 +++++- .../useSqlQueryFilterValues.test.tsx | 19 +++ .../src/hooks/useDashboardFilterValues.tsx | 10 +- .../src/hooks/useExpandedSqlQueryVariables.ts | 23 ++++ .../app/src/hooks/useSqlQueryFilterValues.tsx | 24 +++- .../src/__tests__/filters.test.ts | 8 ++ packages/common-utils/src/filters.ts | 9 ++ .../common-utils/src/variableSelection.ts | 6 + 18 files changed, 393 insertions(+), 24 deletions(-) create mode 100644 packages/api/src/mcp/__tests__/dashboards/sqlQueryAllValues.test.ts diff --git a/.changeset/dashboard-filter-all-option-sql-query.md b/.changeset/dashboard-filter-all-option-sql-query.md index 497c402669..44c77e46f6 100644 --- a/.changeset/dashboard-filter-all-option-sql-query.md +++ b/.changeset/dashboard-filter-all-option-sql-query.md @@ -4,4 +4,4 @@ '@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. +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. When the options query hits its 30 s time limit, the filter, tiles that use its "All", and MCP tile runs show a warning that the list may be incomplete. 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/src/mcp/__tests__/dashboards/sqlQueryAllValues.test.ts b/packages/api/src/mcp/__tests__/dashboards/sqlQueryAllValues.test.ts new file mode 100644 index 0000000000..3da63f0325 --- /dev/null +++ b/packages/api/src/mcp/__tests__/dashboards/sqlQueryAllValues.test.ts @@ -0,0 +1,122 @@ +import { fromAny } from '@total-typescript/shoehorn'; + +import { + expandSqlQueryAllVariables, + getTileAllWarnings, +} from '@/mcp/tools/dashboards/sqlQueryAllValues'; +import type { McpContext } from '@/mcp/tools/types'; +import type { + ExternalDashboardFilterWithId, + ExternalDashboardTileWithId, +} from '@/utils/zod'; + +const mockQuery = jest.fn(); + +jest.mock('@/mcp/utils/clickhouse', () => ({ + ...jest.requireActual('@/mcp/utils/clickhouse'), + getMcpClickhouseClient: async () => ({ query: mockQuery }), +})); + +const context: McpContext = { teamId: 'team-1', userId: 'user-1' }; + +const regionFilter: ExternalDashboardFilterWithId = fromAny({ + id: 'region-filter', + type: 'SQL_QUERY', + name: 'Region', + connectionId: 'conn-1', + sqlTemplate: 'SELECT region FROM regions', + allowAll: true, + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'region', +}); + +const sqlTile = (sqlTemplate: string): ExternalDashboardTileWithId => ({ + id: 'tile', + name: 'Tile', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + configType: 'sql', + displayType: 'table', + connectionId: 'conn-1', + sqlTemplate, + }, +}); + +// Each request takes `requestMs` on a fake clock +const respondWith = (values: string[], requestMs: number) => { + let now = 0; + jest.spyOn(Date, 'now').mockImplementation(() => now); + mockQuery.mockImplementation(async () => { + now += requestMs; + return { json: async () => ({ data: values.map(value => ({ value })) }) }; + }); +}; + +const expand = () => + expandSqlQueryAllVariables( + context, + { filters: [regionFilter], savedFilterValues: [] }, + { + variables: [{ name: 'region', values: [], all: true }], + variableValues: [{ name: 'region', values: [], all: true }], + dateRange: [new Date(0), new Date(1000)], + }, + ); + +describe('expandSqlQueryAllVariables', () => { + beforeEach(() => mockQuery.mockReset()); + afterEach(() => jest.restoreAllMocks()); + + it('expands "All" with the options the query returns', async () => { + respondWith(['us-west', 'eu-west'], 100); + + expect(await expand()).toEqual({ + variables: [ + { name: 'region', values: ['eu-west', 'us-west'], all: true }, + ], + warnings: new Map(), + }); + }); + + it('warns when the options request took the whole time limit', async () => { + respondWith(['eu-west'], 30_200); + + const result = await expand(); + + expect(result).toMatchObject({ + warnings: new Map([ + [ + 'region', + '"All" on Region may be missing options: its options query stopped after 30 s.', + ], + ]), + }); + }); +}); + +describe('getTileAllWarnings', () => { + const variables = [ + { name: 'region', values: ['eu-west'], all: true as const }, + ]; + const warnings = new Map([['region', 'Region may be incomplete.']]); + + it('returns the warnings for the variables a tile references', () => { + expect( + getTileAllWarnings( + sqlTile('SELECT 1 WHERE $__filter(region, $region)'), + variables, + warnings, + ), + ).toEqual(['Region may be incomplete.']); + }); + + it("returns nothing for a tile that doesn't reference them", () => { + expect( + getTileAllWarnings(sqlTile('SELECT 1'), variables, warnings), + ).toEqual([]); + }); +}); diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index 9138d2c1ce..2c000d21a6 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -1220,7 +1220,7 @@ SQL query filter shape: 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. + 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. If the query hits its 30 s time limit, "All" covers the values read so far and clickstack_query_tile reports a warning. 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(, $). diff --git a/packages/api/src/mcp/tools/dashboards/queryTile.ts b/packages/api/src/mcp/tools/dashboards/queryTile.ts index 86fa818ca4..99cad1cfe8 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTile.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTile.ts @@ -9,7 +9,10 @@ import Dashboard from '@/models/dashboard'; import { convertToExternalDashboard } from '@/routers/external-api/v2/utils/dashboards'; import { objectIdSchema } from '@/utils/zod'; -import { expandSqlQueryAllVariables } from './sqlQueryAllValues'; +import { + expandSqlQueryAllVariables, + getTileAllWarnings, +} from './sqlQueryAllValues'; import { getRawSqlTileMacroWarnings, getTileVariableWarnings, @@ -134,6 +137,11 @@ export function registerQueryTile({ const warnings = [ ...getRawSqlTileMacroWarnings([tile]), ...getTileVariableWarnings([tile], externalDashboard.filters), + ...getTileAllWarnings( + tile, + expandedVariables.variables, + expandedVariables.warnings, + ), ]; if ( warnings.length > 0 && diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index 7b4ee004a5..3a3a5aaa03 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -15,7 +15,10 @@ import { import type { ExternalDashboardTileWithId } from '@/utils/zod'; import { objectIdSchema } from '@/utils/zod'; -import { expandSqlQueryAllVariables } from './sqlQueryAllValues'; +import { + expandSqlQueryAllVariables, + getTileAllWarnings, +} from './sqlQueryAllValues'; import { getRawSqlTileMacroWarnings, getTileVariableWarnings, @@ -349,6 +352,7 @@ export function registerQueryTiles({ const warnings = [ ...getRawSqlTileMacroWarnings([tile]), ...getTileVariableWarnings([tile], externalDashboard.filters), + ...getTileAllWarnings(tile, variables, expanded.warnings), ]; return { ...base, diff --git a/packages/api/src/mcp/tools/dashboards/sqlQueryAllValues.ts b/packages/api/src/mcp/tools/dashboards/sqlQueryAllValues.ts index 615abad154..fdd36c87f5 100644 --- a/packages/api/src/mcp/tools/dashboards/sqlQueryAllValues.ts +++ b/packages/api/src/mcp/tools/dashboards/sqlQueryAllValues.ts @@ -1,6 +1,7 @@ import { getFilterVariableName, isSqlQueryFilter, + isSqlQueryFilterValuesCutOff, renderSqlQueryFilterValuesQuery, SQL_QUERY_FILTER_VALUES_SETTINGS, toSqlQueryFilterValues, @@ -10,8 +11,10 @@ import { type ChartVariable, SourceKind, } from '@hyperdx/common-utils/dist/types'; +import { filterReferencedVariables } from '@hyperdx/common-utils/dist/variables'; import { ALL_SELECTION_MAX_OPTIONS, + cutOffOptionsForAllMessage, expandAllSelections, tooManyOptionsForAllMessage, } from '@hyperdx/common-utils/dist/variableSelection'; @@ -27,10 +30,15 @@ import { McpConnectionNotFoundError, } from '@/mcp/utils/clickhouse'; import { getMcpSource } from '@/mcp/utils/sources'; -import type { ExternalDashboard } from '@/routers/external-api/v2/utils/dashboards'; +import { + convertToInternalTileConfig, + type ExternalDashboard, + isConfigTile, +} from '@/routers/external-api/v2/utils/dashboards'; import type { ExternalDashboardFilter, ExternalDashboardFilterWithId, + ExternalDashboardTileWithId, } from '@/utils/zod'; import { getVariableSelections, type McpVariableValues } from './variables'; @@ -62,7 +70,14 @@ export async function expandSqlQueryAllVariables( variableValues: McpVariableValues | undefined; dateRange: [Date, Date]; }, -): Promise<{ variables: ChartVariable[] } | { error: string }> { +): Promise< + | { + variables: ChartVariable[]; + /** For "All" options that may be incomplete, keyed by variable name. */ + warnings: ReadonlyMap; + } + | { error: string } +> { const allNames = new Set( variables.filter(variable => variable.all).map(({ name }) => name), ); @@ -75,6 +90,7 @@ export async function expandSqlQueryAllVariables( dateRange, }; const optionsByName = new Map(); + const warnings = new Map(); for (const filter of (dashboard.filters ?? []).filter(isSqlQueryFilter)) { const name = getFilterVariableName(filter); if (!name || !allNames.has(name)) continue; @@ -88,15 +104,39 @@ export async function expandSqlQueryAllVariables( return { error: tooManyOptionsForAllMessage(filter.name) }; } optionsByName.set(name, result.values); + if (result.isCutOff) { + warnings.set(name, cutOffOptionsForAllMessage(filter.name)); + } + } + return { + variables: expandAllSelections(variables, optionsByName), + warnings, + }; +} + +/** The warnings from `expandSqlQueryAllVariables` for the variables a tile uses. */ +export function getTileAllWarnings( + tile: ExternalDashboardTileWithId, + variables: ChartVariable[], + warnings: ReadonlyMap, +): string[] { + if (warnings.size === 0 || !isConfigTile(tile)) return []; + try { + const { config } = convertToInternalTileConfig(tile); + return filterReferencedVariables(config, variables).flatMap( + variable => warnings.get(variable.name) ?? [], + ); + } catch { + // A tile the converter refuses fails when it runs; nothing to add here. + return []; } - return { variables: expandAllSelections(variables, optionsByName) }; } async function loadOptions( context: McpContext, filter: Extract, { variables, selections, dateRange }: DashboardState, -): Promise<{ values: string[] } | { error: string }> { +): Promise<{ values: string[]; isCutOff: boolean } | { error: string }> { const resolve = (value: string | undefined) => { const name = parseVariableReference(value); return name == null ? value : selections.get(name)?.[0]; @@ -139,6 +179,7 @@ async function loadOptions( const client = await getMcpClickhouseClient(context, connectionId, { requestTimeout: MCP_REQUEST_TIMEOUT, }); + const startedAt = Date.now(); const response = await client.query<'JSON'>({ query: rendered.sql, query_params: rendered.params, @@ -149,7 +190,10 @@ async function loadOptions( }, }); const result = await response.json<{ value: string | null }>(); - return { values: toSqlQueryFilterValues(result.data ?? []) }; + return { + values: toSqlQueryFilterValues(result.data ?? []), + isCutOff: isSqlQueryFilterValuesCutOff(Date.now() - startedAt), + }; } catch (e) { if (e instanceof McpConnectionNotFoundError) { return { error: `connection ${connectionId} not found` }; diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx index 430f981e54..316a77d9dc 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -216,6 +216,7 @@ import useDashboardFilters from './hooks/useDashboardFilters'; import { useDashboardRefresh } from './hooks/useDashboardRefresh'; import { getUnavailableVariablesMessage, + getVariableWarningsMessage, UnavailableVariable, useExpandedSqlQueryVariables, } from './hooks/useExpandedSqlQueryVariables'; @@ -503,6 +504,7 @@ const Tile = ({ filters, variables, unavailableVariables, + variableWarnings, unsatisfiedRequiredFilters, referenceVariableNames, showAlertAnnotations, @@ -539,6 +541,8 @@ const Tile = ({ variables?: ChartVariable[]; /** Variables whose "All" can't be expanded yet, keyed by variable name. */ unavailableVariables?: ReadonlyMap; + /** Warnings for variables whose "All" may be incomplete, by variable name. */ + variableWarnings?: ReadonlyMap; /** The dashboard's required filters that have nothing selected. */ unsatisfiedRequiredFilters?: DashboardFilter[]; /** @@ -751,6 +755,10 @@ const Tile = ({ () => getUnavailableVariablesMessage(tileVariables, unavailableVariables), [tileVariables, unavailableVariables], ); + const variableWarningsMessage = useMemo( + () => getVariableWarningsMessage(tileVariables, variableWarnings), + [tileVariables, variableWarnings], + ); const sqlFilters = useMemo( () => (filters ? getSqlFilters(filters) : undefined), @@ -1004,6 +1012,25 @@ const Tile = ({ ); }, [sqlFilters, queriedConfig, source]); + const variableWarning = useMemo( + () => + variableWarningsMessage ? ( + + + + ) : null, + [variableWarningsMessage], + ); + const addTimeZone = useTimeZoneLinkParam(); const replaySearchUrl = useMemo(() => { const url = buildDashboardReplaySearchUrl({ @@ -1280,7 +1307,7 @@ const Tile = ({ // Tile-level actions (alert bell + kebab) render as a suffix so they // sit to the right of each chart's own controls (display switcher, // granularity, etc.), keeping the kebab at the far right edge. - const toolbarPrefixItems = [filterWarning]; + const toolbarPrefixItems = [filterWarning, variableWarning]; const toolbarSuffixItems = hideToolbar ? [] : [hoverToolbar]; // Combined + ordered for containers that only accept `toolbarItems` // (they have no chart-specific controls to interleave). @@ -1598,6 +1625,7 @@ const Tile = ({ fullscreenDateRange, fullscreenGranularity, filterWarning, + variableWarning, isSourceMissing, isSourceUnset, isSourceOnOtherConnection, @@ -2215,14 +2243,17 @@ function DBDashboardPage({ }); // 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 { + variables: expandedVariables, + unavailableVariables, + variableWarnings, + } = useExpandedSqlQueryVariables({ + filters: resolvedFilters, + unresolvedReferenceVariablesByFilterId, + variables, + dateRange: searchedTimeRange, + getDashboardFilters: getFilterQueriesForSource, + }); const { granularityOverride, @@ -2603,6 +2634,7 @@ function DBDashboardPage({ onFilter={tileFilterHandlers.get(chart.id)} variables={expandedVariables} unavailableVariables={unavailableVariables} + variableWarnings={variableWarnings} unsatisfiedRequiredFilters={unsatisfiedRequiredFilters} onTimeRangeSelect={onTimeRangeSelect} showAlertAnnotations={showAlertAnnotations} @@ -2709,6 +2741,7 @@ function DBDashboardPage({ tileFilterHandlers, expandedVariables, unavailableVariables, + variableWarnings, unsatisfiedRequiredFilters, moveTargetContainers, handleMoveTileToGroup, diff --git a/packages/app/src/DashboardFilters.tsx b/packages/app/src/DashboardFilters.tsx index 453f6d12d9..2992bd10ec 100644 --- a/packages/app/src/DashboardFilters.tsx +++ b/packages/app/src/DashboardFilters.tsx @@ -14,6 +14,7 @@ import { isReferenceVariableFilter, isSqlQueryFilter, isStaticListFilter, + SQL_QUERY_FILTER_VALUES_SETTINGS, } from '@hyperdx/common-utils/dist/filters'; import { ReferenceVariableValues } from '@hyperdx/common-utils/dist/referenceVariables'; import { @@ -34,6 +35,7 @@ import { FilterEffect, getIncompatibleVariablesTooltip, getPendingVariablesTooltip, + getValuesCutOffTooltip, } from './components/DashboardFilterLabel'; import { FilterLinkToggle } from './components/FilterLinkToggle'; import { @@ -59,6 +61,8 @@ interface DashboardFilterSelectProps { * match any rows. */ pendingVariables?: string[]; + /** The values query was cut off at its time limit, so `values` may be incomplete. */ + isValuesCutOff?: boolean; } /** @@ -116,6 +120,7 @@ const DashboardFilterSelect = ({ isError, errorMessage, pendingVariables, + isValuesCutOff, }: DashboardFilterSelectProps) => { const valuesOrEmptyMemo = useMemo(() => values ?? [], [values]); const effect = getFilterEffect(filter); @@ -137,6 +142,14 @@ const DashboardFilterSelect = ({ testId={`dashboard-filter-pending-variable-${filter.name}`} /> )} + {isValuesCutOff && ( + + )} {isError && ( onSetFilterValue(filter.id, selection)} values={queriedFilterValues?.values} value={selectedValues} diff --git a/packages/app/src/components/DashboardFilterLabel.tsx b/packages/app/src/components/DashboardFilterLabel.tsx index c6a5020e5a..992043264c 100644 --- a/packages/app/src/components/DashboardFilterLabel.tsx +++ b/packages/app/src/components/DashboardFilterLabel.tsx @@ -29,6 +29,10 @@ export const getIncompatibleVariablesTooltip = ( }. Select a different source.`; }; +/** Explain a SQL query filter whose values query was cut off at its time limit. */ +export const getValuesCutOffTooltip = (seconds: number): string => + `The options query stopped after ${seconds} s, so this list may be incomplete. Narrow the query or add a LIMIT.`; + /** One of the caution icons a filter's label row can carry, with its tooltip. */ export const FilterCaution = ({ label, diff --git a/packages/app/src/components/DashboardFiltersModal/SqlQueryFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/SqlQueryFilterEditForm.tsx index fc084119e4..62b25e34a9 100644 --- a/packages/app/src/components/DashboardFiltersModal/SqlQueryFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/SqlQueryFilterEditForm.tsx @@ -3,6 +3,7 @@ import { UseFormSetValue, useFormState, useWatch } from 'react-hook-form'; import { getSqlQueryFilterSourceTables, SQL_QUERY_FILTER_SOURCE_KINDS, + SQL_QUERY_FILTER_VALUES_SETTINGS, SqlQueryFilterSourceTables, validateSqlQueryFilterTemplate, } from '@hyperdx/common-utils/dist/filters'; @@ -22,6 +23,7 @@ import { IconAlertTriangle, IconPlayerPlay } from '@tabler/icons-react'; import { useQueryClient } from '@tanstack/react-query'; import { ConnectionSelectControlled } from '@/components/ConnectionSelect'; +import { getValuesCutOffTooltip } from '@/components/DashboardFilterLabel'; import EmptyState from '@/components/EmptyState'; import { SourceSelectControlled } from '@/components/SourceSelect'; import { useResolvedReference } from '@/components/sourceSelectUtils'; @@ -368,6 +370,7 @@ const SqlQueryFilterPreview = ({ getDashboardFilters, }); const values = data.get(filter.id)?.values ?? []; + const isCutOff = data.get(filter.id)?.isCutOff ?? false; // While a re-run loads, the previous query's values stand in as placeholder // data, so isLoading alone would show them as this query's results. @@ -420,6 +423,13 @@ const SqlQueryFilterPreview = ({ ))} {notShown > 0 && `, and ${notShown} more`} + {isCutOff && ( + + {getValuesCutOffTooltip( + SQL_QUERY_FILTER_VALUES_SETTINGS.max_execution_time, + )} + + )} ); }; diff --git a/packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx b/packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx index 16974dff5e..85a5b6079f 100644 --- a/packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx +++ b/packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx @@ -7,6 +7,7 @@ import { renderHook } from '@testing-library/react'; import { getUnavailableVariablesMessage, + getVariableWarningsMessage, useExpandedSqlQueryVariables, } from '@/hooks/useExpandedSqlQueryVariables'; import { useSqlQueryFilterValues } from '@/hooks/useSqlQueryFilterValues'; @@ -43,7 +44,9 @@ const staticFilter: StaticListDashboardFilter = { const allRegion: ChartVariable = { name: 'region', values: [], all: true }; const mockResult = ( - result: { values: string[]; isLoading: boolean } | undefined, + result: + | { values: string[]; isLoading: boolean; isCutOff?: boolean } + | undefined, error?: string, ) => mockValues.mockReturnValue({ @@ -82,6 +85,22 @@ describe('useExpandedSqlQueryVariables', () => { expect(unavailableVariables.size).toBe(0); }); + it('warns about "All" expanded from a cut-off options list', () => { + mockResult({ values: ['eu-west'], isLoading: false, isCutOff: true }); + + const { variables, unavailableVariables, variableWarnings } = render([ + allRegion, + ]); + + expect(variables).toEqual([ + { name: 'region', values: ['eu-west'], all: true }, + ]); + expect(unavailableVariables.size).toBe(0); + expect(variableWarnings.get('region')).toBe( + '"All" on Region may be missing options: its options query stopped after 30 s.', + ); + }); + it('queries only SQL query filters with "All" selected', () => { mockResult(undefined); @@ -148,6 +167,28 @@ describe('useExpandedSqlQueryVariables', () => { }); }); +describe('getVariableWarningsMessage', () => { + it("joins the warnings for the tile's variables", () => { + const warnings = new Map([ + ['a', 'A may be incomplete.'], + ['b', 'B may be incomplete.'], + ]); + + expect( + getVariableWarningsMessage( + [ + { name: 'a', values: [] }, + { name: 'c', values: [] }, + ], + warnings, + ), + ).toBe('A may be incomplete.'); + expect( + getVariableWarningsMessage([{ name: 'c', values: [] }], warnings), + ).toBeUndefined(); + }); +}); + describe('getUnavailableVariablesMessage', () => { const unavailable = new Map([ ['a', { isLoading: true, message: 'Loading A.' }], diff --git a/packages/app/src/hooks/__tests__/useSqlQueryFilterValues.test.tsx b/packages/app/src/hooks/__tests__/useSqlQueryFilterValues.test.tsx index 69cd1d8ecb..88a67f596f 100644 --- a/packages/app/src/hooks/__tests__/useSqlQueryFilterValues.test.tsx +++ b/packages/app/src/hooks/__tests__/useSqlQueryFilterValues.test.tsx @@ -124,6 +124,25 @@ describe('useSqlQueryFilterValues', () => { expect(args.clickhouse_settings.timeout_overflow_mode).toBe('break'); }); + it('flags values from a request that took the whole time limit', async () => { + let now = 0; + const clock = jest.spyOn(Date, 'now').mockImplementation(() => now); + mockQuery.mockImplementation(async () => { + now += 30_100; + return { json: async () => ({ data: [{ value: 'prod' }] }) }; + }); + const { result } = renderFilters([filter()], []); + + await waitFor(() => expect(result.current.isFetching).toBe(false)); + clock.mockRestore(); + + expect(result.current.data.get('sql1')).toEqual({ + values: ['prod'], + isLoading: false, + isCutOff: true, + }); + }); + it('does not re-run a query that ignores the time range when it changes', async () => { const filters = [filter({ sqlTemplate: 'SELECT env FROM envs' })]; const { result, rerender } = renderHook( diff --git a/packages/app/src/hooks/useDashboardFilterValues.tsx b/packages/app/src/hooks/useDashboardFilterValues.tsx index db383efa78..eb370dc056 100644 --- a/packages/app/src/hooks/useDashboardFilterValues.tsx +++ b/packages/app/src/hooks/useDashboardFilterValues.tsx @@ -19,7 +19,15 @@ import { useStaticDashboardFilterValues } from './useStaticDashboardFilterValues export type DashboardFilterValuesResult = { /** Dropdown values keyed by `filter.id` */ - data: ReadonlyMap; + data: ReadonlyMap< + string, + { + values: string[]; + isLoading: boolean; + /** Set when the values query was cut off at its time limit. */ + isCutOff?: boolean; + } + >; /** Filter IDs whose values lookup failed, or never resolved. */ erroredFilterIds: ReadonlySet; /** Error messages, when known, for filters in `erroredFilterIds`. */ diff --git a/packages/app/src/hooks/useExpandedSqlQueryVariables.ts b/packages/app/src/hooks/useExpandedSqlQueryVariables.ts index 2bbe136fb8..0dc7aea3a8 100644 --- a/packages/app/src/hooks/useExpandedSqlQueryVariables.ts +++ b/packages/app/src/hooks/useExpandedSqlQueryVariables.ts @@ -10,6 +10,7 @@ import { } from '@hyperdx/common-utils/dist/types'; import { ALL_SELECTION_MAX_OPTIONS, + cutOffOptionsForAllMessage, expandAllSelections, tooManyOptionsForAllMessage, } from '@hyperdx/common-utils/dist/variableSelection'; @@ -39,6 +40,18 @@ export function getUnavailableVariablesMessage( return shown.map(({ message }) => message).join(' ') || undefined; } +/** The warnings for the variables a tile references, or undefined if none. */ +export function getVariableWarningsMessage( + tileVariables: ChartVariable[] | undefined, + variableWarnings: ReadonlyMap | undefined, +): string | undefined { + return ( + (tileVariables ?? []) + .flatMap(variable => variableWarnings?.get(variable.name) ?? []) + .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 @@ -63,6 +76,11 @@ export function useExpandedSqlQueryVariables({ variables: ChartVariable[] | undefined; /** Variables whose "All" can't be expanded, keyed by variable name. */ unavailableVariables: ReadonlyMap; + /** + * Warnings for variables whose "All" expanded from an options list that may + * be incomplete, keyed by variable name. Tiles still run. + */ + variableWarnings: ReadonlyMap; } { const allSelectedFilters = useMemo(() => { const allNames = new Set( @@ -93,6 +111,7 @@ export function useExpandedSqlQueryVariables({ return useMemo(() => { const optionsByVariableName = new Map(); const unavailableVariables = new Map(); + const variableWarnings = new Map(); for (const filter of allSelectedFilters) { const name = getFilterVariableName(filter) ?? ''; const unresolved = unresolvedReferenceVariablesByFilterId?.get(filter.id); @@ -121,12 +140,16 @@ export function useExpandedSqlQueryVariables({ }); } else { optionsByVariableName.set(name, result.values); + if (result.isCutOff) { + variableWarnings.set(name, cutOffOptionsForAllMessage(filter.name)); + } } } return { variables: variables && expandAllSelections(variables, optionsByVariableName), unavailableVariables, + variableWarnings, }; }, [ allSelectedFilters, diff --git a/packages/app/src/hooks/useSqlQueryFilterValues.tsx b/packages/app/src/hooks/useSqlQueryFilterValues.tsx index 44db0af423..29bde11304 100644 --- a/packages/app/src/hooks/useSqlQueryFilterValues.tsx +++ b/packages/app/src/hooks/useSqlQueryFilterValues.tsx @@ -8,6 +8,7 @@ import { renderSourceFiltersToSql } from '@hyperdx/common-utils/dist/core/render import { getSqlFilters, getSqlQueryFilterSourceTables, + isSqlQueryFilterValuesCutOff, renderSqlQueryFilterValuesQuery, SQL_QUERY_FILTER_VALUES_SETTINGS, toSqlQueryFilterValues, @@ -48,6 +49,13 @@ type ValuesCall = RenderedValuesQuery & { broadcastFilters: Filter[]; }; +/** A values query's result. */ +type QueriedValues = { + values: string[]; + /** The query was cut off at its time limit, so `values` may be incomplete. */ + isCutOff: boolean; +}; + export type DashboardState = { dateRange: [Date, Date]; /** The dashboard's variables and their current selections, if any */ @@ -194,7 +202,7 @@ export function useSqlQueryFilterValues({ const attribution = useMetadataQueryAttribution(); - const results: UseQueryResult[] = useQueries({ + const results: UseQueryResult[] = useQueries({ queries: calls.map(call => ({ queryKey: [SQL_QUERY_FILTER_VALUES_QUERY_KEY, ...valuesCallKey(call)], // Keep the last values while a new range or selection loads, rather than @@ -210,6 +218,7 @@ export function useSqlQueryFilterValues({ variables, dateRange, }); + const startedAt = Date.now(); const result = (await getClickhouseClient({ attribution }) .query<'JSON'>({ query: sql, @@ -220,13 +229,19 @@ export function useSqlQueryFilterValues({ clickhouse_settings: SQL_QUERY_FILTER_VALUES_SETTINGS, }) .then(res => res.json())) as ResponseJSON<{ value: string | null }>; - return toSqlQueryFilterValues(result.data ?? []); + return { + values: toSqlQueryFilterValues(result.data ?? []), + isCutOff: isSqlQueryFilterValuesCutOff(Date.now() - startedAt), + }; }, })), }); return useMemo(() => { - const data = new Map(); + const data = new Map< + string, + { values: string[]; isLoading: boolean; isCutOff?: boolean } + >(); const erroredFilterIds = new Set(); const filterErrorMessages = new Map(); @@ -234,8 +249,9 @@ export function useSqlQueryFilterValues({ const call = calls[index]; if (!call) return; data.set(call.filterId, { - values: result.data ?? [], + values: result.data?.values ?? [], isLoading: result.isLoading, + ...(result.data?.isCutOff ? { isCutOff: true } : {}), }); if (result.isError) { erroredFilterIds.add(call.filterId); diff --git a/packages/common-utils/src/__tests__/filters.test.ts b/packages/common-utils/src/__tests__/filters.test.ts index 035792789d..edb86436b2 100644 --- a/packages/common-utils/src/__tests__/filters.test.ts +++ b/packages/common-utils/src/__tests__/filters.test.ts @@ -26,6 +26,7 @@ import { isFilterVariableEnabled, isQueryExpressionFilter, isRenderablePinnedFilter, + isSqlQueryFilterValuesCutOff, mergeAdhocConditions, parseQuery, renderSqlQueryFilterValuesQuery, @@ -1423,6 +1424,13 @@ describe('filters', () => { }); }); + describe('isSqlQueryFilterValuesCutOff', () => { + it('is true once the request took the whole time limit', () => { + expect(isSqlQueryFilterValuesCutOff(30_020)).toBe(true); + expect(isSqlQueryFilterValuesCutOff(29_900)).toBe(false); + }); + }); + describe('toSqlQueryFilterValues', () => { it('drops nulls, empty strings, and repeats, keeping query order', () => { expect( diff --git a/packages/common-utils/src/filters.ts b/packages/common-utils/src/filters.ts index bb5d193ab9..67952b075c 100644 --- a/packages/common-utils/src/filters.ts +++ b/packages/common-utils/src/filters.ts @@ -1023,6 +1023,15 @@ export const SQL_QUERY_FILTER_VALUES_SETTINGS = { timeout_overflow_mode: 'break', } satisfies ClickHouseSettings; +/** + * Whether a values query was stopped at `max_execution_time`, so it returned + * only the values read so far. ClickHouse doesn't flag a cut-off result, and + * the elapsed time it reports after one is near zero, so this goes by how long + * the request took. + */ +export const isSqlQueryFilterValuesCutOff = (requestMs: number): boolean => + requestMs >= SQL_QUERY_FILTER_VALUES_SETTINGS.max_execution_time * 1000; + /** Rows from the values query, without nulls or repeats, in query order. */ export const toSqlQueryFilterValues = ( rows: { value: string | null }[], diff --git a/packages/common-utils/src/variableSelection.ts b/packages/common-utils/src/variableSelection.ts index 65d43b5316..0d04f4bda1 100644 --- a/packages/common-utils/src/variableSelection.ts +++ b/packages/common-utils/src/variableSelection.ts @@ -1,3 +1,4 @@ +import { SQL_QUERY_FILTER_VALUES_SETTINGS } from '@/filters'; import { type ChartVariable, DASHBOARD_STATIC_FILTER_MAX_OPTIONS, @@ -60,3 +61,8 @@ 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".`; + +/** Why "All" may be missing options: its options query was cut off. */ +export const cutOffOptionsForAllMessage = (filterName: string) => + `"All" on ${filterName} may be missing options: its options query stopped ` + + `after ${SQL_QUERY_FILTER_VALUES_SETTINGS.max_execution_time} s.`;