Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/dashboard-filter-all-option-sql-query.md
Original file line number Diff line number Diff line change
@@ -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. 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.
5 changes: 5 additions & 0 deletions packages/api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down
80 changes: 80 additions & 0 deletions packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
);
});
});
});
122 changes: 122 additions & 0 deletions packages/api/src/mcp/__tests__/dashboards/sqlQueryAllValues.test.ts
Original file line number Diff line number Diff line change
@@ -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([]);
});
});
5 changes: 3 additions & 2 deletions packages/api/src/mcp/prompts/dashboards/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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(<expression>, $<variableName>).

Expand Down Expand Up @@ -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) ==
Expand Down
23 changes: 22 additions & 1 deletion packages/api/src/mcp/tools/dashboards/queryTile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import Dashboard from '@/models/dashboard';
import { convertToExternalDashboard } from '@/routers/external-api/v2/utils/dashboards';
import { objectIdSchema } from '@/utils/zod';

import {
expandSqlQueryAllVariables,
getTileAllWarnings,
} from './sqlQueryAllValues';
import {
getRawSqlTileMacroWarnings,
getTileVariableWarnings,
Expand Down Expand Up @@ -98,6 +102,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,
Expand All @@ -112,7 +128,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
Expand All @@ -121,6 +137,11 @@ export function registerQueryTile({
const warnings = [
...getRawSqlTileMacroWarnings([tile]),
...getTileVariableWarnings([tile], externalDashboard.filters),
...getTileAllWarnings(
tile,
expandedVariables.variables,
expandedVariables.warnings,
),
];
if (
warnings.length > 0 &&
Expand Down
19 changes: 18 additions & 1 deletion packages/api/src/mcp/tools/dashboards/queryTiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import {
import type { ExternalDashboardTileWithId } from '@/utils/zod';
import { objectIdSchema } from '@/utils/zod';

import {
expandSqlQueryAllVariables,
getTileAllWarnings,
} from './sqlQueryAllValues';
import {
getRawSqlTileMacroWarnings,
getTileVariableWarnings,
Expand Down Expand Up @@ -222,7 +226,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
Expand Down Expand Up @@ -336,6 +352,7 @@ export function registerQueryTiles({
const warnings = [
...getRawSqlTileMacroWarnings([tile]),
...getTileVariableWarnings([tile], externalDashboard.filters),
...getTileAllWarnings(tile, variables, expanded.warnings),
];
return {
...base,
Expand Down
7 changes: 7 additions & 0 deletions packages/api/src/mcp/tools/dashboards/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ' +
Expand Down
Loading
Loading