From db4e7ba67a4e05972e4d7d74e1510c6cf4eb2697 Mon Sep 17 00:00:00 2001 From: Karl Power <85935352+karl-power@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:54:47 +0100 Subject: [PATCH 01/55] chore: upgrade ClickHouse to 26.10 (#3624) ## Summary Upgrades ClickHouse from 26.8.36.3 to 26.10.3.7 and updates the tests that assumed the 26.8 TimeSeries layout. Needed for PromQL label lookups through ClickHouse's Prometheus HTTP API (26.9+). - Pins `26.10.3.7` in the four compose files (incl. e2e) and the all-in-one `Dockerfile`. - `metadata.int.test.ts`: pins the `getTimeSeriesTableColumns` tables to `version = 7` (26.10 defaults to version 8, which moves `min_time`/`max_time` out of the tags table), expects the renamed `metric_family` column, and adds `getTimeSeriesTableVersion` coverage. - `timeseriesEngine.int.test.ts`: the version 8 suite fails instead of silently skipping. - `seed-clickhouse.ts`: the e2e PromQL seed writes to `samples` (new tables have no `time_series` column). No production code changes were needed. On an existing volume, `system.metric_log` history moves to `system.metric_log_0`. Local otel smoke tests need `clickhouse-client` 26.9+. ### References - Linear Issue: part of HDX-5420 --- .changeset/upgrade-clickhouse-26-10.md | 11 ++++ docker-compose.ci.yml | 2 +- docker-compose.dev.yml | 2 +- docker-compose.yml | 2 +- docker/hyperdx/Dockerfile | 2 +- .../__tests__/timeseriesEngine.int.test.ts | 40 +++++--------- packages/app/tests/e2e/docker-compose.yml | 2 +- packages/app/tests/e2e/seed-clickhouse.ts | 2 +- .../src/__tests__/metadata.int.test.ts | 53 +++++++++++++++++-- 9 files changed, 80 insertions(+), 36 deletions(-) create mode 100644 .changeset/upgrade-clickhouse-26-10.md diff --git a/.changeset/upgrade-clickhouse-26-10.md b/.changeset/upgrade-clickhouse-26-10.md new file mode 100644 index 0000000000..54b5f8388e --- /dev/null +++ b/.changeset/upgrade-clickhouse-26-10.md @@ -0,0 +1,11 @@ +--- +'@hyperdx/api': minor +--- + +chore: upgrade bundled ClickHouse to 26.10.3.7 + +The all-in-one image and the Docker Compose files now use +`clickhouse/clickhouse-server:26.10.3.7-alpine`. New TimeSeries tables default +to schema version 8, which keeps each series' time range in a separate inner +table; existing tables keep their layout. `system.metric_log` switches to the +bucketed schema, and rows from before the upgrade move to `system.metric_log_0`. diff --git a/docker-compose.ci.yml b/docker-compose.ci.yml index 814e45980f..a5051cd1cf 100644 --- a/docker-compose.ci.yml +++ b/docker-compose.ci.yml @@ -22,7 +22,7 @@ services: depends_on: - ch-server ch-server: - image: clickhouse/clickhouse-server:26.8.36.3-alpine + image: clickhouse/clickhouse-server:26.10.3.7-alpine environment: # default settings CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: 1 diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 01ff8e4554..335054d479 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -112,7 +112,7 @@ services: hdx.dev.service: clickhouse hdx.dev.port: '${HDX_DEV_CH_HTTP_PORT:-8123}' hdx.dev.url: 'http://localhost:${HDX_DEV_CH_HTTP_PORT:-8123}' - image: clickhouse/clickhouse-server:26.8.36.3-alpine + image: clickhouse/clickhouse-server:26.10.3.7-alpine ports: - '${HDX_DEV_CH_HTTP_PORT:-8123}:8123' # http api - '${HDX_DEV_CH_NATIVE_PORT:-9000}:9000' # native diff --git a/docker-compose.yml b/docker-compose.yml index 2f8fdf7f7f..4e9530d0cd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -109,7 +109,7 @@ services: - ch-server - db ch-server: - image: clickhouse/clickhouse-server:26.8.36.3-alpine + image: clickhouse/clickhouse-server:26.10.3.7-alpine # WARNING: Exposing the database port will make it accessible from outside the container, # potentially allowing unauthorized access. If you uncomment the ports below, # ensure to secure your database (e.g., with strong authentication, proper network rules, and firewalls). diff --git a/docker/hyperdx/Dockerfile b/docker/hyperdx/Dockerfile index 4aa309c0ac..749c594d03 100644 --- a/docker/hyperdx/Dockerfile +++ b/docker/hyperdx/Dockerfile @@ -8,7 +8,7 @@ # - Otel Collector (otelcol) ARG NODE_VERSION=22.23.4 -ARG CLICKHOUSE_VERSION=26.8.36.3 +ARG CLICKHOUSE_VERSION=26.10.3.7 ARG OTEL_COLLECTOR_VERSION=0.155.0 ARG OTEL_COLLECTOR_CORE_VERSION=1.61.0 diff --git a/packages/api/src/controllers/__tests__/timeseriesEngine.int.test.ts b/packages/api/src/controllers/__tests__/timeseriesEngine.int.test.ts index 08985c2c57..4428078351 100644 --- a/packages/api/src/controllers/__tests__/timeseriesEngine.int.test.ts +++ b/packages/api/src/controllers/__tests__/timeseriesEngine.int.test.ts @@ -505,13 +505,10 @@ describe('timeseriesEngine controller', () => { }); // Schema version 8 (the default from ClickHouse 26.10) moved min_time and - // max_time out of the tags table into a separate time ranges table. Older - // servers don't know the `version` setting, so these run only where the - // table can be created. + // max_time out of the tags table into a separate time ranges table. describe('table of schema version 8 (time ranges table)', () => { const V8_TABLE = 'test_ts_label_values_v8'; const V8_NO_RANGES_TABLE = 'test_ts_label_values_v8_no_ranges'; - let supported = true; const v8LabelValues = ( args: Partial[0]> & { @@ -520,23 +517,18 @@ describe('timeseriesEngine controller', () => { ) => labelValues({ tableName: V8_TABLE, ...args }); beforeAll(async () => { - try { - await seedTimeSeriesTagsTable({ - table: V8_TABLE, - series: SERIES, - withSamples: true, - timeRanges: true, - }); - await seedTimeSeriesTagsTable({ - table: V8_NO_RANGES_TABLE, - series: SERIES, - storeTimeBounds: false, - timeRanges: true, - }); - } catch (e) { - if (!/Unknown setting 'version'/.test(String(e))) throw e; - supported = false; - } + await seedTimeSeriesTagsTable({ + table: V8_TABLE, + series: SERIES, + withSamples: true, + timeRanges: true, + }); + await seedTimeSeriesTagsTable({ + table: V8_NO_RANGES_TABLE, + series: SERIES, + storeTimeBounds: false, + timeRanges: true, + }); }); afterAll(async () => { @@ -546,7 +538,6 @@ describe('timeseriesEngine controller', () => { }); it('scopes label values to the window through the time ranges table', async () => { - if (!supported) return; expect( await v8LabelValues({ labelName: 'job', @@ -557,7 +548,6 @@ describe('timeseriesEngine controller', () => { }); it('applies lone bounds against the time ranges', async () => { - if (!supported) return; expect( await v8LabelValues({ labelName: '__name__', @@ -573,7 +563,6 @@ describe('timeseriesEngine controller', () => { }); it('returns nothing for a window no series covers', async () => { - if (!supported) return; expect( await v8LabelValues({ labelName: '__name__', @@ -584,7 +573,6 @@ describe('timeseriesEngine controller', () => { }); it('evaluates match[] and narrows it by the window', async () => { - if (!supported) return; expect( await v8LabelValues({ labelName: 'job', @@ -602,7 +590,6 @@ describe('timeseriesEngine controller', () => { }); it('scopes label names to the window and the selector', async () => { - if (!supported) return; const names = ( args: Partial[0]> = {}, ) => @@ -627,7 +614,6 @@ describe('timeseriesEngine controller', () => { }); it('rejects match[] without a time ranges table, and ignores the bounds', async () => { - if (!supported) return; await expect( labelValues({ tableName: V8_NO_RANGES_TABLE, diff --git a/packages/app/tests/e2e/docker-compose.yml b/packages/app/tests/e2e/docker-compose.yml index 986f3d9c58..6016d24e55 100644 --- a/packages/app/tests/e2e/docker-compose.yml +++ b/packages/app/tests/e2e/docker-compose.yml @@ -15,7 +15,7 @@ services: memory: 512M cpus: '0.5' ch-server: - image: clickhouse/clickhouse-server:26.8.36.3-alpine + image: clickhouse/clickhouse-server:26.10.3.7-alpine ports: - ${HDX_E2E_CH_PORT:-20500}:8123 # http api - ${HDX_E2E_CH_NATIVE_PORT:-20600}:9000 # native diff --git a/packages/app/tests/e2e/seed-clickhouse.ts b/packages/app/tests/e2e/seed-clickhouse.ts index f96e4fe916..99cc66c7f3 100644 --- a/packages/app/tests/e2e/seed-clickhouse.ts +++ b/packages/app/tests/e2e/seed-clickhouse.ts @@ -1175,7 +1175,7 @@ async function insertPromqlMetric( .join('\n UNION ALL\n '); await client.query(` - INSERT INTO ${table} (metric_name, tags, time_series) + INSERT INTO ${table} (metric_name, tags, samples) ${rows} `); } diff --git a/packages/common-utils/src/__tests__/metadata.int.test.ts b/packages/common-utils/src/__tests__/metadata.int.test.ts index 55853a7421..0e9133bc87 100644 --- a/packages/common-utils/src/__tests__/metadata.int.test.ts +++ b/packages/common-utils/src/__tests__/metadata.int.test.ts @@ -1159,14 +1159,17 @@ describe('Metadata Integration Tests', () => { clickhouse_settings: { allow_experimental_time_series_table: 1 }, }); + // Pinned to version 7: from version 8 (the default since ClickHouse 26.10) + // min_time/max_time live in a separate time ranges table, and + // store_min_time_and_max_time is rejected. beforeAll(async () => { await timeSeriesCommand(`DROP TABLE IF EXISTS default.${boundedTable}`); await timeSeriesCommand(`DROP TABLE IF EXISTS default.${unboundedTable}`); await timeSeriesCommand( - `CREATE TABLE default.${boundedTable} ENGINE = TimeSeries`, + `CREATE TABLE default.${boundedTable} ENGINE = TimeSeries SETTINGS version = 7`, ); await timeSeriesCommand( - `CREATE TABLE default.${unboundedTable} ENGINE = TimeSeries SETTINGS store_min_time_and_max_time = 0`, + `CREATE TABLE default.${unboundedTable} ENGINE = TimeSeries SETTINGS store_min_time_and_max_time = 0, version = 7`, ); }); @@ -1219,7 +1222,7 @@ describe('Metadata Integration Tests', () => { }); it.each([ - ['Metrics', ['metric_family_name', 'type', 'unit', 'help']], + ['Metrics', ['metric_family', 'type', 'unit', 'help']], ['Data', ['id', 'timestamp', 'value']], ] as const)( 'describes the %s inner table', @@ -1307,6 +1310,50 @@ describe('Metadata Integration Tests', () => { }); }); + // The version decides which samples column a query reads (`samples` from + // version 3, `time_series` before), so a version read as 0 silently breaks + // queries on new tables. + describe('getTimeSeriesTableVersion', () => { + const defaultTable = 'test_ts_version_default'; + const v7Table = 'test_ts_version_7'; + + const timeSeriesCommand = (query: string) => + client.command({ + query, + clickhouse_settings: { allow_experimental_time_series_table: 1 }, + }); + + const version = (tableName: string) => + new Metadata(hdxClient, new MetadataCache()).getTimeSeriesTableVersion({ + connectionId: 'test_connection', + databaseName: 'default', + tableName, + }); + + beforeAll(async () => { + await timeSeriesCommand( + `CREATE OR REPLACE TABLE default.${defaultTable} ENGINE = TimeSeries`, + ); + await timeSeriesCommand( + `CREATE OR REPLACE TABLE default.${v7Table} ENGINE = TimeSeries SETTINGS version = 7`, + ); + }); + + afterAll(async () => { + await timeSeriesCommand(`DROP TABLE IF EXISTS default.${defaultTable}`); + await timeSeriesCommand(`DROP TABLE IF EXISTS default.${v7Table}`); + }); + + it('reads the version from the table definition', async () => { + expect(await version(defaultTable)).toBe(8); + expect(await version(v7Table)).toBe(7); + }); + + it('answers 0 for a table that does not exist', async () => { + expect(await version('test_ts_version_missing')).toBe(0); + }); + }); + describe('getTimeSeriesTables', () => { const database = 'test_ts_discovery'; From ac913ceb3f52ce522cf9138fa90304dd22f46d76 Mon Sep 17 00:00:00 2001 From: Karl Power <85935352+karl-power@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:56:35 +0100 Subject: [PATCH 02/55] feat: Add a PromQL backend setting to ClickHouse PromQL sources (#3601) --- .changeset/promql-source-backend.md | 7 + packages/api/openapi.json | 10 + .../api/src/__tests__/setupDefaults.test.ts | 2 + .../src/controllers/__tests__/promql.test.ts | 55 +++++ .../__tests__/promqlBackend.test.ts | 198 ++++++++++++++++++ packages/api/src/controllers/promql.ts | 169 ++++++++++++--- .../api/src/controllers/timeseriesEngine.ts | 13 +- .../mcp/__tests__/promqlSources.int.test.ts | 60 ++++++ packages/api/src/mcp/tools/sources/schemas.ts | 15 +- packages/api/src/models/source.ts | 2 + .../api/__tests__/connections.int.test.ts | 127 ++++++++++- .../api/__tests__/prometheus.int.test.ts | 188 ++++++++++++++++- .../routers/api/__tests__/sources.int.test.ts | 80 +++++++ packages/api/src/routers/api/connections.ts | 32 +++ packages/api/src/routers/api/prometheus.ts | 21 ++ .../__tests__/sources-crud.int.test.ts | 45 ++++ .../src/routers/external-api/v2/sources.ts | 5 + packages/app/src/__tests__/connection.test.ts | 54 +++++ .../app/src/components/OnboardingModal.tsx | 8 + .../SourceForm/PromqlTableModelForm.tsx | 39 +++- .../Sources/SourceForm/SourceForm.tsx | 3 +- .../Sources/SourceForm/TableModelForm.tsx | 10 +- .../Sources/SourceForm/constants.ts | 15 +- .../components/Sources/SourceForm/types.ts | 2 + .../__tests__/OnboardingModal.test.tsx | 28 +++ .../__tests__/PromqlTableModelForm.test.tsx | 95 +++++++++ packages/app/src/connection.ts | 20 ++ .../common-utils/src/__tests__/types.test.ts | 37 ++++ packages/common-utils/src/types.ts | 17 ++ 29 files changed, 1311 insertions(+), 46 deletions(-) create mode 100644 .changeset/promql-source-backend.md create mode 100644 packages/api/src/controllers/__tests__/promqlBackend.test.ts create mode 100644 packages/app/src/__tests__/connection.test.ts create mode 100644 packages/app/src/components/__tests__/PromqlTableModelForm.test.tsx diff --git a/.changeset/promql-source-backend.md b/.changeset/promql-source-backend.md new file mode 100644 index 0000000000..41fc3063b3 --- /dev/null +++ b/.changeset/promql-source-backend.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': patch +'@hyperdx/app': patch +'@hyperdx/common-utils': patch +--- + +feat: Choose how a PromQL source on ClickHouse is evaluated (the Prometheus HTTP API or the `prometheusQuery` table functions) instead of probing the server on every query. Without a choice the server is still probed, but the answer is now kept for 5 minutes. A source set to the HTTP API against a server that does not serve it fails with a clear error. Onboarding pins a PromQL source it detects to the HTTP API when the server serves it. diff --git a/packages/api/openapi.json b/packages/api/openapi.json index 4c38a71948..a2c7b3faea 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -5748,6 +5748,16 @@ "description": "Floor for the auto-inferred chart granularity, and the scrape interval that `$__rate_interval` is computed from. Set it to the Prometheus scrape interval so a short time range does not produce buckets smaller than that interval. Only constrains \"Auto\" granularity; an explicit granularity picked on a tile is never overridden. Omit for no minimum. Uses the SQL interval format (a positive integer followed by second, minute, hour, or day), not the short form of the materialized view granularity fields.", "pattern": "^\\d+ (second|minute|hour|day)$", "example": "1 minute" + }, + "promqlBackend": { + "type": "string", + "enum": [ + "auto", + "clickhouse-http", + "table-function" + ], + "description": "How PromQL is evaluated on a ClickHouse connection. \"clickhouse-http\" uses ClickHouse's Prometheus HTTP API, which needs ClickHouse 26.6+ with the prometheus_api_v1 handler configured; queries fail with an error when the server does not serve it. \"table-function\" uses the prometheusQuery table functions. \"auto\" (the default when omitted) checks the server and prefers the HTTP API. Ignored when the connection is a Prometheus-compatible endpoint.", + "example": "auto" } } }, diff --git a/packages/api/src/__tests__/setupDefaults.test.ts b/packages/api/src/__tests__/setupDefaults.test.ts index f7b42bc64f..a94af81b38 100644 --- a/packages/api/src/__tests__/setupDefaults.test.ts +++ b/packages/api/src/__tests__/setupDefaults.test.ts @@ -19,6 +19,7 @@ jest.mock('@/config', () => ({ connection: 'Local ClickHouse', from: { databaseName: 'default', tableName: 'metrics_ts' }, timestampValueExpression: 'timestamp', + promqlBackend: 'clickhouse-http', }, ]), get IS_PROMQL_ENABLED() { @@ -73,6 +74,7 @@ describe('setupTeamDefaults', () => { kind: SourceKind.Promql, connection: 'conn-1', from: { databaseName: 'default', tableName: 'metrics_ts' }, + promqlBackend: 'clickhouse-http', }), ); }); diff --git a/packages/api/src/controllers/__tests__/promql.test.ts b/packages/api/src/controllers/__tests__/promql.test.ts index 770a55c275..11a706c47a 100644 --- a/packages/api/src/controllers/__tests__/promql.test.ts +++ b/packages/api/src/controllers/__tests__/promql.test.ts @@ -1,5 +1,6 @@ import { buildPrometheusRequest, + CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, PROMETHEUS_MAX_RESPONSE_BYTES, runPromqlQuery, } from '@/controllers/promql'; @@ -128,6 +129,60 @@ describe('runPromqlQuery', () => { }); }); + describe('when ClickHouse does not serve the Prometheus HTTP API', () => { + it('names the missing handler when the server answers a plain-text 404', async () => { + mockFetch.mockResolvedValueOnce( + new Response('There is no handle /prometheus/api/v1/query', { + status: 404, + }), + ); + + await expect( + runPromqlQuery(clickhouseHttp, instant), + ).rejects.toMatchObject({ + message: CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, + category: 'user', + }); + }); + + it("reports the handler's own failure by its message", async () => { + respond(400, { + status: 'error', + errorType: 'bad_data', + error: 'table default.metrics does not exist', + }); + + await expect( + runPromqlQuery(clickhouseHttp, instant), + ).rejects.toMatchObject({ + message: 'table default.metrics does not exist', + category: 'user', + }); + }); + + it('reports a 404 as a missing handler whatever its body', async () => { + respond(404, { status: 'error', errorType: 'not_found', error: 'nope' }); + + await expect( + runPromqlQuery(clickhouseHttp, instant), + ).rejects.toMatchObject({ + message: CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, + category: 'user', + }); + }); + + it('leaves a 404 from a Prometheus endpoint to its status', async () => { + mockFetch.mockResolvedValueOnce( + new Response('page not found', { status: 404 }), + ); + + await expect(runPromqlQuery(prometheus, instant)).rejects.toMatchObject({ + message: + 'Prometheus at http://prom:9090/api/v1/query returned HTTP 404', + }); + }); + }); + it('gives each query on one ClickHouse backend its own query ID', async () => { respond(200, emptyVector); respond(200, emptyVector); diff --git a/packages/api/src/controllers/__tests__/promqlBackend.test.ts b/packages/api/src/controllers/__tests__/promqlBackend.test.ts new file mode 100644 index 0000000000..99e8af0567 --- /dev/null +++ b/packages/api/src/controllers/__tests__/promqlBackend.test.ts @@ -0,0 +1,198 @@ +import type { PromqlSourceBackend } from '@hyperdx/common-utils/dist/types'; + +import { + clearBackendProbeCache, + resolveClickhouseQueryBackend, +} from '@/controllers/promql'; +import { connectionSupportsPrometheusHttpApi } from '@/controllers/timeseriesEngine'; + +jest.mock('@/controllers/timeseriesEngine', () => ({ + ...jest.requireActual('@/controllers/timeseriesEngine'), + connectionSupportsPrometheusHttpApi: jest.fn(), +})); + +const mockFetch = jest.mocked(global.fetch); +const mockVersionCheck = jest.mocked(connectionSupportsPrometheusHttpApi); + +const handlerAnswer = () => + new Response(JSON.stringify({ status: 'success', data: 'up' })); +const noHandlerAnswer = () => + new Response('There is no handle /prometheus/api/v1/format_query', { + status: 404, + }); + +const target = ( + host = 'http://ch:8123', + promqlBackend?: PromqlSourceBackend, +) => ({ + connection: { id: 'conn-1', host, username: 'default', password: '' }, + databaseName: 'db', + tableName: 'ts', + promqlBackend, +}); + +const resolveKind = async ( + host?: string, + promqlBackend?: PromqlSourceBackend, +) => { + const backend = await resolveClickhouseQueryBackend( + // @ts-expect-error mock connection carries only the fields the resolver reads + target(host, promqlBackend), + ); + return backend.kind; +}; + +describe('resolveClickhouseQueryBackend', () => { + beforeEach(() => { + clearBackendProbeCache(); + mockVersionCheck.mockReset(); + mockVersionCheck.mockResolvedValue(true); + mockFetch.mockReset(); + }); + + describe('probe cache', () => { + it('probes the handler once and keeps the answer', async () => { + mockFetch.mockResolvedValueOnce(handlerAnswer()); + + await expect(resolveKind()).resolves.toBe('clickhouse-http'); + await expect(resolveKind()).resolves.toBe('clickhouse-http'); + + expect(mockFetch).toHaveBeenCalledTimes(1); + expect(String(mockFetch.mock.calls[0][0])).toContain( + '/prometheus/api/v1/format_query', + ); + expect(mockVersionCheck).toHaveBeenCalledTimes(1); + }); + + it('keeps "no handler" so a stock server is not probed on every query', async () => { + mockFetch.mockResolvedValueOnce(noHandlerAnswer()); + + await expect(resolveKind()).resolves.toBe('table-function'); + await expect(resolveKind()).resolves.toBe('table-function'); + + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + + it('keeps a server that is too old without probing the handler', async () => { + mockVersionCheck.mockResolvedValue(false); + + await expect(resolveKind()).resolves.toBe('table-function'); + await expect(resolveKind()).resolves.toBe('table-function'); + + expect(mockVersionCheck).toHaveBeenCalledTimes(1); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it('does not keep an unreadable server version', async () => { + mockVersionCheck.mockResolvedValueOnce(undefined); + mockFetch.mockResolvedValueOnce(handlerAnswer()); + + await expect(resolveKind()).resolves.toBe('table-function'); + await expect(resolveKind()).resolves.toBe('clickhouse-http'); + + expect(mockVersionCheck).toHaveBeenCalledTimes(2); + }); + + it('does not keep a probe that failed to reach the server', async () => { + mockFetch.mockRejectedValueOnce(new Error('ECONNREFUSED')); + mockFetch.mockResolvedValueOnce(handlerAnswer()); + + await expect(resolveKind()).resolves.toBe('table-function'); + await expect(resolveKind()).resolves.toBe('clickhouse-http'); + + expect(mockFetch).toHaveBeenCalledTimes(2); + }); + + it("does not keep an answer that says nothing about the handler, like a proxy's 502", async () => { + mockFetch.mockResolvedValueOnce( + new Response('Bad gateway', { status: 502 }), + ); + mockFetch.mockResolvedValueOnce(handlerAnswer()); + + await expect(resolveKind()).resolves.toBe('table-function'); + await expect(resolveKind()).resolves.toBe('clickhouse-http'); + + expect(mockFetch).toHaveBeenCalledTimes(2); + }); + + it('probes again once the answer has expired', async () => { + const now = jest.spyOn(Date, 'now'); + try { + mockFetch.mockImplementation(async () => handlerAnswer()); + + now.mockReturnValue(1_000); + await resolveKind(); + now.mockReturnValue(1_000 + 5 * 60_000 - 1); + await resolveKind(); + expect(mockFetch).toHaveBeenCalledTimes(1); + + now.mockReturnValue(1_000 + 5 * 60_000); + await resolveKind(); + expect(mockFetch).toHaveBeenCalledTimes(2); + } finally { + now.mockRestore(); + } + }); + + it('keeps a separate answer for each host of the same connection', async () => { + mockFetch.mockResolvedValueOnce(noHandlerAnswer()); + mockFetch.mockResolvedValueOnce(handlerAnswer()); + + await expect(resolveKind('http://old:8123')).resolves.toBe( + 'table-function', + ); + await expect(resolveKind('http://new:8123')).resolves.toBe( + 'clickhouse-http', + ); + + expect(mockFetch).toHaveBeenCalledTimes(2); + }); + + it('shares one probe between concurrent queries', async () => { + mockFetch.mockResolvedValueOnce(handlerAnswer()); + + await expect( + Promise.all([resolveKind(), resolveKind()]), + ).resolves.toEqual(['clickhouse-http', 'clickhouse-http']); + + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + }); + + describe('source setting', () => { + it.each([ + ['clickhouse-http', 'clickhouse-http'], + ['table-function', 'table-function'], + ] as const)( + 'takes %s at its word, without a version check or probe', + async (setting, kind) => { + await expect(resolveKind(undefined, setting)).resolves.toBe(kind); + + expect(mockVersionCheck).not.toHaveBeenCalled(); + expect(mockFetch).not.toHaveBeenCalled(); + }, + ); + + it.each([[undefined], ['auto' as const]])( + 'probes when the setting is %s', + async setting => { + mockFetch.mockResolvedValueOnce(handlerAnswer()); + + await expect(resolveKind(undefined, setting)).resolves.toBe( + 'clickhouse-http', + ); + + expect(mockFetch).toHaveBeenCalledTimes(1); + }, + ); + + it('ignores a kept probe answer once the source names a backend', async () => { + mockFetch.mockResolvedValueOnce(handlerAnswer()); + await resolveKind(); + + await expect(resolveKind(undefined, 'table-function')).resolves.toBe( + 'table-function', + ); + }); + }); +}); diff --git a/packages/api/src/controllers/promql.ts b/packages/api/src/controllers/promql.ts index e68d9a084b..3e687c0b20 100644 --- a/packages/api/src/controllers/promql.ts +++ b/packages/api/src/controllers/promql.ts @@ -3,9 +3,15 @@ import { buildQueryId, } from '@hyperdx/common-utils/dist/clickhouse'; import { getCurrentQueryAttribution } from '@hyperdx/common-utils/dist/clickhouse/node'; +import { MetadataCache } from '@hyperdx/common-utils/dist/core/metadata'; import type { PromqlQuery } from '@hyperdx/common-utils/dist/core/promqlChart'; import { parseJSON } from '@hyperdx/common-utils/dist/core/utils'; -import { SourceKind, type SQLInterval } from '@hyperdx/common-utils/dist/types'; +import { + type PromqlSourceBackend, + SourceKind, + type SQLInterval, +} from '@hyperdx/common-utils/dist/types'; +import { trace } from '@opentelemetry/api'; import { z } from 'zod'; import { ClickhouseClient } from '@/clickhouse'; @@ -160,11 +166,24 @@ const SERVER_ERROR_TYPES = new Set(['timeout', 'canceled', 'unavailable']); const labelListSchema = z.array(z.string()); +/** + * What a user is told when a source set to the Prometheus HTTP API reaches a + * ClickHouse server that does not serve it. Without it they would see a bare + * 404 from a path they never chose. + */ +export const CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE = + "This ClickHouse connection does not serve the Prometheus HTTP API. Enable the prometheus_api_v1 HTTP handler on the server, or set the source's PromQL backend to Auto."; + /** * GETs a Prometheus API path from a Prometheus-compatible endpoint and returns * the response's `data`, checked against `dataSchema`. Errors name only the * origin and path: the host may carry credentials in its userinfo or query * string. + * + * `handlerMissingMessage` is for ClickHouse's own Prometheus API: a 404 there + * means the handler is not configured (the handler itself answers failures + * with a 400), which is reported with this message as a user error instead of + * by its status. */ async function fetchPrometheusData( host: string, @@ -173,6 +192,7 @@ async function fetchPrometheusData( dataSchema: T, signal?: AbortSignal, headers?: Record, + handlerMissingMessage?: string, ): Promise> { const request = buildPrometheusRequest(host, path, params, headers); const { redactedTarget } = request; @@ -193,6 +213,11 @@ async function fetchPrometheusData( ); } + if (handlerMissingMessage && resp.status === 404) { + await resp.body?.cancel().catch(() => {}); + throw new PromQLQueryError(handlerMissingMessage, 'user'); + } + let text: string; try { text = await readBoundedBody(resp, PROMETHEUS_MAX_RESPONSE_BYTES); @@ -319,6 +344,8 @@ type PromqlTarget = { tableName: string; /** The source's scrape interval floor, e.g. "1 minute". */ minAutoGranularity?: SQLInterval; + /** How the source is evaluated on ClickHouse; unset means `auto`. */ + promqlBackend?: PromqlSourceBackend; }; /** @@ -356,6 +383,7 @@ export async function resolvePromqlTarget( databaseName: source.from.databaseName, tableName: source.from.tableName, minAutoGranularity: source.minAutoGranularity, + promqlBackend: source.promqlBackend, }; } @@ -442,33 +470,50 @@ export function newPromqlClickhouseClient(connection: { }); } +const PROBE_TIMEOUT_MS = 5_000; + +// How long a probe answer is kept. A server's version and handler config +// change rarely, and a stale answer only costs errors until the entry expires. +const BACKEND_PROBE_TTL_MS = 5 * 60_000; + +let backendProbeCache = new MetadataCache(); + +/** Forgets every kept probe answer. For tests. */ +export function clearBackendProbeCache(): void { + backendProbeCache = new MetadataCache(); +} + +/** The probe could not tell, so its outcome must not be kept. */ +class InconclusiveProbeError extends Error {} + /** - * Whether a ClickHouse connection answers PromQL over HTTP. Two conditions, - * cheapest first: the server is new enough (26.6+), and the prometheus_api_v1 - * handler is actually configured — a self-managed server needs an - * `` rule for that, which a stock install lacks. The handler - * answers every request, error or not, with Prometheus JSON (`{status, ...}`); - * a server without it answers a plain-text 404. `format_query` is used as the - * probe because it is the one endpoint that needs no table. + * Asks a ClickHouse connection whether it answers PromQL over HTTP. Two + * conditions, cheapest first: the server is new enough (26.6+), and the + * prometheus_api_v1 handler is actually configured — a self-managed server + * needs an `` rule for that, which a stock install lacks. The + * handler answers every request, error or not, with Prometheus JSON + * (`{status, ...}`); a server without it answers a plain-text 404. + * `format_query` is used as the probe because it is the one endpoint that + * needs no table. * - * Probed on every request, like the version check, so a handler enabled or - * removed on the server is reflected immediately. + * Resolves only with a definitive answer. Rejects with + * InconclusiveProbeError when the server could not be asked or answered with + * something that says nothing about the handler (a timeout, a proxy's 502, a + * rejected login), so a blip is never kept as "no". */ -const PROBE_TIMEOUT_MS = 5_000; - -async function clickhouseServesPrometheusHttpApi( +async function probePrometheusHttpApi( client: ClickhouseClient, connection: { id: string; host: string; username: string; password?: string }, ): Promise { - if ( - !(await connectionSupportsPrometheusHttpApi({ - client, - connectionId: connection.id, - })) - ) { - return false; - } + const supported = await connectionSupportsPrometheusHttpApi({ + client, + connectionId: connection.id, + }); + if (supported === undefined) throw new InconclusiveProbeError(); + if (!supported) return false; + let status: number; + let text: string; try { const { url, headers } = buildPrometheusRequest( connection.host, @@ -480,12 +525,73 @@ async function clickhouseServesPrometheusHttpApi( headers, signal: AbortSignal.timeout(PROBE_TIMEOUT_MS), }); - return typeof JSON.parse(await resp.text())?.status === 'string'; + status = resp.status; + text = await resp.text(); } catch { + throw new InconclusiveProbeError(); + } + + if (typeof parseJSON(text)?.status === 'string') return true; + if (status === 404) return false; + throw new InconclusiveProbeError(); +} + +/** + * Whether a ClickHouse connection answers PromQL over HTTP, keeping a + * definitive answer for BACKEND_PROBE_TTL_MS so each query does not pay for a + * `SELECT version()` and a probe request first. Keyed on the host as well as + * the connection, so editing a connection's host drops its answer. Concurrent + * callers share one probe. An inconclusive probe is answered "no" for this + * request only. + */ +async function clickhouseServesPrometheusHttpApi( + client: ClickhouseClient, + connection: { id: string; host: string; username: string; password?: string }, +): Promise { + const key = `${connection.id}|${connection.host}`; + const span = trace.getActiveSpan(); + + const kept = backendProbeCache.get(key); + if (kept !== undefined) { + span?.setAttribute('hyperdx.promql.backend_probe', 'cached'); + return kept; + } + + try { + const served = await backendProbeCache.getOrFetch( + key, + () => probePrometheusHttpApi(client, connection), + { ttlMs: BACKEND_PROBE_TTL_MS }, + ); + span?.setAttribute('hyperdx.promql.backend_probe', 'live'); + return served; + } catch { + span?.setAttribute('hyperdx.promql.backend_probe', 'inconclusive'); return false; } } +/** + * Whether a connection serves PromQL over ClickHouse's HTTP API right now, + * for callers that want to pin a source to it (see the onboarding flow). Reads + * the same kept answer the queries do. Only a definitive yes is true: a + * Prometheus endpoint, an old server, a missing handler and a server that + * could not be asked all answer false. + */ +export async function connectionServesPrometheusHttpApi(connection: { + id: string; + host: string; + username: string; + password?: string; + isPrometheusEndpoint?: boolean; +}): Promise { + if (connection.isPrometheusEndpoint) return false; + return clickhouseServesPrometheusHttpApi( + newPromqlClickhouseClient(connection), + connection, + ); +} + type ClickhouseQueryBackend = | { kind: 'clickhouse-http'; @@ -509,16 +615,28 @@ type PromqlQueryBackend = /** * How to evaluate PromQL on a ClickHouse-backed target. The Prometheus HTTP * API is the only surface ClickHouse holds forward-compatible while TimeSeries - * is in preview, so it is preferred wherever the server has it (26.6+); the - * table function is the fallback. + * is in preview, so under `auto` it is preferred wherever the server has it + * (26.6+) and the table function is the fallback. A source set to either one + * is taken at its word, with no probe. */ export async function resolveClickhouseQueryBackend({ connection, databaseName, tableName, + promqlBackend = 'auto', }: PromqlTarget): Promise { const client = newPromqlClickhouseClient(connection); - if (await clickhouseServesPrometheusHttpApi(client, connection)) { + const span = trace.getActiveSpan(); + span?.setAttribute('hyperdx.promql.backend_setting', promqlBackend); + + let useHttpApi: boolean; + if (promqlBackend === 'auto') { + useHttpApi = await clickhouseServesPrometheusHttpApi(client, connection); + } else { + span?.setAttribute('hyperdx.promql.backend_probe', 'skipped'); + useHttpApi = promqlBackend === 'clickhouse-http'; + } + if (useHttpApi) { return { kind: 'clickhouse-http', connection: { @@ -615,6 +733,7 @@ async function evaluatePromqlQuery( promqlQueryDataSchema, signal, headers, + CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, ); } case 'table-function': diff --git a/packages/api/src/controllers/timeseriesEngine.ts b/packages/api/src/controllers/timeseriesEngine.ts index 2f51aec671..5c76bd8ef2 100644 --- a/packages/api/src/controllers/timeseriesEngine.ts +++ b/packages/api/src/controllers/timeseriesEngine.ts @@ -452,9 +452,9 @@ export async function queryInstantViaTableFunction({ /** * Whether the connection's ClickHouse is new enough for the Prometheus HTTP - * API. `SELECT version()` runs each call (throwaway cache) so an upgraded - * server is picked up without a restart; an unknown version is treated as - * old, matching the other version-gated features. + * API, or `undefined` when its version could not be read. `SELECT version()` + * runs each call (throwaway cache); callers that keep the answer decide how + * long to. */ export async function connectionSupportsPrometheusHttpApi({ client, @@ -462,9 +462,8 @@ export async function connectionSupportsPrometheusHttpApi({ }: { client: ClickhouseClient; connectionId: string; -}): Promise { +}): Promise { const metadata = new Metadata(client, new MetadataCache()); - return supportsPrometheusHttpApi( - await metadata.getServerVersion({ connectionId }), - ); + const version = await metadata.getServerVersion({ connectionId }); + return version == null ? undefined : supportsPrometheusHttpApi(version); } diff --git a/packages/api/src/mcp/__tests__/promqlSources.int.test.ts b/packages/api/src/mcp/__tests__/promqlSources.int.test.ts index acfc5c9da6..8d4d794d34 100644 --- a/packages/api/src/mcp/__tests__/promqlSources.int.test.ts +++ b/packages/api/src/mcp/__tests__/promqlSources.int.test.ts @@ -249,6 +249,66 @@ describe('MCP PromQL sources', () => { expect(output.partial).toBe(true); expect(output.error).toContain('returned more than 8 MB'); }); + + it('keeps promqlBackend through a describe -> rename -> save round trip', async () => { + const pinned = await Source.create({ + kind: SourceKind.Promql, + team: team._id, + connection: promqlSource.connection, + name: 'Rename Me', + from: { databaseName: DEFAULT_DATABASE, tableName: TABLE }, + timestampValueExpression: 'timestamp', + promqlBackend: 'clickhouse-http', + }); + + const described = await callTool(client, 'clickstack_describe_source', { + sourceId: pinned._id.toString(), + }); + const sourceConfig = JSON.parse(getFirstText(described)).source.config; + expect(sourceConfig.promqlBackend).toBe('clickhouse-http'); + + const result = await callTool(client, 'clickstack_save_source', { + ...sourceConfig, + id: pinned._id.toString(), + name: 'Renamed', + }); + expect(result.isError).toBeFalsy(); + + const stored = await Source.findById(pinned._id); + expect(stored?.name).toBe('Renamed'); + expect(stored?.get('promqlBackend')).toBe('clickhouse-http'); + }); + + it('sets promqlBackend when saving a new PromQL source', async () => { + const result = await callTool(client, 'clickstack_save_source', { + kind: 'promql', + name: 'Pinned PromQL', + connection: promqlSource.connection.toString(), + databaseName: DEFAULT_DATABASE, + tableName: TABLE, + timestampValueExpression: 'timestamp', + promqlBackend: 'table-function', + }); + + expect(result.isError).toBeFalsy(); + const stored = await Source.findOne({ name: 'Pinned PromQL' }); + expect(stored?.get('promqlBackend')).toBe('table-function'); + }); + + it('rejects a promqlBackend that is not one of the known backends', async () => { + const result = await callTool(client, 'clickstack_save_source', { + kind: 'promql', + name: 'Bad PromQL', + connection: promqlSource.connection.toString(), + databaseName: DEFAULT_DATABASE, + tableName: TABLE, + timestampValueExpression: 'timestamp', + promqlBackend: 'http', + }); + + expect(result.isError).toBe(true); + expect(await Source.findOne({ name: 'Bad PromQL' })).toBeNull(); + }); }); describe('with PromQL disabled', () => { diff --git a/packages/api/src/mcp/tools/sources/schemas.ts b/packages/api/src/mcp/tools/sources/schemas.ts index 45b51863e3..03f293efa4 100644 --- a/packages/api/src/mcp/tools/sources/schemas.ts +++ b/packages/api/src/mcp/tools/sources/schemas.ts @@ -1,4 +1,7 @@ -import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { + PromqlSourceBackendSchema, + SourceKind, +} from '@hyperdx/common-utils/dist/types'; import { z } from 'zod'; import { sanitizeMetricTables } from './metricKinds'; @@ -440,6 +443,16 @@ const mcpSaveSourceSchema = z.object({ 'for no minimum.', ), + // ── PromQL ── + promqlBackend: PromqlSourceBackendSchema.optional().describe( + 'Promql sources on a ClickHouse connection. How PromQL is evaluated: ' + + '"clickhouse-http" uses ClickHouse\'s Prometheus HTTP API (ClickHouse ' + + '26.6+ with the prometheus_api_v1 handler configured), "table-function" ' + + 'uses the prometheusQuery table functions, and "auto" (the default when ' + + 'omitted) probes the server and prefers the HTTP API. Ignored when the ' + + 'connection is a Prometheus endpoint.', + ), + // ── Materialized views (advanced; granularities use " " form) ── materializedViews: materializedViewsSchema .optional() diff --git a/packages/api/src/models/source.ts b/packages/api/src/models/source.ts index 19902a41a0..6b162640d7 100644 --- a/packages/api/src/models/source.ts +++ b/packages/api/src/models/source.ts @@ -3,6 +3,7 @@ import { LogSourceSchema, MetricsDataType, MetricSourceSchema, + PROMQL_SOURCE_BACKENDS, PromqlSourceSchema, QuerySettings, SessionSourceSchema, @@ -307,5 +308,6 @@ export const PromqlSource = Source.discriminator( SourceKind.Promql, new Schema>({ minAutoGranularity: minAutoGranularityField, + promqlBackend: { type: String, enum: PROMQL_SOURCE_BACKENDS }, }), ); diff --git a/packages/api/src/routers/api/__tests__/connections.int.test.ts b/packages/api/src/routers/api/__tests__/connections.int.test.ts index c08c10d14a..d508e88a8c 100644 --- a/packages/api/src/routers/api/__tests__/connections.int.test.ts +++ b/packages/api/src/routers/api/__tests__/connections.int.test.ts @@ -1,9 +1,18 @@ import { ObjectId } from 'mongodb'; +import { Types } from 'mongoose'; import * as config from '@/config'; -import { getLoggedInAgent, getServer } from '@/fixtures'; +import { clearBackendProbeCache } from '@/controllers/promql'; +import { getAgent, getLoggedInAgent, getServer } from '@/fixtures'; import Connection from '@/models/connection'; +const mockFetch = jest.mocked(global.fetch); + +// What the router's `format_query` probe sees from a server that does, or does +// not, have the prometheus_api_v1 handler configured. +const probeAnswer = (status: number, body: string) => + new Response(body, { status }); + describe('connections router', () => { const server = getServer(); @@ -13,6 +22,8 @@ describe('connections router', () => { afterEach(async () => { await server.clearDBs(); + clearBackendProbeCache(); + mockFetch.mockReset(); }); afterAll(async () => { @@ -118,4 +129,118 @@ describe('connections router', () => { expect(stored?.host).toBe(config.CLICKHOUSE_HOST); expect(stored?.isPrometheusEndpoint).toBe(false); }); + + describe('GET /connections/:id/prometheus-http-api', () => { + const createClickHouseConnection = (teamId: Types.ObjectId) => + Connection.create({ + team: teamId, + name: 'CH', + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + + it('rejects unauthenticated requests with 401', async () => { + await getAgent(server) + .get(`/connections/${new ObjectId().toString()}/prometheus-http-api`) + .expect(401); + }); + + it('rejects an id that is not an ObjectId with 400', async () => { + const { agent } = await getLoggedInAgent(server); + await agent.get('/connections/nope/prometheus-http-api').expect(400); + }); + + it("returns 404 for another team's connection", async () => { + const { agent } = await getLoggedInAgent(server); + const other = await Connection.create({ + team: new ObjectId(), + name: 'Other', + host: config.CLICKHOUSE_HOST, + username: 'default', + password: '', + }); + + await agent + .get(`/connections/${other._id.toString()}/prometheus-http-api`) + .expect(404); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it('reports a Prometheus endpoint as not serving it, without probing', async () => { + const { agent, team } = await getLoggedInAgent(server); + const connection = await Connection.create({ + team: team._id, + name: 'Thanos', + host: 'http://thanos:10902', + username: '', + password: '', + isPrometheusEndpoint: true, + }); + + const res = await agent + .get(`/connections/${connection._id.toString()}/prometheus-http-api`) + .expect(200); + + expect(res.body).toEqual({ supported: false }); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it('reports a server with the handler as serving it', async () => { + const { agent, team } = await getLoggedInAgent(server); + const connection = await createClickHouseConnection(team._id); + mockFetch.mockResolvedValue( + probeAnswer(200, JSON.stringify({ status: 'success', data: 'up' })), + ); + + const res = await agent + .get(`/connections/${connection._id.toString()}/prometheus-http-api`) + .expect(200); + + expect(res.body).toEqual({ supported: true }); + expect(String(mockFetch.mock.calls[0][0])).toContain( + '/prometheus/api/v1/format_query', + ); + }); + + it('reports a server without the handler as not serving it', async () => { + const { agent, team } = await getLoggedInAgent(server); + const connection = await createClickHouseConnection(team._id); + mockFetch.mockResolvedValue(probeAnswer(404, 'Not found.\n')); + + const res = await agent + .get(`/connections/${connection._id.toString()}/prometheus-http-api`) + .expect(200); + + expect(res.body).toEqual({ supported: false }); + }); + + it('keeps the answer between requests', async () => { + const { agent, team } = await getLoggedInAgent(server); + const connection = await createClickHouseConnection(team._id); + mockFetch.mockResolvedValue( + probeAnswer(200, JSON.stringify({ status: 'success', data: 'up' })), + ); + + for (let i = 0; i < 2; i++) { + await agent + .get(`/connections/${connection._id.toString()}/prometheus-http-api`) + .expect(200); + } + + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + + it('answers false rather than failing when the probe is inconclusive', async () => { + const { agent, team } = await getLoggedInAgent(server); + const connection = await createClickHouseConnection(team._id); + mockFetch.mockResolvedValue(probeAnswer(502, 'Bad gateway')); + + const res = await agent + .get(`/connections/${connection._id.toString()}/prometheus-http-api`) + .expect(200); + + expect(res.body).toEqual({ supported: false }); + }); + }); }); diff --git a/packages/api/src/routers/api/__tests__/prometheus.int.test.ts b/packages/api/src/routers/api/__tests__/prometheus.int.test.ts index d82be84618..b5ed7ddfab 100644 --- a/packages/api/src/routers/api/__tests__/prometheus.int.test.ts +++ b/packages/api/src/routers/api/__tests__/prometheus.int.test.ts @@ -3,11 +3,16 @@ import { QUERY_ATTRIBUTION_HEADER, } from '@hyperdx/common-utils/dist/clickhouse'; import { Metadata } from '@hyperdx/common-utils/dist/core/metadata'; -import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { + type PromqlSourceBackend, + SourceKind, +} from '@hyperdx/common-utils/dist/types'; import { Types } from 'mongoose'; import * as config from '@/config'; import { + clearBackendProbeCache, + CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, CLICKHOUSE_PROMETHEUS_API_PREFIX, clickhousePrometheusUpstream, joinPrometheusUpstreamUrl, @@ -74,6 +79,7 @@ describe('prometheus router', () => { afterEach(async () => { await server.clearDBs(); + clearBackendProbeCache(); mockFetch.mockReset(); mockFetch.mockResolvedValue(fakeUpstreamResponse({})); }); @@ -88,7 +94,13 @@ describe('prometheus router', () => { name = 'PromQL', databaseName = DEFAULT_DATABASE, tableName = 'metrics_ts', - }: { name?: string; databaseName?: string; tableName?: string } = {}, + promqlBackend, + }: { + name?: string; + databaseName?: string; + tableName?: string; + promqlBackend?: PromqlSourceBackend; + } = {}, ) => Source.create({ kind: SourceKind.Promql, @@ -97,6 +109,7 @@ describe('prometheus router', () => { name, from: { databaseName, tableName }, timestampValueExpression: 'timestamp', + promqlBackend, }); const seedPrometheusSource = async ( @@ -116,7 +129,11 @@ describe('prometheus router', () => { const seedClickHouseSource = async ( teamId: Types.ObjectId, - from?: { databaseName?: string; tableName?: string }, + from?: { + databaseName?: string; + tableName?: string; + promqlBackend?: PromqlSourceBackend; + }, ) => { const connection = await Connection.create({ team: teamId, @@ -928,6 +945,144 @@ describe('prometheus router', () => { expect(res.body.error).toMatch(/no_such_table_for_fallback/); }); + describe('on a source that sets its PromQL backend', () => { + const range = { + query: 'up', + start: '1700000000', + end: '1700000060', + step: '60s', + }; + + it('proxies to the handler without probing when set to clickhouse-http', async () => { + const { agent, team } = await getLoggedInAgent(server); + const source = await seedClickHouseSource(team._id, { + promqlBackend: 'clickhouse-http', + }); + mockFetch.mockResolvedValueOnce( + fakeUpstreamResponse({ + status: 'success', + data: { resultType: 'matrix', result: [] }, + }), + ); + + await agent + .get('/v1/prometheus/query_range') + .query({ ...range, sourceId: source._id.toString() }) + .expect(200); + + expect(mockFetch).toHaveBeenCalledTimes(1); + expect(String(mockFetch.mock.calls[0][0])).toContain( + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}/query_range`, + ); + }); + + it('evaluates through prometheusQueryRange() without probing when set to table-function', async () => { + const { agent, team } = await getLoggedInAgent(server); + // The CI server does serve the handler, so only the setting can have + // sent this query down the table-function path. + const source = await seedClickHouseSource(team._id, { + tableName: 'no_such_table_for_pinned', + promqlBackend: 'table-function', + }); + + const res = await agent + .get('/v1/prometheus/query_range') + .query({ ...range, sourceId: source._id.toString() }) + .expect(400); + + expect(mockFetch).not.toHaveBeenCalled(); + expect(res.body.error).toMatch(/no_such_table_for_pinned/); + }); + + it('says so when clickhouse-http reaches a server without the handler', async () => { + const { agent, team } = await getLoggedInAgent(server); + const source = await seedClickHouseSource(team._id, { + promqlBackend: 'clickhouse-http', + }); + mockFetch.mockResolvedValueOnce( + new Response('There is no handle /prometheus/api/v1/query_range', { + status: 404, + }), + ); + + const res = await agent + .get('/v1/prometheus/query_range') + .query({ ...range, sourceId: source._id.toString() }) + .expect(400); + + expect(res.body).toEqual({ + status: 'error', + errorType: 'bad_data', + error: CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, + }); + expect(res.headers['x-content-type-options']).toBe('nosniff'); + }); + + it('says so for an instant query too', async () => { + const { agent, team } = await getLoggedInAgent(server); + const source = await seedClickHouseSource(team._id, { + promqlBackend: 'clickhouse-http', + }); + mockFetch.mockResolvedValueOnce( + new Response('There is no handle /prometheus/api/v1/query', { + status: 404, + }), + ); + + const res = await agent + .get('/v1/prometheus/query') + .query({ query: 'up', sourceId: source._id.toString() }) + .expect(400); + + expect(res.body.error).toBe(CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE); + }); + + it("passes the handler's own failure through unchanged", async () => { + const { agent, team } = await getLoggedInAgent(server); + const source = await seedClickHouseSource(team._id, { + promqlBackend: 'clickhouse-http', + }); + const handlerError = { + status: 'error', + errorType: 'bad_data', + error: 'Table default.metrics_ts does not exist', + }; + mockFetch.mockResolvedValueOnce( + fakeUpstreamResponse(handlerError, 400), + ); + + const res = await agent + .get('/v1/prometheus/query_range') + .query({ ...range, sourceId: source._id.toString() }) + .expect(400); + + expect(res.body).toEqual(handlerError); + }); + + it('does not rewrite a 404 from a Prometheus endpoint', async () => { + const { agent, team } = await getLoggedInAgent(server); + const source = await seedPrometheusSource(team._id); + mockFetch.mockResolvedValueOnce( + new Response('page not found', { status: 404 }), + ); + + // The proxy labels every body as JSON, so read this one raw. + const res = await agent + .get('/v1/prometheus/query_range') + .query({ ...range, sourceId: source._id.toString() }) + .buffer(true) + .parse((upstream, done) => { + let body = ''; + upstream.setEncoding('utf8'); + upstream.on('data', chunk => (body += chunk)); + upstream.on('end', () => done(null, body)); + }) + .expect(404); + + expect(res.body).toBe('page not found'); + }); + }); + // The one place the proxy meets a real prometheus_api_v1 handler: the CI // ClickHouse (26.8, docker/clickhouse/local/config.xml) serves it, so the // stubbed fetch is swapped for the real one and the answer has to be @@ -1326,6 +1481,33 @@ describe('prometheus router', () => { 'X-ClickHouse-User': config.CLICKHOUSE_USER, }); }); + + it('probes the handler once across queries on the same connection', async () => { + const { agent, team } = await getLoggedInAgent(server); + const source = await seedClickHouseSource(team._id); + const answer = () => + fakeUpstreamResponse({ + status: 'success', + data: { resultType: 'vector', result: [] }, + }); + mockFetch + .mockResolvedValueOnce(handlerProbeResponse()) + .mockResolvedValueOnce(answer()) + .mockResolvedValueOnce(answer()); + + for (let i = 0; i < 2; i++) { + await agent + .get('/v1/prometheus/query') + .query({ query: 'up', sourceId: source._id.toString() }) + .expect(200); + } + + const urls = mockFetch.mock.calls.map(([url]) => String(url)); + expect(urls.filter(url => url.includes('/format_query'))).toHaveLength(1); + expect( + urls.filter(url => url.includes('/prometheus/api/v1/query?')), + ).toHaveLength(2); + }); }); describe('GET /v1/prometheus/label/:name/values', () => { diff --git a/packages/api/src/routers/api/__tests__/sources.int.test.ts b/packages/api/src/routers/api/__tests__/sources.int.test.ts index 7cb4f072d6..ea83a0874d 100644 --- a/packages/api/src/routers/api/__tests__/sources.int.test.ts +++ b/packages/api/src/routers/api/__tests__/sources.int.test.ts @@ -930,6 +930,86 @@ describe('sources router', () => { }); }); + describe('promqlBackend on a PromQL source', () => { + it('POST / - creates a PromQL source with promqlBackend and it round-trips', async () => { + const { agent } = await getLoggedInAgent(server); + + const response = await agent + .post('/sources') + .send({ ...MOCK_PROMQL_SOURCE, promqlBackend: 'clickhouse-http' }) + .expect(200); + + expect(response.body.promqlBackend).toBe('clickhouse-http'); + + const sources = await Source.find({}).lean(); + expect(sources).toHaveLength(1); + expect(sources[0]).toHaveProperty('promqlBackend', 'clickhouse-http'); + }); + + it('POST / - leaves promqlBackend unset when the request omits it', async () => { + const { agent } = await getLoggedInAgent(server); + + const response = await agent + .post('/sources') + .send(MOCK_PROMQL_SOURCE) + .expect(200); + + expect(response.body).not.toHaveProperty('promqlBackend'); + expect(await Source.find({}).lean()).toEqual([ + expect.not.objectContaining({ promqlBackend: expect.anything() }), + ]); + }); + + it('POST / - rejects a promqlBackend that is not one of the known backends', async () => { + const { agent } = await getLoggedInAgent(server); + + await agent + .post('/sources') + .send({ ...MOCK_PROMQL_SOURCE, promqlBackend: 'http' }) + .expect(400); + + expect(await Source.countDocuments()).toBe(0); + }); + + it('PUT /:id - updates promqlBackend', async () => { + const { agent, team } = await getLoggedInAgent(server); + const promqlSource = await Source.create({ + ...MOCK_PROMQL_SOURCE, + promqlBackend: 'clickhouse-http', + team: team._id, + }); + + await agent + .put(`/sources/${promqlSource._id}`) + .send({ + id: promqlSource._id.toString(), + ...MOCK_PROMQL_SOURCE, + promqlBackend: 'table-function', + }) + .expect(200); + + const updatedSource = await Source.findById(promqlSource._id).lean(); + expect(updatedSource).toHaveProperty('promqlBackend', 'table-function'); + }); + + it('PUT /:id - removes promqlBackend when omitted from the update payload', async () => { + const { agent, team } = await getLoggedInAgent(server); + const promqlSource = await Source.create({ + ...MOCK_PROMQL_SOURCE, + promqlBackend: 'clickhouse-http', + team: team._id, + }); + + await agent + .put(`/sources/${promqlSource._id}`) + .send({ id: promqlSource._id.toString(), ...MOCK_PROMQL_SOURCE }) + .expect(200); + + const updatedSource = await Source.findById(promqlSource._id).lean(); + expect(updatedSource).not.toHaveProperty('promqlBackend'); + }); + }); + it('DELETE /:id - deletes a source', async () => { const { agent, team } = await getLoggedInAgent(server); diff --git a/packages/api/src/routers/api/connections.ts b/packages/api/src/routers/api/connections.ts index e202b1a99b..4f7d8e8120 100644 --- a/packages/api/src/routers/api/connections.ts +++ b/packages/api/src/routers/api/connections.ts @@ -1,5 +1,6 @@ import { ConnectionSchema } from '@hyperdx/common-utils/dist/types'; import express from 'express'; +import z from 'zod'; import { validateRequest } from 'zod-express-middleware'; import { @@ -9,7 +10,9 @@ import { getConnectionsByTeam, updateConnection, } from '@/controllers/connection'; +import { connectionServesPrometheusHttpApi } from '@/controllers/promql'; import { getNonNullUserWithTeam } from '@/middleware/auth'; +import { objectIdSchema } from '@/utils/zod'; const router = express.Router(); @@ -118,6 +121,35 @@ router.put( }, ); +// Whether the connection answers PromQL over ClickHouse's Prometheus HTTP API. +// Onboarding uses it to pin a new PromQL source to that API. +router.get( + '/:id/prometheus-http-api', + validateRequest({ params: z.object({ id: objectIdSchema }) }), + async (req, res, next) => { + try { + const { teamId } = getNonNullUserWithTeam(req); + + const connection = await getConnectionById( + teamId.toString(), + req.params.id, + true, + ); + + if (!connection) { + res.status(404).send(); + return; + } + + res.json({ + supported: await connectionServesPrometheusHttpApi(connection), + }); + } catch (e) { + next(e); + } + }, +); + router.delete('/:id', async (req, res, next) => { try { const { teamId } = getNonNullUserWithTeam(req); diff --git a/packages/api/src/routers/api/prometheus.ts b/packages/api/src/routers/api/prometheus.ts index 8ad5bc86a2..b266bc8a31 100644 --- a/packages/api/src/routers/api/prometheus.ts +++ b/packages/api/src/routers/api/prometheus.ts @@ -12,6 +12,7 @@ import z from 'zod'; import { buildPrometheusRequest, + CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, CLICKHOUSE_PROMETHEUS_API_PREFIX, clickhousePrometheusRequest, newPromqlClickhouseClient, @@ -205,12 +206,17 @@ const CALLER_SETTABLE_PARAM_KEYS = new Set([ // Prometheus's native response shape (`{status, data}` / `{status, errorType, // error}`) is already what HyperDX clients expect, so we forward the status code // as-is — but never the content-type, which is always relabelled (see below). +// +// `handlerMissingMessage` is for ClickHouse's own Prometheus API: a 404 means +// the server has no such handler, and is answered with a 400 carrying this +// message instead. async function proxyToPrometheus( upstreamHost: string, path: string, params: Record, res: express.Response, headers?: Record, + handlerMissingMessage?: string, ): Promise { // For a key in CALLER_SETTABLE_PARAM_KEYS, the request always wins // outright, including repeatable ones like `match[]` -- so a Connection @@ -286,6 +292,19 @@ async function proxyToPrometheus( return 502; } + // A server without the handler answers 404 for any path under it, while the + // handler answers every failure (a missing table, a bad query) with a 400 + // and Prometheus JSON, so the status alone tells them apart. + if (handlerMissingMessage && upstreamResp.status === 404) { + await upstreamResp.body?.cancel().catch(() => {}); + res.status(400).json({ + status: 'error', + errorType: 'bad_data', + error: handlerMissingMessage, + }); + return 400; + } + res.status(upstreamResp.status); // The connection host is member-configured, so its response is untrusted output @@ -420,6 +439,7 @@ const queryRangeHandler: express.RequestHandler = async (req, res) => { { ...params, database: databaseName, table: tableName }, res, headers, + CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, ); recordProxyOutcome(status, 'query_range', backend); return; @@ -515,6 +535,7 @@ const queryHandler: express.RequestHandler = async (req, res) => { { ...params, database: databaseName, table: tableName }, res, headers, + CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, ); recordProxyOutcome(status, 'query', backend); return; diff --git a/packages/api/src/routers/external-api/__tests__/sources-crud.int.test.ts b/packages/api/src/routers/external-api/__tests__/sources-crud.int.test.ts index 7ad19429cd..d188607f9f 100644 --- a/packages/api/src/routers/external-api/__tests__/sources-crud.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/sources-crud.int.test.ts @@ -286,6 +286,51 @@ describe('External API v2 Sources CRUD', () => { .expect(400); }); + it('should round-trip promqlBackend on a promql source', async () => { + const body = { + kind: SourceKind.Promql, + name: 'Prometheus Metrics', + from: { databaseName: 'default', tableName: 'default' }, + timestampValueExpression: 'timestamp', + connection: connection._id.toString(), + promqlBackend: 'clickhouse-http', + }; + + const created = await authRequest('post', BASE_URL) + .send(body) + .expect(200); + expect(created.body.data.promqlBackend).toBe('clickhouse-http'); + + const updated = await authRequest( + 'put', + `${BASE_URL}/${created.body.data.id}`, + ) + .send({ ...body, promqlBackend: 'table-function' }) + .expect(200); + expect(updated.body.data.promqlBackend).toBe('table-function'); + + const fetched = await authRequest( + 'get', + `${BASE_URL}/${created.body.data.id}`, + ).expect(200); + expect(fetched.body.data.promqlBackend).toBe('table-function'); + }); + + it('should return 400 for a promqlBackend that is not a known backend', async () => { + await authRequest('post', BASE_URL) + .send({ + kind: SourceKind.Promql, + name: 'Prometheus Metrics', + from: { databaseName: 'default', tableName: 'default' }, + timestampValueExpression: 'timestamp', + connection: connection._id.toString(), + promqlBackend: 'http', + }) + .expect(400); + + expect(await Source.findOne({ team: team._id })).toBeNull(); + }); + it('should return 400 when connection is not a valid id', async () => { await authRequest('post', BASE_URL) .send({ ...logSourceBody(), connection: 'my-connection-name' }) diff --git a/packages/api/src/routers/external-api/v2/sources.ts b/packages/api/src/routers/external-api/v2/sources.ts index 0a30bd7bed..561625bc65 100644 --- a/packages/api/src/routers/external-api/v2/sources.ts +++ b/packages/api/src/routers/external-api/v2/sources.ts @@ -840,6 +840,11 @@ function formatExternalSource(source: SourceDocument) { * description: Floor for the auto-inferred chart granularity, and the scrape interval that `$__rate_interval` is computed from. Set it to the Prometheus scrape interval so a short time range does not produce buckets smaller than that interval. Only constrains "Auto" granularity; an explicit granularity picked on a tile is never overridden. Omit for no minimum. Uses the SQL interval format (a positive integer followed by second, minute, hour, or day), not the short form of the materialized view granularity fields. * pattern: '^\d+ (second|minute|hour|day)$' * example: 1 minute + * promqlBackend: + * type: string + * enum: [auto, clickhouse-http, table-function] + * description: How PromQL is evaluated on a ClickHouse connection. "clickhouse-http" uses ClickHouse's Prometheus HTTP API, which needs ClickHouse 26.6+ with the prometheus_api_v1 handler configured; queries fail with an error when the server does not serve it. "table-function" uses the prometheusQuery table functions. "auto" (the default when omitted) checks the server and prefers the HTTP API. Ignored when the connection is a Prometheus-compatible endpoint. + * example: auto * Source: * oneOf: * - $ref: '#/components/schemas/LogSource' diff --git a/packages/app/src/__tests__/connection.test.ts b/packages/app/src/__tests__/connection.test.ts new file mode 100644 index 0000000000..5b4ebb8d45 --- /dev/null +++ b/packages/app/src/__tests__/connection.test.ts @@ -0,0 +1,54 @@ +const mockConfig = { IS_LOCAL_MODE: false }; +jest.mock('@/config', () => ({ + HDX_LOCAL_DEFAULT_CONNECTIONS: undefined, + get IS_LOCAL_MODE() { + return mockConfig.IS_LOCAL_MODE; + }, +})); + +const mockHdxServer = jest.fn(); +jest.mock('@/api', () => ({ + hdxServer: (...args: unknown[]) => mockHdxServer(...args), +})); + +import { fetchPrometheusHttpApiSupport } from '@/connection'; + +const answers = (body: unknown) => + mockHdxServer.mockReturnValue({ json: () => Promise.resolve(body) }); + +describe('fetchPrometheusHttpApiSupport', () => { + beforeEach(() => { + mockHdxServer.mockReset(); + mockConfig.IS_LOCAL_MODE = false; + }); + + it('asks the server about the connection', async () => { + answers({ supported: true }); + + await expect(fetchPrometheusHttpApiSupport('conn-1')).resolves.toBe(true); + expect(mockHdxServer).toHaveBeenCalledWith( + 'connections/conn-1/prometheus-http-api', + ); + }); + + it('reports a server that does not serve it', async () => { + answers({ supported: false }); + + await expect(fetchPrometheusHttpApiSupport('conn-1')).resolves.toBe(false); + }); + + it('reports false when the server cannot be asked', async () => { + mockHdxServer.mockReturnValue({ + json: () => Promise.reject(new Error('boom')), + }); + + await expect(fetchPrometheusHttpApiSupport('conn-1')).resolves.toBe(false); + }); + + it('does not ask the server about a local-mode connection', async () => { + mockConfig.IS_LOCAL_MODE = true; + + await expect(fetchPrometheusHttpApiSupport('local')).resolves.toBe(false); + expect(mockHdxServer).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/app/src/components/OnboardingModal.tsx b/packages/app/src/components/OnboardingModal.tsx index 4d98c32d51..ab2e3cbf05 100644 --- a/packages/app/src/components/OnboardingModal.tsx +++ b/packages/app/src/components/OnboardingModal.tsx @@ -22,6 +22,7 @@ import { IS_PROMQL_ENABLED, } from '@/config'; import { + fetchPrometheusHttpApiSupport, useConnections, useCreateConnection, useUpdateConnection, @@ -536,6 +537,10 @@ function OnboardingModalComponent({ // Create PromQL Source if a TimeSeries table is available if (timeSeriesTable) { try { + // Pin the source to the HTTP API only when the server answers it + // now. Otherwise leave it on Auto, which keeps checking. + const servesHttpApi = + await fetchPrometheusHttpApiSupport(connectionId); const promqlSource = await createSourceMutation.mutateAsync({ source: { kind: SourceKind.Promql, @@ -543,6 +548,9 @@ function OnboardingModalComponent({ connection: connectionId, from: timeSeriesTable, timestampValueExpression: PROMQL_TIMESTAMP_EXPRESSION, + ...(servesHttpApi + ? { promqlBackend: 'clickhouse-http' as const } + : {}), }, }); createdSources.push(promqlSource); diff --git a/packages/app/src/components/Sources/SourceForm/PromqlTableModelForm.tsx b/packages/app/src/components/Sources/SourceForm/PromqlTableModelForm.tsx index 2f228c4583..07f909843d 100644 --- a/packages/app/src/components/Sources/SourceForm/PromqlTableModelForm.tsx +++ b/packages/app/src/components/Sources/SourceForm/PromqlTableModelForm.tsx @@ -1,24 +1,51 @@ import { useEffect } from 'react'; +import { Stack } from '@mantine/core'; +import SelectControlled from '@/components/SelectControlled'; import { PROMQL_TIMESTAMP_EXPRESSION } from '@/source'; +import { PROMQL_BACKEND_OPTIONS } from './constants'; +import { FormRow } from './FormRow'; import { MinAutoGranularityFormRow } from './MinAutoGranularityFormRow'; import { TableModelProps } from './types'; const PROMQL_MIN_AUTO_GRANULARITY_HELP_TEXT = "Floor for 'auto granularity' on charts querying this source. Set this to your metrics' scrape interval to avoid sparse-looking charts on short time ranges. Doesn't affect an explicitly chosen (non-auto) granularity. $__rate_interval is also sized from it, assuming a 15 second scrape interval when no minimum is set."; -export function PromqlTableModelForm({ control, setValue }: TableModelProps) { +const PROMQL_BACKEND_HELP_TEXT = + 'How ClickHouse evaluates queries on this source. Auto uses the Prometheus HTTP API when the server serves it (ClickHouse 26.6+ with the prometheus_api_v1 handler configured) and the prometheusQuery table functions otherwise, and re-checks every few minutes. Pick one to skip that check.'; + +export function PromqlTableModelForm({ + control, + setValue, + isPrometheusEndpoint, +}: TableModelProps) { useEffect(() => { - setValue('timestampValueExpression' as any, PROMQL_TIMESTAMP_EXPRESSION); + setValue('timestampValueExpression', PROMQL_TIMESTAMP_EXPRESSION); }, [setValue]); // PromQL sources use the standard database + table fields from BaseSourceSchema. // The table should point to the TimeSeries engine table. return ( - + + {/* A Prometheus endpoint is always queried through its own API. */} + {!isPrometheusEndpoint && ( + + + + )} + + ); } diff --git a/packages/app/src/components/Sources/SourceForm/SourceForm.tsx b/packages/app/src/components/Sources/SourceForm/SourceForm.tsx index f3d9f5e792..329a8d54e5 100644 --- a/packages/app/src/components/Sources/SourceForm/SourceForm.tsx +++ b/packages/app/src/components/Sources/SourceForm/SourceForm.tsx @@ -734,7 +734,7 @@ export function TableSourceForm({ variant="secondary" size="sm" color="gray" - mt="md" + mt={querySettingFields.length ? 'md' : 0} disabled={querySettingFields.length >= 10} onClick={() => { if (querySettingFields.length < 10) { @@ -752,6 +752,7 @@ export function TableSourceForm({ setValue={setValue} kind={kind} sourceId={sourceId} + isPrometheusEndpoint={isPrometheusOnlyConnection} /> {onCancel && ( diff --git a/packages/app/src/components/Sources/SourceForm/TableModelForm.tsx b/packages/app/src/components/Sources/SourceForm/TableModelForm.tsx index 4fb5c6d464..e36b981409 100644 --- a/packages/app/src/components/Sources/SourceForm/TableModelForm.tsx +++ b/packages/app/src/components/Sources/SourceForm/TableModelForm.tsx @@ -19,11 +19,13 @@ export function TableModelForm({ setValue, kind, sourceId, + isPrometheusEndpoint, }: { control: Control; setValue: UseFormSetValue; kind: SourceKind; sourceId?: string; + isPrometheusEndpoint?: boolean; }) { switch (kind) { case SourceKind.Log: @@ -41,6 +43,12 @@ export function TableModelForm({ /> ); case SourceKind.Promql: - return ; + return ( + + ); } } diff --git a/packages/app/src/components/Sources/SourceForm/constants.ts b/packages/app/src/components/Sources/SourceForm/constants.ts index 9671e7aa12..9cb5f00e4d 100644 --- a/packages/app/src/components/Sources/SourceForm/constants.ts +++ b/packages/app/src/components/Sources/SourceForm/constants.ts @@ -1,4 +1,8 @@ -import { SourceKind, UseTextIndex } from '@hyperdx/common-utils/dist/types'; +import { + type PromqlSourceBackend, + SourceKind, + UseTextIndex, +} from '@hyperdx/common-utils/dist/types'; import { MV_AGGREGATE_FUNCTIONS, @@ -50,6 +54,15 @@ export const MIN_AUTO_GRANULARITY_OPTIONS = [ ...MV_GRANULARITY_OPTIONS.filter(option => option.value !== '1 second'), ]; +export const PROMQL_BACKEND_OPTIONS: { + value: PromqlSourceBackend; + label: string; +}[] = [ + { value: 'auto', label: 'Auto (detect from server)' }, + { value: 'clickhouse-http', label: 'Prometheus HTTP API' }, + { value: 'table-function', label: 'Table functions' }, +]; + export const USE_TEXT_INDEX_OPTIONS = [ { value: UseTextIndex.Auto, diff --git a/packages/app/src/components/Sources/SourceForm/types.ts b/packages/app/src/components/Sources/SourceForm/types.ts index 4e46912c19..e47f4c8ea1 100644 --- a/packages/app/src/components/Sources/SourceForm/types.ts +++ b/packages/app/src/components/Sources/SourceForm/types.ts @@ -6,4 +6,6 @@ export interface TableModelProps { setValue: UseFormSetValue; // Set when editing an existing source sourceId?: string; + // The selected connection is a Prometheus-compatible endpoint, not ClickHouse + isPrometheusEndpoint?: boolean; } diff --git a/packages/app/src/components/__tests__/OnboardingModal.test.tsx b/packages/app/src/components/__tests__/OnboardingModal.test.tsx index b66ae46f87..8bb64b1995 100644 --- a/packages/app/src/components/__tests__/OnboardingModal.test.tsx +++ b/packages/app/src/components/__tests__/OnboardingModal.test.tsx @@ -39,7 +39,10 @@ const mockConnectionsResult = { data: [{ id: 'conn-1', name: 'Default', host: 'http://localhost:8123' }], }; const mockUpdateConnectionMutation = { mutateAsync: jest.fn() }; +const mockFetchHttpApiSupport = jest.fn(); jest.mock('@/connection', () => ({ + fetchPrometheusHttpApiSupport: (...args: unknown[]) => + mockFetchHttpApiSupport(...args), useConnections: () => mockConnectionsResult, useCreateConnection: () => ({ mutate: jest.fn() }), useUpdateConnection: () => mockUpdateConnectionMutation, @@ -93,6 +96,7 @@ describe('OnboardingModal auto-detection', () => { }), ); mockUpdateSource.mockResolvedValue(undefined); + mockFetchHttpApiSupport.mockResolvedValue(false); mockMetadata.getOtelTables.mockResolvedValue(OTEL_LOGS_ONLY); mockMetadata.getTimeSeriesTables.mockResolvedValue([ { databaseName: 'default', tableName: 'metrics_ts' }, @@ -118,6 +122,29 @@ describe('OnboardingModal auto-detection', () => { }); }); + it('pins the PromQL source to the HTTP API when the server serves it', async () => { + mockFetchHttpApiSupport.mockResolvedValue(true); + + renderWithMantine(); + + await screen.findByText('Automatically detected and created 2 sources.'); + expect(mockFetchHttpApiSupport).toHaveBeenCalledWith('conn-1'); + expect(mockCreateSource).toHaveBeenLastCalledWith({ + source: expect.objectContaining({ + kind: SourceKind.Promql, + promqlBackend: 'clickhouse-http', + }), + }); + }); + + it('leaves the PromQL backend unset when the server does not serve the HTTP API', async () => { + renderWithMantine(); + + await screen.findByText('Automatically detected and created 2 sources.'); + const [{ source }] = mockCreateSource.mock.lastCall; + expect(source).not.toHaveProperty('promqlBackend'); + }); + it('skips PromQL detection when PromQL is disabled', async () => { mockConfig.IS_PROMQL_ENABLED = false; @@ -125,6 +152,7 @@ describe('OnboardingModal auto-detection', () => { await screen.findByText('Automatically detected and created 1 source.'); expect(mockMetadata.getTimeSeriesTables).not.toHaveBeenCalled(); + expect(mockFetchHttpApiSupport).not.toHaveBeenCalled(); expect(createdKinds()).toEqual([SourceKind.Log]); }); diff --git a/packages/app/src/components/__tests__/PromqlTableModelForm.test.tsx b/packages/app/src/components/__tests__/PromqlTableModelForm.test.tsx new file mode 100644 index 0000000000..c9de0976bb --- /dev/null +++ b/packages/app/src/components/__tests__/PromqlTableModelForm.test.tsx @@ -0,0 +1,95 @@ +import { useForm, useWatch } from 'react-hook-form'; +import { + PromqlSourceBackend, + SourceKind, + TSource, +} from '@hyperdx/common-utils/dist/types'; +import { screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { PromqlTableModelForm } from '@/components/Sources/SourceForm/PromqlTableModelForm'; + +// Mantine's Combobox calls scrollIntoView when its dropdown opens; jsdom lacks it. +window.HTMLElement.prototype.scrollIntoView = jest.fn(); + +function Harness({ + promqlBackend, + isPrometheusEndpoint, +}: { + promqlBackend?: PromqlSourceBackend; + isPrometheusEndpoint?: boolean; +}) { + const { control, setValue } = useForm({ + defaultValues: { + kind: SourceKind.Promql, + name: 'PromQL', + connection: 'conn-1', + from: { databaseName: 'default', tableName: 'metrics_ts' }, + timestampValueExpression: 'timestamp', + promqlBackend, + }, + }); + const backend = useWatch({ control, name: 'promqlBackend' }); + return ( + <> + +
{backend ?? 'unset'}
+ + ); +} + +const backendSelect = () => screen.getByTestId('promql-backend-select'); + +describe('PromqlTableModelForm', () => { + it('shows Auto for a source that has no backend set', () => { + renderWithMantine(); + + expect(backendSelect()).toHaveAttribute( + 'placeholder', + 'Auto (detect from server)', + ); + expect(backendSelect()).toHaveValue(''); + expect(screen.getByTestId('backend-value')).toHaveTextContent('unset'); + }); + + it('shows the backend a source has set', () => { + renderWithMantine(); + + expect(backendSelect()).toHaveValue('Prometheus HTTP API'); + }); + + it('sets the backend from the option picked', async () => { + const user = userEvent.setup(); + renderWithMantine(); + + await user.click(backendSelect()); + await user.click(await screen.findByText('Table functions')); + + expect(screen.getByTestId('backend-value')).toHaveTextContent( + 'table-function', + ); + }); + + it('can go back to Auto after another backend was picked', async () => { + const user = userEvent.setup(); + renderWithMantine(); + + await user.click(backendSelect()); + await user.click(await screen.findByText('Auto (detect from server)')); + + expect(screen.getByTestId('backend-value')).toHaveTextContent('auto'); + }); + + it('hides the backend for a Prometheus endpoint, which is always queried through its own API', () => { + renderWithMantine(); + + expect(screen.queryByTestId('promql-backend-select')).toBeNull(); + expect(screen.queryByText('PromQL backend')).toBeNull(); + // The rest of the form is unaffected. + expect(screen.getByText('Minimum auto granularity')).toBeInTheDocument(); + }); +}); diff --git a/packages/app/src/connection.ts b/packages/app/src/connection.ts index 3ed38168b7..97a933c14b 100644 --- a/packages/app/src/connection.ts +++ b/packages/app/src/connection.ts @@ -53,6 +53,26 @@ export function useConnections() { }); } +/** + * Whether the server behind a connection answers PromQL over ClickHouse's + * Prometheus HTTP API. False when it does not, and also when it could not be + * asked, so a caller pins to the HTTP API only on a definitive yes. + */ +export async function fetchPrometheusHttpApiSupport( + connectionId: string, +): Promise { + // A local-mode connection lives in the browser; the API has no record of it. + if (IS_LOCAL_MODE) return false; + try { + const { supported } = await hdxServer( + `connections/${connectionId}/prometheus-http-api`, + ).json<{ supported: boolean }>(); + return supported === true; + } catch { + return false; + } +} + export function useCreateConnection() { const queryClient = useQueryClient(); diff --git a/packages/common-utils/src/__tests__/types.test.ts b/packages/common-utils/src/__tests__/types.test.ts index 166f004708..1640578a2e 100644 --- a/packages/common-utils/src/__tests__/types.test.ts +++ b/packages/common-utils/src/__tests__/types.test.ts @@ -951,6 +951,43 @@ describe('PromqlSourceSchema.minAutoGranularity', () => { }); }); +describe('PromqlSourceSchema.promqlBackend', () => { + const base = { + id: 'source-1', + kind: 'promql' as const, + name: 'Prometheus', + connection: 'conn-1', + from: { databaseName: 'default', tableName: 'metrics_ts' }, + timestampValueExpression: 'timestamp', + }; + const parse = (promqlBackend: unknown) => + PromqlSourceSchema.safeParse({ ...base, promqlBackend }); + + it.each(['auto', 'clickhouse-http', 'table-function'])( + 'accepts %s', + value => { + const result = parse(value); + expect(result.success).toBe(true); + if (result.success) { + expect(result.data.promqlBackend).toBe(value); + } + }, + ); + + it('accepts an absent setting', () => { + const result = parse(undefined); + expect(result.success).toBe(true); + if (result.success) { + expect(result.data.promqlBackend).toBeUndefined(); + } + }); + + it('rejects anything else', () => { + expect(parse('http').success).toBe(false); + expect(parse('').success).toBe(false); + }); +}); + describe('MetricFormulaSchema', () => { it('parses an expression-only formula', () => { const result = MetricFormulaSchema.safeParse({ diff --git a/packages/common-utils/src/types.ts b/packages/common-utils/src/types.ts index 16519d95f7..dba9c7854e 100644 --- a/packages/common-utils/src/types.ts +++ b/packages/common-utils/src/types.ts @@ -2833,6 +2833,22 @@ export const MinAutoGranularitySchema = z.preprocess( SQLIntervalSchema.optional(), ); +/** + * How a PromQL source on a ClickHouse connection is evaluated: through the + * Prometheus HTTP API (`clickhouse-http`, which needs ClickHouse 26.6+ with the + * `prometheus_api_v1` handler configured) or through the `prometheusQuery` + * table functions (`table-function`). `auto`, which is also what an unset + * value means, probes the server on first use and prefers the HTTP API. A + * connection that is itself a Prometheus endpoint ignores it. + */ +export const PROMQL_SOURCE_BACKENDS = [ + 'auto', + 'clickhouse-http', + 'table-function', +] as const; +export const PromqlSourceBackendSchema = z.enum(PROMQL_SOURCE_BACKENDS); +export type PromqlSourceBackend = z.infer; + // Metric source form schema export const MetricSourceSchema = BaseSourceSchema.extend({ kind: z.literal(SourceKind.Metric), @@ -2860,6 +2876,7 @@ export const MetricSourceSchema = BaseSourceSchema.extend({ export const PromqlSourceSchema = BaseSourceSchema.extend({ kind: z.literal(SourceKind.Promql), minAutoGranularity: MinAutoGranularitySchema, + promqlBackend: PromqlSourceBackendSchema.optional(), }); // Union of all source form schemas for validation From 2d17de5d7d8ca2e41c36e17bbdca6224f9dd5022 Mon Sep 17 00:00:00 2001 From: Karl Power <85935352+karl-power@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:40:53 +0100 Subject: [PATCH 03/55] feat(api): serve PromQL label lookups from ClickHouse's Prometheus HTTP API (#3628) --- .../promql-labels-via-clickhouse-http-api.md | 8 + agent_docs/observability.md | 7 +- .../__tests__/promqlBackend.test.ts | 79 +++++- .../__tests__/timeseriesEngine.test.ts | 33 +++ packages/api/src/controllers/promql.ts | 82 +++++-- .../api/src/controllers/timeseriesEngine.ts | 56 +++-- packages/api/src/mcp/__tests__/query.test.ts | 2 +- packages/api/src/mcp/tools/query/helpers.ts | 51 +--- .../api/__tests__/prometheus.int.test.ts | 230 ++++++++++++++++++ packages/api/src/routers/api/prometheus.ts | 62 +++-- packages/api/src/utils/clickhouseErrors.ts | 45 ++++ .../src/__tests__/clickhouseVersion.test.ts | 23 ++ .../src/core/clickhouseVersion.ts | 13 + 13 files changed, 577 insertions(+), 114 deletions(-) create mode 100644 .changeset/promql-labels-via-clickhouse-http-api.md create mode 100644 packages/api/src/utils/clickhouseErrors.ts diff --git a/.changeset/promql-labels-via-clickhouse-http-api.md b/.changeset/promql-labels-via-clickhouse-http-api.md new file mode 100644 index 0000000000..7821da8ad2 --- /dev/null +++ b/.changeset/promql-labels-via-clickhouse-http-api.md @@ -0,0 +1,8 @@ +--- +'@hyperdx/api': minor +'@hyperdx/common-utils': minor +--- + +feat: serve PromQL label lookups from ClickHouse's Prometheus HTTP API + +On ClickHouse 26.9+ with the `prometheus_api_v1` handler, `/labels` and `/label/:name/values` for a ClickHouse-backed PromQL source now proxy to the handler instead of querying the TimeSeries tags table with SQL. Older servers, servers without the handler, and sources set to `table-function` keep the SQL path, so a source that runs queries over HTTP on 26.6-26.8 still gets label autocomplete. diff --git a/agent_docs/observability.md b/agent_docs/observability.md index d19c2e922d..1de5356b42 100644 --- a/agent_docs/observability.md +++ b/agent_docs/observability.md @@ -305,9 +305,10 @@ calls `/api/v1/prometheus/query{,_range}`, and `/labels` and (`QUERY_ATTRIBUTION_HEADER`), and the router parses it with `parseLogComment` into a `withQueryAttribution` scope layered over the auth middleware's `api` scope. The browser's surface and ids win; `trace` and `label` stay the -server's. Queries the route runs through a ClickHouse client (label lookups, -and the `prometheusQuery()`/`prometheusQueryRange()` fallback) pick the scope -up as usual. Requests proxied to ClickHouse's Prometheus HTTP API on 26.6+ are tagged +server's. Queries the route runs through a ClickHouse client (label lookups +before 26.9, and the `prometheusQuery()`/`prometheusQueryRange()` fallback) +pick the scope up as usual. Requests proxied to ClickHouse's Prometheus HTTP +API (queries on 26.6+, label lookups on 26.9+) are tagged by `clickhousePrometheusRequest`: `log_comment` as a URL setting, `query_id` as the `X-ClickHouse-Query-Id` header, because the handler rejects `query_id` as an unknown setting in the URL. diff --git a/packages/api/src/controllers/__tests__/promqlBackend.test.ts b/packages/api/src/controllers/__tests__/promqlBackend.test.ts index 99e8af0567..43dea0a04a 100644 --- a/packages/api/src/controllers/__tests__/promqlBackend.test.ts +++ b/packages/api/src/controllers/__tests__/promqlBackend.test.ts @@ -2,17 +2,24 @@ import type { PromqlSourceBackend } from '@hyperdx/common-utils/dist/types'; import { clearBackendProbeCache, + resolveClickhouseLabelBackend, resolveClickhouseQueryBackend, } from '@/controllers/promql'; -import { connectionSupportsPrometheusHttpApi } from '@/controllers/timeseriesEngine'; +import { connectionPrometheusHttpApiSupport } from '@/controllers/timeseriesEngine'; jest.mock('@/controllers/timeseriesEngine', () => ({ ...jest.requireActual('@/controllers/timeseriesEngine'), - connectionSupportsPrometheusHttpApi: jest.fn(), + connectionPrometheusHttpApiSupport: jest.fn(), })); const mockFetch = jest.mocked(global.fetch); -const mockVersionCheck = jest.mocked(connectionSupportsPrometheusHttpApi); +const mockVersionCheck = jest.mocked(connectionPrometheusHttpApiSupport); + +// What the version check answers for a server on each side of the 26.6 (query) +// and 26.9 (label lookup) cut-offs. +const CLICKHOUSE_26_10 = { query: true, labels: true }; +const CLICKHOUSE_26_8 = { query: true, labels: false }; +const CLICKHOUSE_26_5 = { query: false, labels: false }; const handlerAnswer = () => new Response(JSON.stringify({ status: 'success', data: 'up' })); @@ -46,7 +53,7 @@ describe('resolveClickhouseQueryBackend', () => { beforeEach(() => { clearBackendProbeCache(); mockVersionCheck.mockReset(); - mockVersionCheck.mockResolvedValue(true); + mockVersionCheck.mockResolvedValue(CLICKHOUSE_26_10); mockFetch.mockReset(); }); @@ -74,7 +81,7 @@ describe('resolveClickhouseQueryBackend', () => { }); it('keeps a server that is too old without probing the handler', async () => { - mockVersionCheck.mockResolvedValue(false); + mockVersionCheck.mockResolvedValue(CLICKHOUSE_26_5); await expect(resolveKind()).resolves.toBe('table-function'); await expect(resolveKind()).resolves.toBe('table-function'); @@ -196,3 +203,65 @@ describe('resolveClickhouseQueryBackend', () => { }); }); }); + +describe('resolveClickhouseLabelBackend', () => { + const resolveLabels = (promqlBackend?: PromqlSourceBackend) => + resolveClickhouseLabelBackend( + // @ts-expect-error mock connection carries only the fields the resolver reads + target(undefined, promqlBackend), + ); + + beforeEach(() => { + clearBackendProbeCache(); + mockVersionCheck.mockReset(); + mockFetch.mockReset(); + mockFetch.mockImplementation(async () => handlerAnswer()); + }); + + it.each([[undefined], ['auto' as const], ['clickhouse-http' as const]])( + 'uses the HTTP API on 26.9+ with the handler when the setting is %s', + async setting => { + mockVersionCheck.mockResolvedValue(CLICKHOUSE_26_10); + + await expect(resolveLabels(setting)).resolves.toBe('clickhouse-http'); + }, + ); + + // 26.6-26.8 answers queries over HTTP but not label lookups, so a source on + // the HTTP API must not lose its labels there. + it.each([[undefined], ['clickhouse-http' as const]])( + 'reads labels with SQL on 26.8 even though queries use the HTTP API (setting %s)', + async setting => { + mockVersionCheck.mockResolvedValue(CLICKHOUSE_26_8); + + await expect(resolveLabels(setting)).resolves.toBe('sql'); + await expect(resolveKind(undefined, setting)).resolves.toBe( + 'clickhouse-http', + ); + }, + ); + + it('reads labels with SQL when the server has no handler', async () => { + mockVersionCheck.mockResolvedValue(CLICKHOUSE_26_10); + mockFetch.mockImplementation(async () => noHandlerAnswer()); + + await expect(resolveLabels()).resolves.toBe('sql'); + }); + + it('reads labels with SQL for a table-function source, without a probe', async () => { + await expect(resolveLabels('table-function')).resolves.toBe('sql'); + + expect(mockVersionCheck).not.toHaveBeenCalled(); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it('shares the kept probe answer with queries', async () => { + mockVersionCheck.mockResolvedValue(CLICKHOUSE_26_10); + + await resolveKind(); + await expect(resolveLabels()).resolves.toBe('clickhouse-http'); + + expect(mockVersionCheck).toHaveBeenCalledTimes(1); + expect(mockFetch).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/api/src/controllers/__tests__/timeseriesEngine.test.ts b/packages/api/src/controllers/__tests__/timeseriesEngine.test.ts index f1f0d2b36e..499d2aebc1 100644 --- a/packages/api/src/controllers/__tests__/timeseriesEngine.test.ts +++ b/packages/api/src/controllers/__tests__/timeseriesEngine.test.ts @@ -1,8 +1,41 @@ +import { ClickHouseError } from '@clickhouse/client-common'; +import { ClickHouseQueryError } from '@hyperdx/common-utils/dist/clickhouse'; + import { formatMatrixResponse, formatVectorResponse, + isNoTimeRangesTableError, } from '@/controllers/timeseriesEngine'; +describe('isNoTimeRangesTableError', () => { + // The shape ClickhouseClient throws: the server's error wrapped as `cause`. + const queryError = (type: string) => + Object.assign(new ClickHouseQueryError('query failed', 'DESCRIBE ...'), { + cause: new ClickHouseError({ message: 'failed', code: '0', type }), + }); + + it.each([ + ['UNKNOWN_FUNCTION', 'servers before 26.10'], + ['UNKNOWN_TABLE', '26.10 and later'], + ])('accepts %s (%s)', type => { + expect(isNoTimeRangesTableError(queryError(type))).toBe(true); + }); + + it('rejects any other ClickHouse error', () => { + expect(isNoTimeRangesTableError(queryError('TIMEOUT_EXCEEDED'))).toBe( + false, + ); + }); + + it('rejects an error without a ClickHouse type, whatever its message', () => { + expect( + isNoTimeRangesTableError( + new Error('Unknown table function timeSeriesTimeRanges'), + ), + ).toBe(false); + }); +}); + describe('formatMatrixResponse', () => { it('converts prometheusQueryRange rows into Prometheus matrix shape', () => { const rows = [ diff --git a/packages/api/src/controllers/promql.ts b/packages/api/src/controllers/promql.ts index 3e687c0b20..2227194eff 100644 --- a/packages/api/src/controllers/promql.ts +++ b/packages/api/src/controllers/promql.ts @@ -18,9 +18,10 @@ import { ClickhouseClient } from '@/clickhouse'; import { getConnectionById } from '@/controllers/connection'; import { getSource } from '@/controllers/sources'; import { - connectionSupportsPrometheusHttpApi, + connectionPrometheusHttpApiSupport, PROMETHEUS_MAX_EXECUTION_SEC, PROMETHEUS_MAX_RESULT_ROWS, + type PrometheusHttpApiSupport, queryInstantViaTableFunction, queryLabelNames, queryLabelValues, @@ -486,11 +487,17 @@ export function clearBackendProbeCache(): void { /** The probe could not tell, so its outcome must not be kept. */ class InconclusiveProbeError extends Error {} +const NO_PROMETHEUS_HTTP_API: PrometheusHttpApiSupport = { + query: false, + labels: false, +}; + /** - * Asks a ClickHouse connection whether it answers PromQL over HTTP. Two - * conditions, cheapest first: the server is new enough (26.6+), and the - * prometheus_api_v1 handler is actually configured — a self-managed server - * needs an `` rule for that, which a stock install lacks. The + * Asks a ClickHouse connection which parts of the Prometheus HTTP API it + * serves. Two conditions, cheapest first: the server is new enough (26.6+ for + * queries, 26.9+ for label lookups), and the prometheus_api_v1 handler is + * actually configured — a self-managed server needs an `` rule + * for that, which a stock install lacks. The * handler answers every request, error or not, with Prometheus JSON * (`{status, ...}`); a server without it answers a plain-text 404. * `format_query` is used as the probe because it is the one endpoint that @@ -504,13 +511,13 @@ class InconclusiveProbeError extends Error {} async function probePrometheusHttpApi( client: ClickhouseClient, connection: { id: string; host: string; username: string; password?: string }, -): Promise { - const supported = await connectionSupportsPrometheusHttpApi({ +): Promise { + const supported = await connectionPrometheusHttpApiSupport({ client, connectionId: connection.id, }); if (supported === undefined) throw new InconclusiveProbeError(); - if (!supported) return false; + if (!supported.query) return NO_PROMETHEUS_HTTP_API; let status: number; let text: string; @@ -531,27 +538,27 @@ async function probePrometheusHttpApi( throw new InconclusiveProbeError(); } - if (typeof parseJSON(text)?.status === 'string') return true; - if (status === 404) return false; + if (typeof parseJSON(text)?.status === 'string') return supported; + if (status === 404) return NO_PROMETHEUS_HTTP_API; throw new InconclusiveProbeError(); } /** - * Whether a ClickHouse connection answers PromQL over HTTP, keeping a - * definitive answer for BACKEND_PROBE_TTL_MS so each query does not pay for a - * `SELECT version()` and a probe request first. Keyed on the host as well as - * the connection, so editing a connection's host drops its answer. Concurrent - * callers share one probe. An inconclusive probe is answered "no" for this - * request only. + * Which parts of the Prometheus HTTP API a ClickHouse connection serves, + * keeping a definitive answer for BACKEND_PROBE_TTL_MS so each request does + * not pay for a `SELECT version()` and a probe request first. Keyed on the + * host as well as the connection, so editing a connection's host drops its + * answer. Concurrent callers share one probe. An inconclusive probe is + * answered "none" for this request only. */ -async function clickhouseServesPrometheusHttpApi( +async function prometheusHttpApiSupport( client: ClickhouseClient, connection: { id: string; host: string; username: string; password?: string }, -): Promise { +): Promise { const key = `${connection.id}|${connection.host}`; const span = trace.getActiveSpan(); - const kept = backendProbeCache.get(key); + const kept = backendProbeCache.get(key); if (kept !== undefined) { span?.setAttribute('hyperdx.promql.backend_probe', 'cached'); return kept; @@ -567,7 +574,7 @@ async function clickhouseServesPrometheusHttpApi( return served; } catch { span?.setAttribute('hyperdx.promql.backend_probe', 'inconclusive'); - return false; + return NO_PROMETHEUS_HTTP_API; } } @@ -586,10 +593,11 @@ export async function connectionServesPrometheusHttpApi(connection: { isPrometheusEndpoint?: boolean; }): Promise { if (connection.isPrometheusEndpoint) return false; - return clickhouseServesPrometheusHttpApi( + const support = await prometheusHttpApiSupport( newPromqlClickhouseClient(connection), connection, ); + return support.query; } type ClickhouseQueryBackend = @@ -631,7 +639,7 @@ export async function resolveClickhouseQueryBackend({ let useHttpApi: boolean; if (promqlBackend === 'auto') { - useHttpApi = await clickhouseServesPrometheusHttpApi(client, connection); + useHttpApi = (await prometheusHttpApiSupport(client, connection)).query; } else { span?.setAttribute('hyperdx.promql.backend_probe', 'skipped'); useHttpApi = promqlBackend === 'clickhouse-http'; @@ -657,6 +665,36 @@ export async function resolveClickhouseQueryBackend({ }; } +/** + * How to answer a label lookup (`/labels`, `/label//values`) on a + * ClickHouse target: through the Prometheus HTTP API, or with SQL against the + * tags table. The handler serves label lookups only from 26.9, three releases + * after it serves queries, so a source on the HTTP API reads labels with SQL + * on 26.6-26.8 rather than losing them. That holds for a source set to + * `clickhouse-http` too, so it is probed like `auto`. A source set to + * `table-function` reads them with SQL, with no probe. + */ +export async function resolveClickhouseLabelBackend({ + connection, + promqlBackend = 'auto', +}: PromqlTarget): Promise<'clickhouse-http' | 'sql'> { + const span = trace.getActiveSpan(); + span?.setAttribute('hyperdx.promql.backend_setting', promqlBackend); + + let labelBackend: 'clickhouse-http' | 'sql' = 'sql'; + if (promqlBackend === 'table-function') { + span?.setAttribute('hyperdx.promql.backend_probe', 'skipped'); + } else { + const support = await prometheusHttpApiSupport( + newPromqlClickhouseClient(connection), + connection, + ); + if (support.labels) labelBackend = 'clickhouse-http'; + } + span?.setAttribute('hyperdx.promql.label_backend', labelBackend); + return labelBackend; +} + /** How to evaluate PromQL on a target. Probes ClickHouse targets for the HTTP API. */ export async function resolvePromqlQueryBackend( target: PromqlTarget, diff --git a/packages/api/src/controllers/timeseriesEngine.ts b/packages/api/src/controllers/timeseriesEngine.ts index 5c76bd8ef2..6acf667016 100644 --- a/packages/api/src/controllers/timeseriesEngine.ts +++ b/packages/api/src/controllers/timeseriesEngine.ts @@ -3,7 +3,10 @@ import { chSql, concatChSql, } from '@hyperdx/common-utils/dist/clickhouse'; -import { supportsPrometheusHttpApi } from '@hyperdx/common-utils/dist/core/clickhouseVersion'; +import { + supportsPrometheusHttpApi, + supportsPrometheusLabelsApi, +} from '@hyperdx/common-utils/dist/core/clickhouseVersion'; import { Metadata, MetadataCache, @@ -15,6 +18,7 @@ import { } from '@hyperdx/common-utils/dist/types'; import { ClickhouseClient } from '@/clickhouse'; +import { getClickHouseErrorType } from '@/utils/clickhouseErrors'; import logger from '@/utils/logger'; export const PROMETHEUS_MAX_EXECUTION_SEC = 30; @@ -33,14 +37,21 @@ export type TimeSeriesTagsQueryArgs = { signal?: AbortSignal; }; -// What a table without a time ranges table answers (version 7 or earlier, or -// store_time_ranges off): servers before 26.10 have no timeSeriesTimeRanges(), -// newer ones reject the table. Any other error is unexpected. -const isNoTimeRangesTableError = (e: unknown): boolean => - e instanceof Error && - /Unknown table function timeSeriesTimeRanges|has no TimeRanges target table/.test( - e.message, - ); +/** + * What a table without a time ranges table answers (version 7 or earlier, or + * store_time_ranges off): servers before 26.10 have no timeSeriesTimeRanges() + * (UNKNOWN_FUNCTION), newer ones reject the table (UNKNOWN_TABLE). Any other + * error is unexpected. + * + * 26.10 also answers UNKNOWN_TABLE when the TimeSeries table itself is + * missing. That case already failed, and warned, on the Tags probe that + * timeSeriesTimeBounds runs first, so treating it as expected here hides + * nothing. + */ +export const isNoTimeRangesTableError = (e: unknown): boolean => { + const type = getClickHouseErrorType(e); + return type === 'UNKNOWN_FUNCTION' || type === 'UNKNOWN_TABLE'; +}; /** * Where the given TimeSeries table keeps each series' time range, if anywhere: @@ -60,6 +71,7 @@ async function timeSeriesTimeBounds({ database: string; table: string; }): Promise<'tags' | 'timeRanges' | undefined> { + // Tags first: a version 7 table returns there without a second query. for (const [innerTableType, bounds] of [ ['Tags', 'tags'], ['TimeRanges', 'timeRanges'], @@ -170,7 +182,7 @@ async function getSeriesFilterConditions({ // that would answer a different question. if (timeBounds == null) { throw new Error( - 'match[] requires a TimeSeries table that stores time ranges (store_time_ranges = 1, or store_min_time_and_max_time = 1 before version 8)', + 'match[] requires a TimeSeries table that stores time ranges (store_time_ranges = 1, or store_min_time_and_max_time = 1 before version 8), or the prometheus_api_v1 HTTP handler on ClickHouse 26.9+', ); } conditions.push( @@ -451,19 +463,29 @@ export async function queryInstantViaTableFunction({ } /** - * Whether the connection's ClickHouse is new enough for the Prometheus HTTP - * API, or `undefined` when its version could not be read. `SELECT version()` - * runs each call (throwaway cache); callers that keep the answer decide how - * long to. + * The parts of ClickHouse's Prometheus HTTP API a server can serve: queries + * (26.6+) and label lookups (26.9+). + */ +export type PrometheusHttpApiSupport = { query: boolean; labels: boolean }; + +/** + * Which parts of the Prometheus HTTP API the connection's ClickHouse is new + * enough for, or `undefined` when its version could not be read. + * `SELECT version()` runs each call (throwaway cache); callers that keep the + * answer decide how long to. */ -export async function connectionSupportsPrometheusHttpApi({ +export async function connectionPrometheusHttpApiSupport({ client, connectionId, }: { client: ClickhouseClient; connectionId: string; -}): Promise { +}): Promise { const metadata = new Metadata(client, new MetadataCache()); const version = await metadata.getServerVersion({ connectionId }); - return version == null ? undefined : supportsPrometheusHttpApi(version); + if (version == null) return undefined; + return { + query: supportsPrometheusHttpApi(version), + labels: supportsPrometheusLabelsApi(version), + }; } diff --git a/packages/api/src/mcp/__tests__/query.test.ts b/packages/api/src/mcp/__tests__/query.test.ts index 1fb8106a59..c45606b11a 100644 --- a/packages/api/src/mcp/__tests__/query.test.ts +++ b/packages/api/src/mcp/__tests__/query.test.ts @@ -17,7 +17,6 @@ import { assertSourceKindMatchesSelect, clickHouseErrorResult, errorHint, - getClickHouseErrorType, INCREASE_TOP_N_CAP, isServerError, mergeWhereIntoSelectItems, @@ -34,6 +33,7 @@ import { } from '@/mcp/tools/query/schemas'; import { defaultOrderBy, resolveOrderBy } from '@/mcp/tools/query/table'; import { getErrorCategory } from '@/mcp/utils/errors'; +import { getClickHouseErrorType } from '@/utils/clickhouseErrors'; describe('parseTimeRange', () => { it('should return default range (last 15 minutes) when no arguments provided', () => { diff --git a/packages/api/src/mcp/tools/query/helpers.ts b/packages/api/src/mcp/tools/query/helpers.ts index 98871ea467..282bf2f056 100644 --- a/packages/api/src/mcp/tools/query/helpers.ts +++ b/packages/api/src/mcp/tools/query/helpers.ts @@ -1,7 +1,4 @@ -import { - ClickHouseError, - type ClickHouseSettings, -} from '@clickhouse/client-common'; +import { type ClickHouseSettings } from '@clickhouse/client-common'; import { getHeatmapMode } from '@hyperdx/common-utils/dist/core/heatmap'; import { getMetadata } from '@hyperdx/common-utils/dist/core/metadata'; import { PromqlChartError } from '@hyperdx/common-utils/dist/core/promqlChart'; @@ -45,6 +42,7 @@ import { isConfigTile, } from '@/routers/external-api/v2/utils/dashboards'; import { isQueryTimeoutError } from '@/tasks/checkAlerts/errors'; +import { isClickHouseError } from '@/utils/clickhouseErrors'; import { trimToolResponse } from '@/utils/trimToolResponse'; import type { ExternalDashboardTileWithId } from '@/utils/zod'; import { externalDashboardTileSchemaWithId } from '@/utils/zod'; @@ -843,51 +841,6 @@ const SERVER_NODE_ERROR_CODES = new Set([ 'UND_ERR_CONNECT_TIMEOUT', ]); -/** - * Check whether an error is a ClickHouseError, using both `instanceof` - * and a constructor-name fallback. The fallback handles the case where - * multiple copies of `@clickhouse/client-common` are installed (e.g. - * the root workspace uses one version while `common-utils` bundles - * another). In that scenario, `instanceof` fails because the class - * identities are different even though the shapes are identical. - */ -function isClickHouseError( - err: unknown, -): err is ClickHouseError & { type: string } { - if (err instanceof ClickHouseError) return true; - if ( - err instanceof Error && - err.constructor?.name === 'ClickHouseError' && - 'type' in err && - typeof (err as Record).type === 'string' - ) { - return true; - } - return false; -} - -/** - * Extract the ClickHouse error `type` from an error, walking `.cause` to - * find the original `ClickHouseError` from `@clickhouse/client-common`. - * - * Uses `instanceof` with a constructor-name fallback to handle duplicate - * package installations across the monorepo (see `isClickHouseError`). - * - * @internal Exported for testing only. - */ -export function getClickHouseErrorType(e: unknown): string | undefined { - if (!(e instanceof Error)) return undefined; - // ClickHouseQueryError wraps the original ClickHouseError as .cause - if (isClickHouseError(e.cause)) { - return e.cause.type; - } - // Direct ClickHouseError (has .type on itself) - if (isClickHouseError(e)) { - return e.type; - } - return undefined; -} - /** * Check whether an error represents a system-level infrastructure failure * rather than a user query issue. Covers both ClickHouse server-side error diff --git a/packages/api/src/routers/api/__tests__/prometheus.int.test.ts b/packages/api/src/routers/api/__tests__/prometheus.int.test.ts index b5ed7ddfab..3c67422fa2 100644 --- a/packages/api/src/routers/api/__tests__/prometheus.int.test.ts +++ b/packages/api/src/routers/api/__tests__/prometheus.int.test.ts @@ -17,6 +17,7 @@ import { clickhousePrometheusUpstream, joinPrometheusUpstreamUrl, } from '@/controllers/promql'; +import { PROMETHEUS_MAX_RESULT_ROWS } from '@/controllers/timeseriesEngine'; import { DEFAULT_DATABASE, dropTimeSeriesTable, @@ -1823,6 +1824,8 @@ describe('prometheus router', () => { // controllers/__tests__/timeseriesEngine.int.test.ts. What only the route // can show is that query-string params reach it intact — bounds in unix // seconds where the controller takes milliseconds, and a stringified limit. + // The sources are set to table-function so this is the SQL path on any + // server version. describe('ClickHouse-backed', () => { const TABLE = 'prom_label_values_bounded_test'; const OLD_METRIC = 'label_values_old_metric'; @@ -1840,6 +1843,7 @@ describe('prometheus router', () => { const { agent, team } = await getLoggedInAgent(server); const source = await seedClickHouseSource(team._id, { tableName: TABLE, + promqlBackend: 'table-function', }); const res = await agent .get(`/v1/prometheus/label/${labelName}/values`) @@ -1898,6 +1902,7 @@ describe('prometheus router', () => { const { agent, team } = await getLoggedInAgent(server); const source = await seedClickHouseSource(team._id, { tableName: TABLE, + promqlBackend: 'table-function', }); const res = await agent @@ -1987,6 +1992,7 @@ describe('prometheus router', () => { const { agent, team } = await getLoggedInAgent(server); const source = await seedClickHouseSource(team._id, { tableName: TABLE, + promqlBackend: 'table-function', }); const res = await agent @@ -2076,6 +2082,7 @@ describe('prometheus router', () => { expect(mockFetch).not.toHaveBeenCalled(); }); + // Set to table-function, like the label values tests above. describe('ClickHouse-backed', () => { const TABLE = 'prom_labels_test'; const OLD_METRIC = 'labels_old_metric'; @@ -2091,6 +2098,7 @@ describe('prometheus router', () => { const { agent, team } = await getLoggedInAgent(server); const source = await seedClickHouseSource(team._id, { tableName: TABLE, + promqlBackend: 'table-function', }); const res = await agent .get('/v1/prometheus/labels') @@ -2189,6 +2197,7 @@ describe('prometheus router', () => { const { agent, team } = await getLoggedInAgent(server); const source = await seedClickHouseSource(team._id, { tableName: TABLE, + promqlBackend: 'table-function', }); const res = await agent @@ -2208,6 +2217,227 @@ describe('prometheus router', () => { }); }); + describe("label lookups through ClickHouse's prometheus_api_v1 handler", () => { + const ROUTES = [ + ['/v1/prometheus/labels', '/labels'], + ['/v1/prometheus/label/job/values', '/label/job/values'], + ] as const; + + const stubServerVersion = (version: [number, number, number, number]) => + jest + .spyOn(Metadata.prototype, 'getServerVersion') + .mockResolvedValue(version); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it.each(ROUTES)( + "proxies %s with the source's table, the request's params and the connection's credentials", + async (route, apiPath) => { + stubServerVersion([26, 10, 0, 0]); + const { agent, team } = await getLoggedInAgent(server); + const source = await seedClickHouseSource(team._id, { + databaseName: 'otel', + tableName: 'metrics_ts', + }); + const promResponse = { status: 'success', data: ['api'] }; + mockFetch + .mockResolvedValueOnce(handlerProbeResponse()) + .mockResolvedValueOnce(fakeUpstreamResponse(promResponse)); + + const res = await agent + .get(route) + .set( + QUERY_ATTRIBUTION_HEADER, + buildLogComment({ surface: 'dashboard', tile: 'tile-1' })!, + ) + .query( + `sourceId=${source._id.toString()}&start=1700000000&end=1700000060` + + `&limit=25&database=other_db&${matchQueryString(['up'])}`, + ) + .expect(200); + + expect(res.body).toEqual(promResponse); + expect(mockFetch).toHaveBeenCalledTimes(2); + const [calledUrl, init] = mockFetch.mock.calls[1]; + const url = new URL(String(calledUrl)); + expect(url.pathname).toBe( + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}${apiPath}`, + ); + expect(url.searchParams.getAll('database')).toEqual(['otel']); + expect(url.searchParams.getAll('table')).toEqual(['metrics_ts']); + expect(url.searchParams.get('start')).toBe('1700000000'); + expect(url.searchParams.get('end')).toBe('1700000060'); + expect(url.searchParams.get('limit')).toBe('25'); + expect(url.searchParams.getAll('match[]')).toEqual(['up']); + expect(url.searchParams.has('sourceId')).toBe(false); + expect(JSON.parse(url.searchParams.get('log_comment')!)).toMatchObject({ + surface: 'dashboard', + tile: 'tile-1', + }); + expect(init?.headers).toMatchObject({ + 'X-ClickHouse-User': config.CLICKHOUSE_USER, + 'X-ClickHouse-Key': config.CLICKHOUSE_PASSWORD, + 'X-ClickHouse-Query-Id': expect.stringMatching(/^hdx-dashboard-/), + }); + }, + ); + + // The handler returns all values in one row, which max_result_rows can't cap. + it.each([ + ['no limit', ''], + ['limit=0', '&limit=0'], + ['a limit over the cap', `&limit=${PROMETHEUS_MAX_RESULT_ROWS + 1}`], + ])( + 'caps the values the handler returns when the request has %s', + async (_case, limitQuery) => { + stubServerVersion([26, 10, 0, 0]); + const { agent, team } = await getLoggedInAgent(server); + const source = await seedClickHouseSource(team._id); + mockFetch + .mockResolvedValueOnce(handlerProbeResponse()) + .mockResolvedValueOnce( + fakeUpstreamResponse({ status: 'success', data: [] }), + ); + + await agent + .get('/v1/prometheus/label/job/values') + .query(`sourceId=${source._id.toString()}${limitQuery}`) + .expect(200); + + const url = new URL(String(mockFetch.mock.calls[1][0])); + expect(url.searchParams.getAll('limit')).toEqual([ + String(PROMETHEUS_MAX_RESULT_ROWS), + ]); + }, + ); + + // 26.8's handler answers label lookups with a 400 ("not implemented"), so + // the route must never send them there. + it.each(ROUTES)( + 'reads %s with SQL on ClickHouse 26.8, whose handler serves only queries', + async route => { + stubServerVersion([26, 8, 36, 3]); + const { agent, team } = await getLoggedInAgent(server); + const source = await seedClickHouseSource(team._id, { + tableName: 'no_such_table_for_label_sql', + }); + mockFetch.mockResolvedValueOnce(handlerProbeResponse()); + + const res = await agent + .get(route) + .query({ sourceId: source._id.toString() }) + .expect(400); + + // Only the probe reached the handler; the SQL lookup failed on the + // missing table. + expect(mockFetch).toHaveBeenCalledTimes(1); + expect(res.body.error).toMatch(/no_such_table_for_label_sql/); + }, + ); + + // Needs ClickHouse 26.9+, whose handler serves label lookups. + describe('against the CI ClickHouse', () => { + const TABLE = 'prom_labels_http_api_live'; + const START = 1700000000; + + let agent: Awaited>['agent']; + let sourceId: string; + + beforeEach(async () => { + mockFetch.mockImplementation(realFetch); + const loggedIn = await getLoggedInAgent(server); + agent = loggedIn.agent; + const source = await seedClickHouseSource(loggedIn.team._id, { + tableName: TABLE, + }); + sourceId = source._id.toString(); + }); + + const lookup = async (route: string, query: string) => { + const res = await agent + .get(route) + .query(`sourceId=${sourceId}${query}`) + .expect(200); + const handlerPaths = mockFetch.mock.calls + .map(([url]) => new URL(String(url)).pathname) + .filter( + path => path !== `${CLICKHOUSE_PROMETHEUS_API_PREFIX}/format_query`, + ); + return { body: res.body, handlerPaths }; + }; + + beforeAll(async () => { + await seedTimeSeriesTagsTable({ + table: TABLE, + series: [ + { + metricName: 'live_up', + tags: { job: 'api' }, + startSec: START, + endSec: START + 60, + }, + { + metricName: 'live_up', + tags: { job: 'web', region: 'eu' }, + startSec: START, + endSec: START + 60, + }, + ], + withSamples: true, + }); + }); + + afterAll(async () => { + await dropTimeSeriesTable({ table: TABLE }); + }); + + it('answers /labels from the handler', async () => { + const { body, handlerPaths } = await lookup( + '/v1/prometheus/labels', + '', + ); + + expect(body).toEqual({ + status: 'success', + data: ['__name__', 'job', 'region'], + }); + expect(handlerPaths).toEqual([ + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}/labels`, + ]); + }); + + it('answers /label//values narrowed by match[] and the window', async () => { + const route = '/v1/prometheus/label/job/values'; + const window = `&start=${START}&end=${START + 60}`; + + expect((await lookup(route, '')).body).toEqual({ + status: 'success', + data: ['api', 'web'], + }); + const narrowed = await lookup( + route, + `${window}&${matchQueryString(['live_up{region="eu"}'])}`, + ); + expect(narrowed.body).toEqual({ status: 'success', data: ['web'] }); + expect(narrowed.handlerPaths).toContain( + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}/label/job/values`, + ); + expect( + (await lookup(route, `&start=${START + 3600}&end=${START + 7200}`)) + .body, + ).toEqual({ status: 'success', data: [] }); + }); + + it('forwards limit', async () => { + const { body } = await lookup('/v1/prometheus/labels', '&limit=1'); + + expect(body).toMatchObject({ status: 'success', data: ['__name__'] }); + }); + }); + }); + describe('GET /v1/prometheus/query_exemplars', () => { it('returns 400 when query parameter is missing', async () => { const { agent } = await getLoggedInAgent(server); diff --git a/packages/api/src/routers/api/prometheus.ts b/packages/api/src/routers/api/prometheus.ts index b266bc8a31..be27d84050 100644 --- a/packages/api/src/routers/api/prometheus.ts +++ b/packages/api/src/routers/api/prometheus.ts @@ -17,10 +17,12 @@ import { clickhousePrometheusRequest, newPromqlClickhouseClient, PROMETHEUS_MAX_RESOLUTION, + resolveClickhouseLabelBackend, resolveClickhouseQueryBackend, resolvePromqlTarget, } from '@/controllers/promql'; import { + PROMETHEUS_MAX_RESULT_ROWS, queryInstantViaTableFunction, queryLabelNames, queryLabelValues, @@ -792,18 +794,19 @@ type ClickHouseLabelLookup = ( /** * Handles a Prometheus label lookup — `/labels` or `/label/:name/values` — from - * whichever backend the connection points at. + * whichever backend the connection points at. `apiPath` is the Prometheus API + * path below `/api/v1`, e.g. `/labels`. */ async function handleLabelLookup( req: express.Request, res: express.Response, { subject, - proxyPath, + apiPath, queryClickHouse, }: { subject: LabelLookupSubject; - proxyPath: string; + apiPath: string; queryClickHouse: ClickHouseLabelLookup; }, ) { @@ -832,31 +835,56 @@ async function handleLabelLookup( } const { connection, databaseName, tableName } = target; + const proxyParams = { + ...(start != null ? { start: String(start) } : {}), + ...(end != null ? { end: String(end) } : {}), + // Any non-negative integer. Pass 0 ("unlimited") on too: proxyToPrometheus + // sends it as an omitted key, which also clears a host-pinned `limit`. + ...(limit != null ? { limit: String(limit) } : {}), + // Restored under the name Prometheus expects + ...(match != null ? { 'match[]': match } : {}), + }; + // Proxy to Prometheus if endpoint is set if (connection.isPrometheusEndpoint) { backend = 'prometheus'; const status = await proxyToPrometheus( connection.host, - proxyPath, + `/api/v1${apiPath}`, + proxyParams, + res, + ); + recordProxyOutcome(status, subject, backend); + return; + } + + backend = 'clickhouse'; + if ((await resolveClickhouseLabelBackend(target)) === 'clickhouse-http') { + const { upstream, headers } = clickhousePrometheusRequest(connection); + // The handler returns every value in a single row, so the upstream's + // max_result_rows never applies. Cap the values themselves instead. + const cappedLimit = Math.min( + limit || PROMETHEUS_MAX_RESULT_ROWS, + PROMETHEUS_MAX_RESULT_ROWS, + ); + const status = await proxyToPrometheus( + upstream, + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}${apiPath}`, { - ...(start != null ? { start: String(start) } : {}), - ...(end != null ? { end: String(end) } : {}), - // `limit` is 0 or absent when validation passes (see the schema - // above); 0 means "unlimited" to Prometheus and must still be - // forwarded (`v == null` is the merge loop's own absence check), - // otherwise a request explicitly asking for unlimited results - // silently loses to a host-pinned `limit`. - ...(limit != null ? { limit: String(limit) } : {}), - // Restored under the name Prometheus expects - ...(match != null ? { 'match[]': match } : {}), + ...proxyParams, + limit: String(cappedLimit), + database: databaseName, + table: tableName, }, res, + headers, + CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, ); recordProxyOutcome(status, subject, backend); return; } - backend = 'clickhouse'; + // Servers before 26.9, or without the handler, or a table-function source const client = newPromqlClickhouseClient(connection); const startMs = start != null ? Math.floor(start * 1000) : undefined; @@ -892,7 +920,7 @@ async function handleLabelLookup( router.get('/labels', (req, res) => handleLabelLookup(req, res, { subject: 'labels', - proxyPath: '/api/v1/labels', + apiPath: '/labels', queryClickHouse: queryLabelNames, }), ); @@ -909,7 +937,7 @@ router.get('/label/:name/values', (req, res) => { return handleLabelLookup(req, res, { subject: 'label_values', - proxyPath: `/api/v1/label/${labelName}/values`, + apiPath: `/label/${labelName}/values`, queryClickHouse: args => queryLabelValues({ ...args, labelName }), }); }); diff --git a/packages/api/src/utils/clickhouseErrors.ts b/packages/api/src/utils/clickhouseErrors.ts new file mode 100644 index 0000000000..cc0b1c1f0e --- /dev/null +++ b/packages/api/src/utils/clickhouseErrors.ts @@ -0,0 +1,45 @@ +import { ClickHouseError } from '@clickhouse/client-common'; + +/** + * Check whether an error is a ClickHouseError, using both `instanceof` + * and a constructor-name fallback. The fallback handles the case where + * multiple copies of `@clickhouse/client-common` are installed (e.g. + * the root workspace uses one version while `common-utils` bundles + * another). In that scenario, `instanceof` fails because the class + * identities are different even though the shapes are identical. + */ +export function isClickHouseError( + err: unknown, +): err is ClickHouseError & { type: string } { + if (err instanceof ClickHouseError) return true; + if ( + err instanceof Error && + err.constructor?.name === 'ClickHouseError' && + 'type' in err && + typeof err.type === 'string' + ) { + return true; + } + return false; +} + +/** + * Extract the ClickHouse error `type` (e.g. `UNKNOWN_TABLE`) from an error, + * walking `.cause` to find the original `ClickHouseError` from + * `@clickhouse/client-common`. + * + * Uses `instanceof` with a constructor-name fallback to handle duplicate + * package installations across the monorepo (see `isClickHouseError`). + */ +export function getClickHouseErrorType(e: unknown): string | undefined { + if (!(e instanceof Error)) return undefined; + // ClickHouseQueryError wraps the original ClickHouseError as .cause + if (isClickHouseError(e.cause)) { + return e.cause.type; + } + // Direct ClickHouseError (has .type on itself) + if (isClickHouseError(e)) { + return e.type; + } + return undefined; +} diff --git a/packages/common-utils/src/__tests__/clickhouseVersion.test.ts b/packages/common-utils/src/__tests__/clickhouseVersion.test.ts index 580bef9085..bac73aacbb 100644 --- a/packages/common-utils/src/__tests__/clickhouseVersion.test.ts +++ b/packages/common-utils/src/__tests__/clickhouseVersion.test.ts @@ -5,6 +5,7 @@ import { supportsDirectReadMap, supportsMergeTreeIndex, supportsPrometheusHttpApi, + supportsPrometheusLabelsApi, } from '@/core/clickhouseVersion'; type ClickHouseVersionTuple = readonly [number, number, number, number]; @@ -301,3 +302,25 @@ describe('supportsPrometheusHttpApi', () => { expect(supportsPrometheusHttpApi(undefined)).toBe(false); }); }); + +describe('supportsPrometheusLabelsApi', () => { + it.each([ + [[26, 9, 0, 0]], + [[26, 10, 3, 7]], + [[27, 0, 0, 0]], + ])('accepts %j', version => { + expect(supportsPrometheusLabelsApi(version)).toBe(true); + }); + + it.each([ + [[26, 8, 36, 3]], + [[26, 6, 0, 0]], + [[25, 12, 0, 0]], + ])('rejects %j', version => { + expect(supportsPrometheusLabelsApi(version)).toBe(false); + }); + + it('returns false when the version is unknown', () => { + expect(supportsPrometheusLabelsApi(undefined)).toBe(false); + }); +}); diff --git a/packages/common-utils/src/core/clickhouseVersion.ts b/packages/common-utils/src/core/clickhouseVersion.ts index e4d1278075..f26eb3216b 100644 --- a/packages/common-utils/src/core/clickhouseVersion.ts +++ b/packages/common-utils/src/core/clickhouseVersion.ts @@ -181,3 +181,16 @@ export function supportsPrometheusHttpApi( ): boolean { return isClickHouseVersionAtLeast(version, PROMETHEUS_HTTP_API_MIN); } + +/** + * First release whose Prometheus HTTP API serves `/api/v1/labels` and + * `/api/v1/label//values`. Older handlers answer both with a 400 + * ("not implemented"). + */ +const PROMETHEUS_LABELS_API_MIN: ClickHouseVersion = [26, 9, 0, 0]; + +export function supportsPrometheusLabelsApi( + version: ClickHouseVersion | undefined, +): boolean { + return isClickHouseVersionAtLeast(version, PROMETHEUS_LABELS_API_MIN); +} From 7b03880eb1f666e69846ad47c846b6279627b66b Mon Sep 17 00:00:00 2001 From: Karl Power <85935352+karl-power@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:00:42 +0100 Subject: [PATCH 04/55] feat(mcp): read PromQL label catalog from ClickHouse's Prometheus HTTP API (#3630) --- ...l-label-catalog-via-clickhouse-http-api.md | 7 + packages/api/src/controllers/promql.ts | 59 +++++--- .../mcp/__tests__/promqlSources.int.test.ts | 135 +++++++++++++++++- 3 files changed, 183 insertions(+), 18 deletions(-) create mode 100644 .changeset/promql-label-catalog-via-clickhouse-http-api.md diff --git a/.changeset/promql-label-catalog-via-clickhouse-http-api.md b/.changeset/promql-label-catalog-via-clickhouse-http-api.md new file mode 100644 index 0000000000..639e59bf8a --- /dev/null +++ b/.changeset/promql-label-catalog-via-clickhouse-http-api.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': patch +--- + +feat: read the MCP PromQL label catalog from ClickHouse's Prometheus HTTP API + +`describe_source` on a ClickHouse-backed PromQL source now lists label and metric names through the `prometheus_api_v1` handler on ClickHouse 26.9+, and falls back to SQL on older servers, servers without the handler, and sources set to `table-function`. diff --git a/packages/api/src/controllers/promql.ts b/packages/api/src/controllers/promql.ts index 2227194eff..59ed8a33e7 100644 --- a/packages/api/src/controllers/promql.ts +++ b/packages/api/src/controllers/promql.ts @@ -263,7 +263,9 @@ export type PromqlLabelCatalog = { /** * Lists the label names and metric names a PromQL source holds in * [startMs, endMs], at most `limit` of each. Returns `limit + 1` entries when - * there are more, so callers can tell the list was cut. + * there are more, so callers can tell the list was cut. A ClickHouse source + * reads them through the Prometheus HTTP API where resolveClickhouseLabelBackend + * allows it, and with SQL otherwise. */ export async function getPromqlLabelCatalog({ teamId, @@ -277,6 +279,7 @@ export async function getPromqlLabelCatalog({ source: { connection: { toString(): string }; from: { databaseName: string; tableName: string }; + promqlBackend?: PromqlSourceBackend; }; startMs: number; endMs: number; @@ -292,29 +295,51 @@ export async function getPromqlLabelCatalog({ throw new Error('Connection not found'); } + const params = { + start: String(startMs / 1000), + end: String(endMs / 1000), + limit: String(limit + 1), + }; + const fetchCatalog = (fetchLabels: (path: string) => Promise) => + Promise.all([ + fetchLabels('/labels'), + fetchLabels('/label/__name__/values'), + ]); + if (connection.isPrometheusEndpoint) { - const params = { - start: String(startMs / 1000), - end: String(endMs / 1000), - limit: String(limit + 1), - }; - const [labelNames, metricNames] = await Promise.all([ + const [labelNames, metricNames] = await fetchCatalog(path => fetchPrometheusData( connection.host, - '/api/v1/labels', + `/api/v1${path}`, params, labelListSchema, signal, ), - fetchPrometheusData( - connection.host, - '/api/v1/label/__name__/values', - params, + ); + return { backend: 'prometheus', labelNames, metricNames }; + } + + const { databaseName, tableName } = source.from; + const labelBackend = await resolveClickhouseLabelBackend({ + connection, + databaseName, + tableName, + promqlBackend: source.promqlBackend, + }); + if (labelBackend === 'clickhouse-http') { + const [labelNames, metricNames] = await fetchCatalog(path => { + const { upstream, headers } = clickhousePrometheusRequest(connection); + return fetchPrometheusData( + upstream, + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}${path}`, + { ...params, database: databaseName, table: tableName }, labelListSchema, signal, - ), - ]); - return { backend: 'prometheus', labelNames, metricNames }; + headers, + CLICKHOUSE_HTTP_API_UNAVAILABLE_MESSAGE, + ); + }); + return { backend: 'clickhouse', labelNames, metricNames }; } const args = { @@ -325,8 +350,8 @@ export async function getPromqlLabelCatalog({ requestTimeout: PROMETHEUS_FETCH_TIMEOUT_MS, }), connectionId: connection.id, - databaseName: source.from.databaseName, - tableName: source.from.tableName, + databaseName, + tableName, startMs, endMs, limit: limit + 1, diff --git a/packages/api/src/mcp/__tests__/promqlSources.int.test.ts b/packages/api/src/mcp/__tests__/promqlSources.int.test.ts index 8d4d794d34..b18de6eba7 100644 --- a/packages/api/src/mcp/__tests__/promqlSources.int.test.ts +++ b/packages/api/src/mcp/__tests__/promqlSources.int.test.ts @@ -1,8 +1,13 @@ +import { Metadata } from '@hyperdx/common-utils/dist/core/metadata'; import { SourceKind } from '@hyperdx/common-utils/dist/types'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import * as config from '@/config'; -import { PROMETHEUS_MAX_RESPONSE_BYTES } from '@/controllers/promql'; +import { + clearBackendProbeCache, + CLICKHOUSE_PROMETHEUS_API_PREFIX, + PROMETHEUS_MAX_RESPONSE_BYTES, +} from '@/controllers/promql'; import { DEFAULT_DATABASE, dropTimeSeriesTable, @@ -16,6 +21,7 @@ import { Source } from '@/models/source'; import { callTool, createTestClient, getFirstText } from './mcpTestUtils'; const mockFetch = jest.mocked(global.fetch); +const { realFetch } = globalThis as unknown as { realFetch: typeof fetch }; const TABLE = 'mcp_promql_sources'; @@ -88,6 +94,8 @@ describe('MCP PromQL sources', () => { username: config.CLICKHOUSE_USER, password: config.CLICKHOUSE_PASSWORD, }); + // Pinned so these tests read labels with SQL on any server version; the + // HTTP API path is covered on its own below. promqlSource = await Source.create({ kind: SourceKind.Promql, team: team._id, @@ -95,12 +103,15 @@ describe('MCP PromQL sources', () => { name: 'TimeSeries metrics', from: { databaseName: DEFAULT_DATABASE, tableName: TABLE }, timestampValueExpression: 'timestamp', + promqlBackend: 'table-function', }); }); afterEach(async () => { await client?.close(); await server.clearDBs(); + clearBackendProbeCache(); + mockFetch.mockReset(); }); afterAll(async () => { @@ -250,6 +261,128 @@ describe('MCP PromQL sources', () => { expect(output.error).toContain('returned more than 8 MB'); }); + describe("through ClickHouse's prometheus_api_v1 handler", () => { + let autoSource: any; + let versionSpy: jest.SpyInstance | undefined; + + const stubServerVersion = (version: [number, number, number, number]) => { + versionSpy = jest + .spyOn(Metadata.prototype, 'getServerVersion') + .mockResolvedValue(version); + }; + + const describeAutoSource = async () => { + const result = await callTool(client, 'clickstack_describe_source', { + sourceId: autoSource._id.toString(), + }); + expect(result.isError).toBeFalsy(); + return JSON.parse(getFirstText(result)); + }; + + const labelLookupUrls = () => + mockFetch.mock.calls + .map(([input]) => new URL(String(input))) + .filter( + url => + url.pathname !== + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}/format_query`, + ); + + beforeEach(async () => { + autoSource = await Source.create({ + kind: SourceKind.Promql, + team: team._id, + connection: promqlSource.connection, + name: 'TimeSeries metrics (auto)', + from: { databaseName: DEFAULT_DATABASE, tableName: TABLE }, + timestampValueExpression: 'timestamp', + }); + }); + + afterEach(() => { + versionSpy?.mockRestore(); + versionSpy = undefined; + }); + + it("sends the label lookups with the source's table and the connection's credentials", async () => { + stubServerVersion([26, 10, 0, 0]); + mockFetch.mockImplementation(async input => { + const { pathname } = new URL(String(input)); + if (pathname.endsWith('/format_query')) { + return prometheusResponse('up'); + } + return prometheusResponse( + pathname.endsWith('/label/__name__/values') + ? ['up'] + : ['__name__', 'job'], + ); + }); + + const output = await describeAutoSource(); + + expect(output.source).toMatchObject({ + backend: 'clickhouse', + table: `${DEFAULT_DATABASE}.${TABLE}`, + }); + expect(output.labelNames).toEqual(['__name__', 'job']); + expect(output.metricNames).toEqual(['up']); + const urls = labelLookupUrls(); + expect(urls.map(u => u.pathname).sort()).toEqual([ + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}/label/__name__/values`, + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}/labels`, + ]); + for (const url of urls) { + expect(url.searchParams.getAll('database')).toEqual([ + DEFAULT_DATABASE, + ]); + expect(url.searchParams.getAll('table')).toEqual([TABLE]); + expect(url.searchParams.get('start')).toBeTruthy(); + expect(url.searchParams.get('end')).toBeTruthy(); + expect(url.searchParams.get('limit')).toBe('201'); + } + for (const [input, init] of mockFetch.mock.calls) { + if (new URL(String(input)).pathname.endsWith('/format_query')) { + continue; + } + expect(init?.headers).toMatchObject({ + 'X-ClickHouse-User': config.CLICKHOUSE_USER, + 'X-ClickHouse-Key': config.CLICKHOUSE_PASSWORD, + 'X-ClickHouse-Query-Id': expect.stringMatching(/^hdx-mcp-/), + }); + } + }); + + // 26.8's handler answers label lookups with a 400 ("not implemented"). + it('reads labels with SQL on ClickHouse 26.8, whose handler serves only queries', async () => { + stubServerVersion([26, 8, 36, 3]); + mockFetch.mockImplementation(async () => prometheusResponse('up')); + + const output = await describeAutoSource(); + + expect(output.labelNames).toEqual(['__name__', 'instance', 'job']); + expect(output.metricNames).toEqual(['http_requests_total', 'up']); + expect(labelLookupUrls()).toEqual([]); + }); + + // Needs ClickHouse 26.9+, whose handler serves label lookups. + it('lists labels from the CI ClickHouse handler', async () => { + mockFetch.mockImplementation(realFetch); + + const output = await describeAutoSource(); + + expect(output.labelNames).toEqual(['__name__', 'instance', 'job']); + expect(output.metricNames).toEqual(['http_requests_total', 'up']); + expect( + labelLookupUrls() + .map(u => u.pathname) + .sort(), + ).toEqual([ + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}/label/__name__/values`, + `${CLICKHOUSE_PROMETHEUS_API_PREFIX}/labels`, + ]); + }); + }); + it('keeps promqlBackend through a describe -> rename -> save round trip', async () => { const pinned = await Source.create({ kind: SourceKind.Promql, From 7cfd333ea7b77ef8c375baa8836cc198190f8c58 Mon Sep 17 00:00:00 2001 From: Brandon Pereira Date: Thu, 12 Nov 2026 14:31:50 -0600 Subject: [PATCH 05/55] fix(mcp): drop the health verdict from clickstack_service_health (#3634) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary `clickstack_service_health` no longer tells the agent whether a service is critical, degraded or healthy. A healthy service used to get "report this service as steady, no action needed". That verdict comes from service-wide totals, so a regression confined to one endpoint, pod or attribute segment can sit under every threshold while the tool tells the agent to stop looking. In the `deploy-regression` eval, main calls the service with the bug "Healthy". Each service now carries only evidence: | | Before | After | |---|---|---| | Per-service field | `status: critical / degraded / healthy` | removed; `flags` and `score` stay | | Summary, nothing crossed | `Healthy: … normal variance; report this service as steady, no action needed.` | `No metric crossed a threshold vs yesterday: error rate 0.50% vs 0.49%, p95 120ms vs 115ms, requests 3000 vs 2900.` | | Summary, threshold crossed | `CRITICAL: error rate 8.00% vs 0.50%.` | `Crossed thresholds: error rate 8.00% vs 0.50%.` | | Report summary | `statusCounts: {critical, degraded, healthy}` | `servicesFlagged` | | Ordering | status, then new errors, then score | threshold-flagged services, then the rest; within each, new or growing errors first, then score | | Span attributes | `mcp.service_health.critical_count`, `degraded_count` | `mcp.service_health.flagged_count` | The tool description and `usage` now say that thresholds apply to service-wide totals and point to `clickstack_table` breakdowns before a service is ruled out. "No flags is a valid result for a routine check" stays, so status reports are not pushed into escalating. `statusCounts` and per-service `status` are gone from the response. Both are MCP output read by agents; nothing else in the repo consumes them. ## Evals A/B with `packages/hdx-eval`: branch (slot 99) vs `main` (slot 98), both built from `02f6fd060`, identical seeded data, `claude-opus-4-6`. | Scenario | Runs/arm | Branch | Main | Δ | Tool calls (branch / main) | |---|---|---|---|---|---| | `service-health-check` | 3 | 76% | 75% | +1 | 7.7 / 5.7 | | `error-root-cause` | 3 | 99% | 98% | +1 | 10.3 / 9.0 | | `segmented-regression` | 8 | 75.5% | 71.6% | +3.9 | 14.9 / 17.1 | | `deploy-regression` | 8 | 70.3% | 74.6% | −4.3 | 15.6 / 13.9 | | `quiet-saturation` | 8 | 84.3% | 88.8% | −4.5 | 19.1 / 16.8 | | **Average** | | **81.0%** | **81.6%** | **−0.6** | | The change is neutral on scores. Per-run spread within an arm is 15–20 points, so no difference is significant (the largest has t ≈ 1); `segmented-regression` went from −11 after 3 runs to +13 over the next 5. Routine checks did not get more alarmist: the judge scored `service-health-check` 8 points higher on the branch. Its regex false-alarm checks scored it lower, but they mostly match negated phrases such as "not ongoing" and "not escalation-worthy". Agents make a few more tool calls in most scenarios once the tool stops saying "no action needed". ### How to reproduce **Starting point:** local full stack (`yarn dev`) with trace data, and an MCP client such as `npx @modelcontextprotocol/inspector` connected to the local MCP endpoint (see `MCP.md`). **On `main`:** 1. Call `clickstack_list_sources` and copy a `kind: "trace"` source ID. 2. Call `clickstack_service_health` with `{ "sourceId": "" }`. 3. Each service has a `status`, and steady services read "Healthy: … no action needed." **On this branch:** 1. Repeat the call. 2. There is no `status` field. Summaries state the crossed thresholds or the current vs comparison values, and `summary.servicesFlagged` replaces `statusCounts`. ### How to test on Vercel preview N/A — non-UI change. ### References - Linear Issue: HDX-5877 - Related PRs: #3411 (added `clickstack_service_health`) --- .changeset/service-health-no-verdict.md | 13 ++ .../__tests__/serviceHealthTool.int.test.ts | 19 +-- .../query/__tests__/serviceHealthRank.test.ts | 142 ++++++++++++++++-- .../mcp/tools/query/serviceHealth/index.ts | 17 +-- .../src/mcp/tools/query/serviceHealth/rank.ts | 31 ++-- .../mcp/tools/query/serviceHealth/report.ts | 55 ++++--- .../mcp/tools/query/serviceHealth/summary.ts | 24 +-- 7 files changed, 208 insertions(+), 93 deletions(-) create mode 100644 .changeset/service-health-no-verdict.md diff --git a/.changeset/service-health-no-verdict.md b/.changeset/service-health-no-verdict.md new file mode 100644 index 0000000000..31d1df9e56 --- /dev/null +++ b/.changeset/service-health-no-verdict.md @@ -0,0 +1,13 @@ +--- +'@hyperdx/api': patch +--- + +fix(mcp): drop the health verdict from clickstack_service_health + +The tool no longer labels services critical, degraded or healthy, and no longer +tells agents a service needs "no action". Each service keeps its threshold +flags, score and a factual summary, so agents reason from the numbers instead of +a verdict that service-wide totals can get wrong. `summary.statusCounts` is +replaced by `summary.servicesFlagged`, and the span attributes +`mcp.service_health.critical_count` and `mcp.service_health.degraded_count` are +replaced by `mcp.service_health.flagged_count`. diff --git a/packages/api/src/mcp/__tests__/serviceHealthTool.int.test.ts b/packages/api/src/mcp/__tests__/serviceHealthTool.int.test.ts index be604d69eb..271d7711f6 100644 --- a/packages/api/src/mcp/__tests__/serviceHealthTool.int.test.ts +++ b/packages/api/src/mcp/__tests__/serviceHealthTool.int.test.ts @@ -32,7 +32,6 @@ type Span = { type ServiceReport = { service: string; - status: string; flags: string[]; current: { requests: number; @@ -218,23 +217,21 @@ describe('MCP Service Health Tool', () => { ]); }); - it('ranks regressions first and leaves steady services healthy', async () => { + it('ranks regressions first and leaves steady services unflagged', async () => { const { summary, services } = parse(await call()); - expect(services.map(s => [s.service, s.status])).toEqual([ - [svc('erroring'), 'critical'], - [svc('slow'), 'degraded'], - [svc('steady'), 'healthy'], + expect(services.map(s => s.service)).toEqual([ + svc('erroring'), + svc('slow'), + svc('steady'), ]); + expect(services[0]).not.toHaveProperty('status'); + expect(services[2].flags).toEqual([]); expect(services[0].flags).toEqual( expect.arrayContaining(['error_rate_up', 'high_error_rate']), ); expect(services[1].flags).toContain('latency_up'); expect(services[1].current.p95Ms).toBeCloseTo(600, -1); - expect(summary.statusCounts).toEqual({ - critical: 1, - degraded: 1, - healthy: 1, - }); + expect(summary.servicesFlagged).toBe(2); }); it('counts server spans only by default', async () => { diff --git a/packages/api/src/mcp/tools/query/__tests__/serviceHealthRank.test.ts b/packages/api/src/mcp/tools/query/__tests__/serviceHealthRank.test.ts index a0a2140c54..1486889f59 100644 --- a/packages/api/src/mcp/tools/query/__tests__/serviceHealthRank.test.ts +++ b/packages/api/src/mcp/tools/query/__tests__/serviceHealthRank.test.ts @@ -2,6 +2,7 @@ import { errorGroupKey } from '@/mcp/tools/query/serviceHealth/errorGroups'; import type { NewOperation } from '@/mcp/tools/query/serviceHealth/operations'; import { assessService, + crossedThreshold, HEALTH_THRESHOLDS, type WindowStats, } from '@/mcp/tools/query/serviceHealth/rank'; @@ -28,9 +29,9 @@ const stats = (s: Partial = {}): WindowStats => ({ }); describe('assessService', () => { - it('is healthy when nothing moved', () => { + it('flags nothing when nothing moved', () => { const a = assessService(stats(), stats(), 50); - expect(a.status).toBe('healthy'); + expect(crossedThreshold(a.flags)).toBe(false); expect(a.flags).toEqual([]); }); @@ -38,29 +39,29 @@ describe('assessService', () => { // 0.5% -> 1.0%: 2x, but only +0.5pp const a = assessService(stats({ errors: 10 }), stats({ errors: 5 }), 50); expect(a.flags).not.toContain('error_rate_up'); - expect(a.status).toBe('healthy'); + expect(crossedThreshold(a.flags)).toBe(false); }); it('flags error_rate_up at exactly the ratio and delta thresholds', () => { // 1% -> 2%: exactly 2x and +1pp const a = assessService(stats({ errors: 20 }), stats({ errors: 10 }), 50); expect(a.flags).toContain('error_rate_up'); - expect(a.status).toBe('degraded'); + expect(crossedThreshold(a.flags)).toBe(true); expect(a.deltas.errorRateDeltaPp).toBe(1); }); - it('is critical when errors rose past the high error rate', () => { + it('flags both error rules when errors rose past the high error rate', () => { const a = assessService(stats({ errors: 80 }), stats({ errors: 5 }), 50); expect(a.flags).toEqual( expect.arrayContaining(['error_rate_up', 'high_error_rate']), ); - expect(a.status).toBe('critical'); + expect(crossedThreshold(a.flags)).toBe(true); }); - it('marks a chronically high error rate degraded, not critical', () => { + it('flags a chronically high error rate without error_rate_up', () => { const a = assessService(stats({ errors: 80 }), stats({ errors: 80 }), 50); expect(a.flags).toEqual(['high_error_rate']); - expect(a.status).toBe('degraded'); + expect(crossedThreshold(a.flags)).toBe(true); }); it('needs both the ratio and the ms delta for latency_up', () => { @@ -79,27 +80,27 @@ describe('assessService', () => { it('flags traffic drops and spikes', () => { const drop = assessService(stats({ requests: 500 }), stats(), 50); expect(drop.flags).toContain('traffic_drop'); - expect(drop.status).toBe('degraded'); + expect(crossedThreshold(drop.flags)).toBe(true); const spike = assessService(stats({ requests: 3000 }), stats(), 50); expect(spike.flags).toContain('traffic_spike'); - expect(spike.status).toBe('healthy'); + expect(crossedThreshold(spike.flags)).toBe(false); }); it('flags new and missing services', () => { const fresh = assessService(stats(), null, 50); expect(fresh.flags).toEqual(['new_service']); - expect(fresh.status).toBe('healthy'); + expect(crossedThreshold(fresh.flags)).toBe(false); const gone = assessService(null, stats(), 50); expect(gone.flags).toEqual(['missing_service']); - expect(gone.status).toBe('degraded'); + expect(crossedThreshold(gone.flags)).toBe(true); }); it('treats a handful of prior requests as no baseline', () => { const a = assessService(stats(), stats({ requests: 1, errors: 1 }), 50); expect(a.flags).toEqual(['new_service']); - expect(a.status).toBe('healthy'); + expect(crossedThreshold(a.flags)).toBe(false); }); it('never flags services under minRequests in both windows', () => { @@ -110,7 +111,7 @@ describe('assessService', () => { ); expect(a.flags).toEqual(['low_volume']); expect(a.score).toBe(0); - expect(a.status).toBe('healthy'); + expect(crossedThreshold(a.flags)).toBe(false); }); it('applies absolute rules only when comparisons are off', () => { @@ -126,7 +127,7 @@ describe('assessService', () => { }); describe('rankServices', () => { - it('sorts by status, then by score with volume as a multiplier', () => { + it('sorts flagged services first, then by score with volume as a multiplier', () => { const cur = new Map([ ['steady', stats()], ['small-regression', stats({ requests: 100, errors: 10 })], @@ -280,6 +281,45 @@ describe('buildReport', () => { expect(report.services[0].flags).toContain('new_errors'); }); + it('keeps a flagged service ahead of an unflagged one with new errors', () => { + const report = buildReport({ + ranked: rankServices( + new Map([ + ['slow', stats({ p95Ms: 600 })], + ['quiet', stats()], + ]), + new Map([ + ['slow', stats()], + ['quiet', stats()], + ]), + 50, + ), + current: { start: new Date(0), end: new Date(600_000) }, + comparison: { start: new Date(-600_000), end: new Date(0) }, + comparisonMode: 'previous_period', + spanKind: 'server', + topN: 1, + errorGroupBy: ['SpanName', 'StatusMessage'], + currentErrors: new Map([ + [ + 'quiet', + [ + { + service: 'quiet', + group: { SpanName: 'POST /pay', StatusMessage: 'unavailable' }, + count: 8, + }, + ], + ], + ]), + comparisonErrorCounts: new Map(), + newOperations: new Map(), + spanNameKey: 'SpanName', + }); + expect(report.services.map(s => s.service)).toEqual(['slow']); + expect(report.summary.servicesFlagged).toBe(1); + }); + const reportFor = ( cur: WindowStats, cmp: WindowStats, @@ -326,6 +366,49 @@ describe('buildReport', () => { expect(svc.topErrors[0].status).toBe('new_operation'); }); + it('reports facts, not a health verdict', () => { + const steady = reportFor(stats(), stats()); + expect(steady).not.toHaveProperty('status'); + expect(steady.summary).toMatch( + /^No metric crossed a threshold vs previous_period: error rate 0\.50% vs 0\.50%, p95 200ms vs 200ms, requests 1000 vs 1000\./, + ); + const regressed = reportFor(stats({ errors: 80 }), stats()); + expect(regressed.summary).toMatch( + /^Crossed thresholds: error rate 8\.00% vs 0\.50%\./, + ); + for (const s of [steady.summary, regressed.summary]) { + expect(s).not.toMatch(/healthy|degraded|critical|no action needed/i); + } + }); + + it('counts flagged services instead of statuses', () => { + const report = buildReport({ + ranked: rankServices( + new Map([ + ['a', stats({ errors: 80 })], + ['b', stats()], + ]), + new Map([ + ['a', stats()], + ['b', stats()], + ]), + 50, + ), + current: { start: new Date(0), end: new Date(600_000) }, + comparison: { start: new Date(-600_000), end: new Date(0) }, + comparisonMode: 'previous_period', + spanKind: 'server', + topN: 5, + errorGroupBy: ['SpanName'], + currentErrors: new Map(), + comparisonErrorCounts: new Map(), + newOperations: new Map(), + spanNameKey: 'SpanName', + }); + expect(report.summary.servicesFlagged).toBe(1); + expect(report.summary).not.toHaveProperty('statusCounts'); + }); + it('does not call errors new when the service has no baseline', () => { const svc = reportFor(stats(), stats({ requests: 1, errors: 0 })); expect(svc.flags).toEqual(['new_service']); @@ -363,6 +446,35 @@ describe('errorTiming', () => { expect(errorTiming(group('17:20', '17:21'), window).pattern).toBe('burst'); }); + it('states absolute values when comparisons are off', () => { + expect( + serviceSummary({ + current: stats(), + comparison: undefined, + assessment: assessService(stats(), undefined, 50), + changedErrors: [], + newOperations: [], + window, + comparisonMode: 'none', + }), + ).toBe( + 'No absolute threshold crossed (no comparison window): error rate 0.50%, p95 200ms.', + ); + }); + + it('prints n/a, not "n/ams", for a missing p95', () => { + const summary = serviceSummary({ + current: stats(), + comparison: stats({ p95Ms: null }), + assessment: assessService(stats(), stats({ p95Ms: null }), 50), + changedErrors: [], + newOperations: [], + window, + comparisonMode: 'yesterday', + }); + expect(summary).toMatch(/p95 200ms vs n\/a,/); + }); + it('only calls bursts transient in the summary', () => { const summary = (g: ReturnType) => serviceSummary({ diff --git a/packages/api/src/mcp/tools/query/serviceHealth/index.ts b/packages/api/src/mcp/tools/query/serviceHealth/index.ts index ae68c7c650..d45d08258d 100644 --- a/packages/api/src/mcp/tools/query/serviceHealth/index.ts +++ b/packages/api/src/mcp/tools/query/serviceHealth/index.ts @@ -37,9 +37,9 @@ const TIMEOUT_SUFFIX = const DESCRIPTION = 'One-call health report for every service on a trace source: throughput, ' + 'error rate, p50/p95/p99 latency and top error groups, compared with the ' + - 'same window yesterday and ranked worst first. Each service gets a status ' + - '(critical / degraded / healthy), flags, and a one-line summary of which ' + - 'changes crossed a threshold. New or growing error groups come first, ' + + 'same window yesterday and ranked by how far each moved the wrong way. ' + + 'Each service gets flags for changes that crossed a fixed threshold and ' + + 'a one-line factual summary. New or growing error groups come first, ' + 'with first/last-seen times; operations with no prior traffic are listed ' + 'as likely rollouts.\n\n' + 'USE THIS FIRST for status checks, "is X healthy", post-deploy checks, and ' + @@ -53,8 +53,10 @@ const DESCRIPTION = 'use clickstack_event_deltas and ' + 'clickstack_trace_top_time_consuming_operations.\n\n' + 'CALIBRATION: flags fire only past fixed thresholds (see `usage` in the ' + - 'response). Small swings on a healthy service are normal variance. An ' + - 'all-healthy report is a valid answer.\n\n' + + 'response); smaller swings are usually normal variance, and no flags is ' + + 'a valid result for a routine check. Thresholds apply to service-wide ' + + 'totals, so an unflagged service can still hide a regression in one ' + + 'endpoint, pod or segment. Weigh the numbers against the question.\n\n' + PREFER_BUILDER_OVER_SQL_NUDGE; export function registerServiceHealth({ @@ -172,10 +174,7 @@ export function registerServiceHealth({ 'mcp.service_health.window_ms': current.end.getTime() - current.start.getTime(), 'mcp.service_health.services_assessed': ranked.length, - 'mcp.service_health.critical_count': - report.summary.statusCounts.critical, - 'mcp.service_health.degraded_count': - report.summary.statusCounts.degraded, + 'mcp.service_health.flagged_count': report.summary.servicesFlagged, }); const { data, isTrimmed, notes: trimNotes } = trimToolResponse(report); diff --git a/packages/api/src/mcp/tools/query/serviceHealth/rank.ts b/packages/api/src/mcp/tools/query/serviceHealth/rank.ts index 3c4ebeb1a8..005a357774 100644 --- a/packages/api/src/mcp/tools/query/serviceHealth/rank.ts +++ b/packages/api/src/mcp/tools/query/serviceHealth/rank.ts @@ -8,7 +8,7 @@ export const HEALTH_THRESHOLDS = { errorRateRatio: 2, /** ...and at least this many percentage points higher. */ errorRateMinDeltaPp: 1, - /** high_error_rate, and critical when combined with error_rate_up. */ + /** high_error_rate: current error rate at or above this. */ highErrorRate: 0.05, /** latency_up: p95 at least this multiple of the comparison... */ latencyRatio: 1.5, @@ -34,24 +34,25 @@ export type HealthFlag = | 'latency_up' | 'traffic_drop' | 'missing_service' - // Context for the reader; these never change status. + // Context only; these do not count as a crossed threshold. | 'traffic_spike' | 'new_service' | 'low_volume' // Set by the report: a shown error group is new or growing. | 'new_errors'; -const DEGRADING_FLAGS: ReadonlySet = new Set([ +const THRESHOLD_FLAGS: ReadonlySet = new Set([ 'error_rate_up', 'high_error_rate', 'latency_up', 'traffic_drop', 'missing_service', ]); -export type HealthStatus = 'critical' | 'degraded' | 'healthy'; + +export const crossedThreshold = (flags: readonly HealthFlag[]) => + flags.some(f => THRESHOLD_FLAGS.has(f)); export type ServiceAssessment = { - status: HealthStatus; flags: HealthFlag[]; score: number; deltas: { @@ -62,12 +63,6 @@ export type ServiceAssessment = { }; }; -export const STATUS_ORDER: Record = { - critical: 0, - degraded: 1, - healthy: 2, -}; - const errorRate = (s: WindowStats) => s.requests > 0 ? s.errors / s.requests : 0; @@ -157,16 +152,7 @@ export function assessService( flags.push('traffic_drop'); } - const status: HealthStatus = - flags.includes('error_rate_up') && - curRate >= HEALTH_THRESHOLDS.highErrorRate - ? 'critical' - : flags.some(f => DEGRADING_FLAGS.has(f)) - ? 'degraded' - : 'healthy'; - return { - status, flags, // Too few requests to judge, so it should not outrank real services. score: flags.includes('low_volume') @@ -177,7 +163,7 @@ export function assessService( } /** - * Orders services within a status. Sums how far each metric moved the wrong + * Orders services by magnitude. Sums how far each metric moved the wrong * way, then scales by log volume so a busy service outranks a quiet one with * the same shift. Error points are percentage points; latency and traffic are * log2 ratios, so doubling p95 weighs the same as +2pp errors. @@ -202,7 +188,8 @@ export function compareAssessments( b: { assessment: ServiceAssessment; errors: number; requests: number }, ): number { return ( - STATUS_ORDER[a.assessment.status] - STATUS_ORDER[b.assessment.status] || + Number(crossedThreshold(b.assessment.flags)) - + Number(crossedThreshold(a.assessment.flags)) || b.assessment.score - a.assessment.score || b.errors - a.errors || b.requests - a.requests diff --git a/packages/api/src/mcp/tools/query/serviceHealth/report.ts b/packages/api/src/mcp/tools/query/serviceHealth/report.ts index c5f7fc2b2c..d9a147790f 100644 --- a/packages/api/src/mcp/tools/query/serviceHealth/report.ts +++ b/packages/api/src/mcp/tools/query/serviceHealth/report.ts @@ -3,11 +3,10 @@ import { MAX_NEW_OPERATIONS, type NewOperation } from './operations'; import { assessService, compareAssessments, + crossedThreshold, HEALTH_THRESHOLDS, type HealthFlag, - type HealthStatus, type ServiceAssessment, - STATUS_ORDER, type WindowStats, } from './rank'; import type { Window } from './schema'; @@ -142,21 +141,25 @@ const iso = (w: Window) => ({ }); const USAGE = - 'Services are sorted by status (critical, degraded, healthy), then score. ' + + 'Services with a threshold flag come first, then the rest. Within each ' + + 'group, services with new or growing errors (new_errors) come first, ' + + 'then by score (how far error rate, p95 and traffic moved the wrong way, ' + + 'weighted by volume). Threshold flags: ' + `error_rate_up: error rate >= ${HEALTH_THRESHOLDS.errorRateRatio}x the comparison AND ` + `>= ${HEALTH_THRESHOLDS.errorRateMinDeltaPp} percentage point higher. ` + - `high_error_rate: error rate >= ${HEALTH_THRESHOLDS.highErrorRate * 100}%. ` + - 'critical = error_rate_up together with high_error_rate. ' + + `high_error_rate: error rate >= ${HEALTH_THRESHOLDS.highErrorRate * 100}% (may be chronic; check comparison). ` + `latency_up: p95 >= ${HEALTH_THRESHOLDS.latencyRatio}x AND >= ${HEALTH_THRESHOLDS.latencyMinDeltaMs}ms slower. ` + `traffic_drop: requests <= ${HEALTH_THRESHOLDS.trafficDropRatio * 100}% of the comparison. ` + 'missing_service: served requests in the comparison window but none now. ' + - 'Any of those makes a service degraded. traffic_spike, new_service and ' + - 'low_volume (under minRequests in both windows, never flagged) and ' + - 'new_errors (a listed error group is new or growing; such services sort ' + - 'first within their status) are context only. Healthy services are not ' + - 'regressions: report them as steady, and treat moves below these ' + - "thresholds as normal variance. Each service's " + - '`summary` states which moves crossed one. topErrors carry firstSeen / ' + + 'Context flags: traffic_spike, new_service, low_volume (under ' + + 'minRequests in both windows, never threshold-flagged) and new_errors. ' + + 'Moves below the thresholds are usually normal variance. The tool sees ' + + 'service-wide totals only: a regression confined to one endpoint, pod, ' + + 'version or attribute segment can stay under every threshold, so break ' + + 'down with clickstack_table before ruling a service out of an ' + + "investigation. Each service's `summary` states the facts: which moves " + + 'crossed a threshold, or the current vs comparison values when none did. ' + + 'topErrors carry firstSeen / ' + 'lastSeen and a pattern: ongoing (still firing), spread (most of the ' + 'window, quiet now; not proven resolved) or burst (short, so transient). topErrors lists new and ' + 'growing error groups first (largest gain first), then the largest steady ' + @@ -192,12 +195,9 @@ export function buildReport(args: { ); const windowMinutes = (args.current.end.getTime() - args.current.start.getTime()) / 60_000; - const counts: Record = { - critical: 0, - degraded: 0, - healthy: 0, - }; - for (const r of args.ranked) counts[r.assessment.status]++; + const servicesFlagged = args.ranked.filter(r => + crossedThreshold(r.assessment.flags), + ).length; const prior = (g: ErrorGroup) => args.comparisonErrorCounts?.get(errorGroupKey(g)) ?? 0; @@ -208,14 +208,20 @@ export function buildReport(args: { ) : []; const hasNewErrors = (r: RankedService) => changedErrors(r).length > 0; - // Within a status, a service with a new or growing error group goes first: - // its aggregate rates may be flat, but it has the most novel signal. + // Within the flagged and unflagged groups, a service with a new or growing + // error group goes first: its aggregate rates may be flat, but it has the + // most novel signal. Flagged services stay ahead so topN never drops one + // that servicesFlagged counts. const shown = args.ranked - .map((r, i) => ({ r, i, novel: hasNewErrors(r) })) + .map((r, i) => ({ + r, + i, + novel: hasNewErrors(r), + flagged: crossedThreshold(r.assessment.flags), + })) .sort( (a, b) => - STATUS_ORDER[a.r.assessment.status] - - STATUS_ORDER[b.r.assessment.status] || + Number(b.flagged) - Number(a.flagged) || Number(b.novel) - Number(a.novel) || a.i - b.i, ) @@ -224,7 +230,6 @@ export function buildReport(args: { const services = shown.map(({ r, novel }, i) => ({ rank: i + 1, service: r.service, - status: r.assessment.status, flags: novel ? [...r.assessment.flags, 'new_errors' satisfies HealthFlag] : r.assessment.flags, @@ -281,7 +286,7 @@ export function buildReport(args: { errorGroupBy: args.errorGroupBy, servicesAssessed: args.ranked.length, servicesReturned: services.length, - statusCounts: counts, + servicesFlagged, ...(args.ranked.length === 0 && { warning: 'No spans matched in either window. Check the time window, the ' + diff --git a/packages/api/src/mcp/tools/query/serviceHealth/summary.ts b/packages/api/src/mcp/tools/query/serviceHealth/summary.ts index a7737af20a..dc826f320f 100644 --- a/packages/api/src/mcp/tools/query/serviceHealth/summary.ts +++ b/packages/api/src/mcp/tools/query/serviceHealth/summary.ts @@ -1,6 +1,7 @@ import type { ErrorGroup } from './errorGroups'; import type { NewOperation } from './operations'; import { + crossedThreshold, HEALTH_THRESHOLDS, type ServiceAssessment, type WindowStats, @@ -20,6 +21,7 @@ type ErrorPattern = 'ongoing' | 'spread' | 'burst'; const pct = (s: WindowStats | null) => s && s.requests > 0 ? `${((s.errors / s.requests) * 100).toFixed(2)}%` : '0%'; +const fmtMs = (v: number | null | undefined) => (v == null ? 'n/a' : `${v}ms`); const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); export function errorTiming(g: ErrorGroup, window: Window) { @@ -59,9 +61,10 @@ function describeError(g: ErrorGroup, window: Window): string { } /** - * A plain verdict per service. Agents otherwise read every nonzero delta as a - * trend ("error rate up 0.08pp"), so this states which moves crossed a - * threshold and which are ordinary variance. + * States which moves crossed a threshold, or the raw values when none did. + * Agents read every nonzero delta as a trend ("error rate up 0.08pp"), but a + * verdict like "healthy, no action needed" stops them investigating a + * regression the service-wide totals hide, so this reports facts only. */ export function serviceSummary(args: { current: WindowStats | null; @@ -92,14 +95,13 @@ export function serviceSummary(args: { const head = parts.length > 0 - ? `${assessment.status.toUpperCase()}: ${parts.join('; ')}.` + ? `Crossed thresholds: ${parts.join('; ')}.` : comparison === undefined - ? 'Healthy: no absolute threshold crossed (no comparison window).' - : `Healthy: no metric crossed a threshold vs ${args.comparisonMode}; ` + - 'the deltas are normal variance' + - (changedErrors.length > 0 - ? ', but see the new errors below.' - : '; report this service as steady, no action needed.'); + ? `No absolute threshold crossed (no comparison window): error rate ${pct(current)}, p95 ${fmtMs(current?.p95Ms)}.` + : `No metric crossed a threshold vs ${args.comparisonMode}: ` + + `error rate ${pct(current)} vs ${pct(comparison)}, ` + + `p95 ${fmtMs(current?.p95Ms)} vs ${fmtMs(comparison?.p95Ms)}, ` + + `requests ${current?.requests ?? 0} vs ${comparison?.requests ?? 0}.`; const context: string[] = []; if (f.has('new_service')) @@ -139,7 +141,7 @@ export function serviceSummary(args: { : ''), ); } - if (args.spanKind === 'all' && assessment.status === 'healthy') + if (args.spanKind === 'all' && !crossedThreshold(assessment.flags)) context.push( 'Internal and client spans are included, which dilutes server-side ' + 'changes; check spanKind:"server" before concluding nothing changed.', From 1fba1c381a27dacb2aa069890271c6d48e2cdc58 Mon Sep 17 00:00:00 2001 From: Brandon Pereira Date: Thu, 12 Nov 2026 14:47:46 -0600 Subject: [PATCH 06/55] fix(mcp): mark save_webhook and save_alert as open-world (#3639) ## Summary `clickstack_save_webhook` and `clickstack_save_alert` now declare `openWorldHint: true`. Neither makes a network call during the tool call, but a saved webhook points at a third-party endpoint (Slack, incident.io, or any public URL with a templated body), and a saved alert sends requests to it on a schedule. Declaring them closed-world told MCP clients they could skip the extra review they give tools that reach outside the system. That review matters here: a prompt-injected agent could create a generic webhook to an attacker URL plus a frequently firing alert, and use them to exfiltrate telemetry. Every other tool stays closed-world. `clickstack_delete_webhook` stays closed-world too, since deleting only stops deliveries. A new test pins the open-world set to exactly these two tools. Flagged by an MCP tool-annotation compatibility check. ### How to reproduce **Starting point:** local `yarn dev` (needs the API). **On `main`:** 1. Call `tools/list` on the MCP server (`/api/mcp`). 2. `clickstack_save_webhook` and `clickstack_save_alert` report `annotations.openWorldHint: false`. **On this branch:** 1. Same call: both report `openWorldHint: true`, and all other tools still report `false`. 2. `cd packages/api && yarn ci:unit src/mcp/__tests__/toolAnnotations.test.ts` passes. ### Notes Committed with `--no-verify`. lint-staged passed. The hook's knip step fails on an issue already on `main`: `@opentelemetry/browser-sdk` is declared in `packages/app/package.json` (added in #3575) but never imported. --- .changeset/mcp-open-world-alert-webhook.md | 7 +++++++ .../api/src/mcp/__tests__/toolAnnotations.test.ts | 15 +++++++++++++++ packages/api/src/mcp/tools/alerts/saveAlert.ts | 4 ++-- packages/api/src/mcp/tools/alerts/saveWebhook.ts | 4 ++-- packages/api/src/mcp/tools/annotations.ts | 14 ++++++++++++-- 5 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 .changeset/mcp-open-world-alert-webhook.md diff --git a/.changeset/mcp-open-world-alert-webhook.md b/.changeset/mcp-open-world-alert-webhook.md new file mode 100644 index 0000000000..7d7092bd77 --- /dev/null +++ b/.changeset/mcp-open-world-alert-webhook.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': patch +--- + +fix: mark the MCP `clickstack_save_webhook` and `clickstack_save_alert` tools as open-world + +Saved webhooks and alerts send HTTP requests to third-party endpoints, so both tools now declare `openWorldHint: true`. diff --git a/packages/api/src/mcp/__tests__/toolAnnotations.test.ts b/packages/api/src/mcp/__tests__/toolAnnotations.test.ts index 4fddeae092..43c5448a48 100644 --- a/packages/api/src/mcp/__tests__/toolAnnotations.test.ts +++ b/packages/api/src/mcp/__tests__/toolAnnotations.test.ts @@ -24,6 +24,21 @@ describe('MCP tool annotations', () => { expect(missing).toEqual([]); }); + it('marks only tools that configure outbound notifications as open-world', async () => { + const client = await createTestClient(context); + const { tools } = await client.listTools(); + + const openWorld = tools + .filter(tool => tool.annotations?.openWorldHint) + .map(tool => tool.name) + .sort(); + + expect(openWorld).toEqual([ + 'clickstack_save_alert', + 'clickstack_save_webhook', + ]); + }); + it('mirrors the tool title into annotations.title', async () => { const client = await createTestClient(context); const { tools } = await client.listTools(); diff --git a/packages/api/src/mcp/tools/alerts/saveAlert.ts b/packages/api/src/mcp/tools/alerts/saveAlert.ts index 9c5962026d..b1149d1e69 100644 --- a/packages/api/src/mcp/tools/alerts/saveAlert.ts +++ b/packages/api/src/mcp/tools/alerts/saveAlert.ts @@ -8,7 +8,7 @@ import { updateAlert, validateAlertInput, } from '@/controllers/alerts'; -import { UPSERT_TOOL } from '@/mcp/tools/annotations'; +import { OPEN_WORLD_UPSERT_TOOL } from '@/mcp/tools/annotations'; import type { ToolRegistrar } from '@/mcp/tools/types'; import { formatZodIssues, @@ -43,7 +43,7 @@ export function registerSaveAlert({ 'clickstack_save_alert', { title: 'Create or Update Alert', - annotations: UPSERT_TOOL, + annotations: OPEN_WORLD_UPSERT_TOOL, description: 'Create a new alert (omit id) or update an existing one (provide id). ' + 'Alerts monitor a saved search, a dashboard tile, or an inline chart ' + diff --git a/packages/api/src/mcp/tools/alerts/saveWebhook.ts b/packages/api/src/mcp/tools/alerts/saveWebhook.ts index 5542f47f60..46c082a960 100644 --- a/packages/api/src/mcp/tools/alerts/saveWebhook.ts +++ b/packages/api/src/mcp/tools/alerts/saveWebhook.ts @@ -3,7 +3,7 @@ import mongoose from 'mongoose'; import { z } from 'zod'; import { createWebhook, updateWebhook } from '@/controllers/webhook'; -import { UPSERT_TOOL } from '@/mcp/tools/annotations'; +import { OPEN_WORLD_UPSERT_TOOL } from '@/mcp/tools/annotations'; import type { ToolRegistrar } from '@/mcp/tools/types'; import { mcpServerError, @@ -106,7 +106,7 @@ export function registerSaveWebhook({ 'clickstack_save_webhook', { title: 'Create or Update Webhook', - annotations: UPSERT_TOOL, + annotations: OPEN_WORLD_UPSERT_TOOL, description: 'Create a new webhook (omit id) or update an existing one (provide ' + 'id). Use the returned id as the webhookId when creating alerts with ' + diff --git a/packages/api/src/mcp/tools/annotations.ts b/packages/api/src/mcp/tools/annotations.ts index ed8b31b8d7..ba2821c5e7 100644 --- a/packages/api/src/mcp/tools/annotations.ts +++ b/packages/api/src/mcp/tools/annotations.ts @@ -11,8 +11,9 @@ export type ToolBehaviorAnnotations = Required< > >; -// Every tool reads or writes only the calling team's own ClickStack metadata -// (MongoDB) and telemetry (ClickHouse), so none of them is open-world. +// Tools read or write only the calling team's own ClickStack metadata +// (MongoDB) and telemetry (ClickHouse), so they are closed-world. The +// exception is OPEN_WORLD_UPSERT_TOOL. export const READ_ONLY_TOOL: ToolBehaviorAnnotations = { readOnlyHint: true, @@ -32,6 +33,15 @@ export const UPSERT_TOOL: ToolBehaviorAnnotations = { openWorldHint: false, }; +/** + * Upserts whose saved object makes ClickStack send HTTP requests to + * third-party endpoints (webhooks, and the alerts that notify them). + */ +export const OPEN_WORLD_UPSERT_TOOL: ToolBehaviorAnnotations = { + ...UPSERT_TOOL, + openWorldHint: true, +}; + /** * Updates or deletes an existing object by ID. Repeating the call with the * same arguments leaves the same end state. From b3cbd02606716fee8103e6501e8819991216d713 Mon Sep 17 00:00:00 2001 From: "Javier O." Date: Thu, 12 Nov 2026 22:53:44 +0100 Subject: [PATCH 07/55] feat(app): split the service map by extra group-by expressions (#3632) --- .changeset/service-map-group-by.md | 7 + packages/app/src/DBServiceMapPage.tsx | 51 +++- .../src/components/ServiceMap/ServiceMap.tsx | 67 ++++- .../components/ServiceMap/ServiceMapEdge.tsx | 7 + .../ServiceMap/ServiceMapGroupByInput.tsx | 72 +++++ .../components/ServiceMap/ServiceMapNode.tsx | 17 ++ .../ServiceMap/ServiceMapTooltip.tsx | 53 +++- .../ServiceMap/__tests__/dimensions.test.ts | 64 +++++ .../__tests__/useServiceMapSizeGate.test.ts | 57 ++++ .../ServiceMap/__tests__/utils.test.ts | 15 ++ .../src/components/ServiceMap/dimensions.ts | 52 ++++ .../ServiceMap/useServiceMapSizeGate.ts | 22 ++ .../app/src/components/ServiceMap/utils.ts | 15 ++ .../src/hooks/__tests__/useServiceMap.test.ts | 248 ++++++++++++++++++ packages/app/src/hooks/useServiceMap.tsx | 140 ++++++++-- .../e2e/features/service-map-group-by.spec.ts | 76 ++++++ packages/app/tests/e2e/seed-clickhouse.ts | 5 +- 17 files changed, 910 insertions(+), 58 deletions(-) create mode 100644 .changeset/service-map-group-by.md create mode 100644 packages/app/src/components/ServiceMap/ServiceMapGroupByInput.tsx create mode 100644 packages/app/src/components/ServiceMap/__tests__/dimensions.test.ts create mode 100644 packages/app/src/components/ServiceMap/__tests__/useServiceMapSizeGate.test.ts create mode 100644 packages/app/src/components/ServiceMap/dimensions.ts create mode 100644 packages/app/src/components/ServiceMap/useServiceMapSizeGate.ts create mode 100644 packages/app/tests/e2e/features/service-map-group-by.spec.ts diff --git a/.changeset/service-map-group-by.md b/.changeset/service-map-group-by.md new file mode 100644 index 0000000000..31b522011e --- /dev/null +++ b/.changeset/service-map-group-by.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/app': minor +--- + +feat: split the service map by up to 3 extra group-by SQL expressions (for +example `ResourceAttributes['k8s.pod.name']`), so a node is a service plus +those values and a slow or failing pod is no longer averaged into its service. diff --git a/packages/app/src/DBServiceMapPage.tsx b/packages/app/src/DBServiceMapPage.tsx index 56d954d62a..8945769d16 100644 --- a/packages/app/src/DBServiceMapPage.tsx +++ b/packages/app/src/DBServiceMapPage.tsx @@ -34,6 +34,10 @@ import { PageLayout } from '@/components/PageLayout'; import SearchWhereInput, { getStoredLanguage, } from '@/components/SearchInput/SearchWhereInput'; +import { parseServiceMapGroupBy } from '@/components/ServiceMap/dimensions'; +import ServiceMapGroupByInput, { + ServiceMapSearchFormValues, +} from '@/components/ServiceMap/ServiceMapGroupByInput'; import { IS_LOCAL_MODE } from '@/config'; import { useGetKeyValues } from '@/hooks/useMetadata'; import { useResolvedSourceParam } from '@/hooks/useResolvedSourceParam'; @@ -86,6 +90,8 @@ const searchQueryStateMap = { where: parseAsStringEncoded, whereLanguage: parseAsStringEnum<'sql' | 'lucene'>(['sql', 'lucene']), services: parseAsArrayOf(parseAsString), + // Comma-separated SQL expressions the nodes are split by, after ServiceName. + groupBy: parseAsStringEncoded, }; function DBServiceMapPage() { @@ -121,14 +127,22 @@ function DBServiceMapPage() { // useResolvedSourceParam will show a notification to the user. const source = paramSource ?? defaultSource; - const { control, handleSubmit, setValue } = useForm({ - values: { - source: source?.id, - where: searchedConfig.where ?? '', - whereLanguage: - searchedConfig.whereLanguage ?? getStoredLanguage() ?? 'lucene', - }, - }); + const groupBy = useMemo( + () => parseServiceMapGroupBy(searchedConfig.groupBy), + [searchedConfig.groupBy], + ); + const { control, handleSubmit, setValue } = + useForm({ + values: { + source: source?.id, + where: searchedConfig.where ?? '', + whereLanguage: + searchedConfig.whereLanguage ?? getStoredLanguage() ?? 'lucene', + // Seeded from the parsed list so the editor shows exactly what the map + // is grouped by, even for a hand-edited URL with too many expressions. + groupBy: groupBy.join(', '), + }, + }); const watchedSource = useWatch({ control, name: 'source' }); const [isSourceSchemaPreviewOpen, setIsSourceSchemaPreviewOpen] = @@ -207,10 +221,17 @@ function DBServiceMapPage() { [setSearchedConfig], ); + // The time range is applied together with the form values, so an invalid + // group-by leaves the URL untouched instead of moving the time window. const onSubmit = useCallback(() => { - onSearch(displayedTimeInputValue); - handleSubmit(({ where, whereLanguage }) => { - setSearchedConfig(prev => ({ ...prev, where, whereLanguage })); + handleSubmit(({ where, whereLanguage, groupBy }) => { + onSearch(displayedTimeInputValue); + setSearchedConfig(prev => ({ + ...prev, + where, + whereLanguage, + groupBy: groupBy || null, + })); })(); }, [handleSubmit, setSearchedConfig, displayedTimeInputValue, onSearch]); @@ -410,6 +431,13 @@ function DBServiceMapPage() { sqlPlaceholder="SQL WHERE to filter spans (ex. Duration > 1000000)" minWidth="min(500px, 100%)" /> + 0 ? selectedServices : undefined } + groupBy={groupBy} onFocusService={onFocusService} /> diff --git a/packages/app/src/components/ServiceMap/ServiceMap.tsx b/packages/app/src/components/ServiceMap/ServiceMap.tsx index e8a5f3a6ce..c00ba1c416 100644 --- a/packages/app/src/components/ServiceMap/ServiceMap.tsx +++ b/packages/app/src/components/ServiceMap/ServiceMap.tsx @@ -4,6 +4,7 @@ import { ClickHouseQueryError } from '@hyperdx/common-utils/dist/clickhouse'; import { TTraceSource } from '@hyperdx/common-utils/dist/types'; import { Box, + Button, Center, Code, Loader, @@ -28,6 +29,7 @@ import { } from '@xyflow/react'; import { SQLPreview } from '@/components/ChartSQLPreview'; +import EmptyState from '@/components/EmptyState'; import useServiceMap, { ServiceAggregation } from '@/hooks/useServiceMap'; import { useResolvedColorScheme } from '@/useUserPreferences'; @@ -38,8 +40,10 @@ import { ServiceMapMetricMax, } from './ServiceMapMetricContext'; import ServiceMapNode, { ServiceMapNodeData } from './ServiceMapNode'; +import { useServiceMapSizeGate } from './useServiceMapSizeGate'; import { getServiceMetricValue, + MAX_SERVICE_MAP_NODES, SERVICE_MAP_METRIC_LABEL, SERVICE_MAP_METRICS, ServiceMapMetric, @@ -96,6 +100,8 @@ interface ServiceMapPresentationProps { dateRange: [Date, Date]; source: TTraceSource; isSingleTrace?: boolean; + // Extra group-by SQL expressions the nodes are split by (beyond ServiceName). + groupBy: string[]; // The single service the map is currently scoped to (via a node's focus // action), or undefined when showing all/multiple services. focusedService?: string; @@ -109,6 +115,7 @@ function ServiceMapPresentation({ dateRange, source, isSingleTrace, + groupBy, focusedService, onFocusService, }: ServiceMapPresentationProps) { @@ -117,6 +124,7 @@ function ServiceMapPresentation({ const { fitView } = useReactFlow(); const colorScheme = useResolvedColorScheme(); const [metric, setMetric] = useState('errorRate'); + const { tooLarge, showAnyway } = useServiceMapSizeGate(services); // Fit the data to the viewport whenever input service information changes useEffect(() => { @@ -166,15 +174,24 @@ function ServiceMapPresentation({ }, [metric, hasLatencyData]); useEffect(() => { + // Skip the layout entirely for an oversized map; dagre on thousands of + // nodes is what locks the tab, not the query. + if (tooLarge) { + setNodes([]); + setEdges([]); + return; + } + const nodes: Node[] = Array.from(services?.values() ?? []).map((service, index) => ({ - id: service.serviceName, + id: service.key, data: { ...service, dateRange, source, maxThroughput: metricMax.throughput, isSingleTrace, + groupBy, focusedService, onFocusService, }, @@ -186,16 +203,16 @@ function ServiceMapPresentation({ services?.values() ?? [], ) .filter(service => service.incomingRequestsByClient.size > 0) - .flatMap(({ serviceName, incomingRequestsByClient: requestsByClient }) => - Array.from(requestsByClient.entries()).map( + .flatMap(({ key, serviceName, dimensions, incomingRequestsByClient }) => + Array.from(incomingRequestsByClient.entries()).map( ([ - clientServiceName, + clientKey, { totalRequests, errorPercentage, p50, p95, p99, hasLatency }, ]) => { return { - id: `${serviceName}-${clientServiceName}`, - source: clientServiceName, - target: serviceName, + id: `${clientKey}->${key}`, + source: clientKey, + target: key, animated: true, type: 'request', data: { @@ -208,6 +225,8 @@ function ServiceMapPresentation({ source, dateRange, serviceName, + dimensions, + groupBy, isSingleTrace, }, }; @@ -221,10 +240,12 @@ function ServiceMapPresentation({ setEdges(edges); }, [ services, + tooLarge, dateRange, source, metricMax.throughput, isSingleTrace, + groupBy, focusedService, onFocusService, ]); @@ -248,6 +269,29 @@ function ServiceMapPresentation({ ); } + if (services && tooLarge) { + return ( +
+ + + +
+ ); + } + if (error) { return ( @@ -336,11 +380,17 @@ interface ServiceMapProps { where?: string; whereLanguage?: 'sql' | 'lucene'; serviceNames?: string[]; + // Extra group-by SQL expressions; ServiceName is always the first key. + groupBy?: string[]; // Called when a node is clicked, e.g. to drive the service filter to focus // on that service and its immediate dependencies. onFocusService?: (serviceName: string) => void; } +// A stable default so the layout effect does not re-run on every render when +// the caller passes no group-by. +const NO_GROUP_BY: string[] = []; + export default function ServiceMap({ traceId, traceTableSource, @@ -350,6 +400,7 @@ export default function ServiceMap({ where, whereLanguage, serviceNames, + groupBy = NO_GROUP_BY, onFocusService, }: ServiceMapProps) { const { @@ -364,6 +415,7 @@ export default function ServiceMap({ where, whereLanguage, serviceNames, + groupBy, }); useEffect(() => { @@ -390,6 +442,7 @@ export default function ServiceMap({ dateRange={dateRange} source={traceTableSource} isSingleTrace={isSingleTrace} + groupBy={groupBy} focusedService={focusedService} onFocusService={onFocusService} /> diff --git a/packages/app/src/components/ServiceMap/ServiceMapEdge.tsx b/packages/app/src/components/ServiceMap/ServiceMapEdge.tsx index 9e08473531..b55e34b7a5 100644 --- a/packages/app/src/components/ServiceMap/ServiceMapEdge.tsx +++ b/packages/app/src/components/ServiceMap/ServiceMapEdge.tsx @@ -20,7 +20,10 @@ export type ServiceMapEdgeData = { hasLatency: boolean; dateRange: [Date, Date]; source: TTraceSource; + // The server (target) node's label parts. serviceName: string; + dimensions: string[]; + groupBy: string[]; isSingleTrace?: boolean; }; @@ -42,6 +45,8 @@ export default function ServiceMapEdge( hasLatency, dateRange, serviceName, + dimensions, + groupBy, source, isSingleTrace, } = props.data; @@ -70,6 +75,8 @@ export default function ServiceMapEdge( source={source} dateRange={dateRange} serviceName={serviceName} + dimensions={dimensions} + groupBy={groupBy} isSingleTrace={isSingleTrace} /> diff --git a/packages/app/src/components/ServiceMap/ServiceMapGroupByInput.tsx b/packages/app/src/components/ServiceMap/ServiceMapGroupByInput.tsx new file mode 100644 index 0000000000..368027c200 --- /dev/null +++ b/packages/app/src/components/ServiceMap/ServiceMapGroupByInput.tsx @@ -0,0 +1,72 @@ +import { Control, useFormState } from 'react-hook-form'; +import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; +import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; +import { Box, Text } from '@mantine/core'; + +import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor'; +import { MAX_SERVICE_MAP_GROUP_BY } from '@/hooks/useServiceMap'; + +export type ServiceMapSearchFormValues = { + source?: string; + where: string; + whereLanguage: 'sql' | 'lucene'; + // Comma-separated extra group-by SQL expressions. + groupBy: string; +}; + +function validateGroupBy(value: string): true | string { + return ( + splitAndTrimWithBracket(value).length <= MAX_SERVICE_MAP_GROUP_BY || + `Up to ${MAX_SERVICE_MAP_GROUP_BY} group by expressions` + ); +} + +/** The "Group by" SQL editor, with the expression-count validation inline. */ +export default function ServiceMapGroupByInput({ + control, + tableConnection, + sourceId, + dateRange, + onSubmit, +}: { + control: Control; + tableConnection: TableConnection; + sourceId: string; + dateRange: [Date, Date]; + onSubmit: () => void; +}) { + const { errors } = useFormState({ control, name: 'groupBy' }); + + return ( + + + {errors.groupBy?.message ? ( + + {errors.groupBy.message} + + ) : null} + + ); +} diff --git a/packages/app/src/components/ServiceMap/ServiceMapNode.tsx b/packages/app/src/components/ServiceMap/ServiceMapNode.tsx index c0a2219340..7936959756 100644 --- a/packages/app/src/components/ServiceMap/ServiceMapNode.tsx +++ b/packages/app/src/components/ServiceMap/ServiceMapNode.tsx @@ -5,6 +5,7 @@ import { Handle, Node, NodeProps, NodeToolbar, Position } from '@xyflow/react'; import { ServiceAggregation } from '@/hooks/useServiceMap'; +import { formatServiceMapDimensions } from './dimensions'; import { ServiceMapMetricContext } from './ServiceMapMetricContext'; import ServiceMapTooltip from './ServiceMapTooltip'; import { @@ -23,6 +24,8 @@ export type ServiceMapNodeData = ServiceAggregation & { // scale node size. maxThroughput: number; isSingleTrace?: boolean; + // The extra group-by SQL expressions behind `dimensions`. + groupBy: string[]; // Name of the service the map is currently focused on (if any), so a node can // tell whether it is the focused one and show the matching CTA. focusedService?: string; @@ -36,6 +39,8 @@ export default function ServiceMapNode( const { data } = props; const { serviceName, + dimensions, + groupBy, incomingRequests: { totalRequests: totalIncomingRequestCount, errorPercentage, @@ -83,6 +88,7 @@ export default function ServiceMapNode( totalIncomingRequestCount + outgoingRequests, maxThroughput, ); + const dimensionsLabel = formatServiceMapDimensions(dimensions); return ( <> @@ -95,6 +101,8 @@ export default function ServiceMapNode( source={source} dateRange={dateRange} serviceName={serviceName} + dimensions={dimensions} + groupBy={groupBy} isSingleTrace={isSingleTrace} isFocused={focusedService === serviceName} onFocus={ @@ -133,6 +141,15 @@ export default function ServiceMapNode( {serviceName} + {dimensionsLabel ? ( + + {dimensionsLabel} + + ) : null} ); diff --git a/packages/app/src/components/ServiceMap/ServiceMapTooltip.tsx b/packages/app/src/components/ServiceMap/ServiceMapTooltip.tsx index 9996df3d71..f2bc0fa039 100644 --- a/packages/app/src/components/ServiceMap/ServiceMapTooltip.tsx +++ b/packages/app/src/components/ServiceMap/ServiceMapTooltip.tsx @@ -13,6 +13,10 @@ import { import { formatDurationMs } from '@/utils'; +import { + buildServiceMapDimensionsWhere, + formatServiceMapDimensions, +} from './dimensions'; import { buildServiceMapErrorWhere, ERROR_RATE_HIGH, @@ -31,6 +35,8 @@ export default function ServiceMapTooltip({ source, dateRange, serviceName, + dimensions, + groupBy, isSingleTrace, isFocused, onFocus, @@ -44,6 +50,10 @@ export default function ServiceMapTooltip({ source: TTraceSource; dateRange: [Date, Date]; serviceName: string; + // Values of the extra group-by expressions for this node, in groupBy order. + dimensions: string[]; + // The extra group-by SQL expressions, so search links can pin each value. + groupBy: string[]; isSingleTrace?: boolean; // Whether the map is currently scoped to this service (the focus toggle is on) // — flips the focus CTA to a "clear" action. @@ -63,30 +73,35 @@ export default function ServiceMapTooltip({ ? 'var(--color-text-danger)' : 'var(--color-chart-warning)'; + const dimensionsLabel = formatServiceMapDimensions(dimensions); + const dimensionsWhere = buildServiceMapDimensionsWhere(groupBy, dimensions); + const handleRequestsClick = useCallback(() => { navigateToTraceSearch({ dateRange, source, - where: SqlString.format("? = ? AND ? IN ('Server', 'Consumer')", [ - SqlString.raw(source.serviceNameExpression ?? 'ServiceName'), - serviceName, - SqlString.raw(source.spanKindExpression ?? 'SpanKind'), - ]), + where: + SqlString.format("? = ? AND ? IN ('Server', 'Consumer')", [ + SqlString.raw(source.serviceNameExpression ?? 'ServiceName'), + serviceName, + SqlString.raw(source.spanKindExpression ?? 'SpanKind'), + ]) + dimensionsWhere, }); - }, [dateRange, source, serviceName]); + }, [dateRange, source, serviceName, dimensionsWhere]); const handleErrorsClick = useCallback(() => { navigateToTraceSearch({ dateRange, source, - where: buildServiceMapErrorWhere({ - serviceNameExpression: source.serviceNameExpression ?? 'ServiceName', - serviceName, - spanKindExpression: source.spanKindExpression ?? 'SpanKind', - statusCodeExpression: source.statusCodeExpression ?? 'StatusCode', - }), + where: + buildServiceMapErrorWhere({ + serviceNameExpression: source.serviceNameExpression ?? 'ServiceName', + serviceName, + spanKindExpression: source.spanKindExpression ?? 'SpanKind', + statusCodeExpression: source.statusCodeExpression ?? 'StatusCode', + }) + dimensionsWhere, }); - }, [dateRange, source, serviceName]); + }, [dateRange, source, serviceName, dimensionsWhere]); const showMetrics = totalRequests > 0 && (requestsPerSecond != null || latencyMs != null); @@ -104,6 +119,18 @@ export default function ServiceMapTooltip({ > {serviceName} + {dimensionsLabel ? ( + + {dimensionsLabel} + + ) : null} + )} {conditions.length === 0 && ( ({ const filter: AdhocDashboardFilterType = { id: 'adhoc1', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Conditions', sourceType: 'sql', sources: ['logs'], @@ -81,6 +82,30 @@ describe('AdhocDashboardFilter', () => { expect(pills[1]).toHaveTextContent('Level regex ^err'); }); + it('collapses conditions past the first three until expanded', async () => { + renderFilter( + Array.from({ length: 5 }, (_, i) => ({ ...existing, value: `${i}` })), + ); + const toggle = screen.getByTestId('adhoc-filter-toggle-more-Conditions'); + + expect(screen.getAllByTestId('adhoc-condition-pill')).toHaveLength(3); + expect(toggle).toHaveTextContent('+2 more'); + + await userEvent.click(toggle); + expect(screen.getAllByTestId('adhoc-condition-pill')).toHaveLength(5); + expect(toggle).toHaveTextContent('Show less'); + + await userEvent.click(toggle); + expect(screen.getAllByTestId('adhoc-condition-pill')).toHaveLength(3); + }); + + it('shows no toggle for three conditions or fewer', () => { + renderFilter([existing, existing, existing]); + expect( + screen.queryByTestId('adhoc-filter-toggle-more-Conditions'), + ).not.toBeInTheDocument(); + }); + it('marks conditions a PromQL filter cannot apply as invalid', () => { renderFilter( [ diff --git a/packages/app/src/components/AdhocDashboardFilter/__tests__/useAdhocFilterOptions.test.tsx b/packages/app/src/components/AdhocDashboardFilter/__tests__/useAdhocFilterOptions.test.tsx index e0880af24f..755d36e428 100644 --- a/packages/app/src/components/AdhocDashboardFilter/__tests__/useAdhocFilterOptions.test.tsx +++ b/packages/app/src/components/AdhocDashboardFilter/__tests__/useAdhocFilterOptions.test.tsx @@ -181,6 +181,7 @@ describe('useAdhocFilterOptions', () => { ): AdhocDashboardFilter => ({ id: 'f', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Conditions', sourceType, sources, diff --git a/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx index aa54074502..6cf870d086 100644 --- a/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx @@ -2,15 +2,19 @@ import { useMemo } from 'react'; import { Controller, UseFormSetValue, useWatch } from 'react-hook-form'; import { Separator } from '@clickhouse/click-ui'; import { tcFromSource } from '@hyperdx/common-utils/dist/core/metadata'; -import { getAdhocFilterSourceKinds } from '@hyperdx/common-utils/dist/filters'; +import { + getAdhocFilterAppliesToSourceIds, + getAdhocFilterSourceKinds, + isAdhocFilter, +} from '@hyperdx/common-utils/dist/filters'; import { AdhocFilterSourceType, DashboardFilter, SourceKind, } from '@hyperdx/common-utils/dist/types'; -import { Box, SegmentedControl } from '@mantine/core'; +import { Alert, SegmentedControl } from '@mantine/core'; +import { IconAlertTriangle } from '@tabler/icons-react'; -import { CheckBoxControlled } from '@/components/InputControlled'; import SearchWhereInput from '@/components/SearchInput/SearchWhereInput'; import { SourceMultiSelectControlled } from '@/components/SourceMultiSelect'; import { IS_PROMQL_ENABLED } from '@/config'; @@ -40,10 +44,26 @@ export const AdhocFilterEditForm = ({ otherFilters, }: AdhocFilterEditFormProps) => { const { data: allSources } = useSources(); - const [sourceType, isBroadcastEnabled, sourceIds] = useWatch({ + const [sourceType, sourceIds, appliesToSourceIds] = useWatch({ control, - name: ['sourceType', 'isBroadcastEnabled', 'sources'], + name: ['sourceType', 'sources', 'appliesToSourceIds'], }); + // Click-to-filter updates every ad hoc filter reaching the clicked tile. + const overlappingFilters = useMemo(() => { + const targets = getAdhocFilterAppliesToSourceIds({ + sources: sourceIds ?? [], + appliesToSourceIds: appliesToSourceIds?.filter(id => !!id), + }); + return otherFilters + .filter(isAdhocFilter) + .filter( + other => + other.sourceType === sourceType && + getAdhocFilterAppliesToSourceIds(other).some(id => + targets.includes(id), + ), + ); + }, [otherFilters, sourceType, sourceIds, appliesToSourceIds]); const allowedSourceKinds = getAdhocFilterSourceKinds(sourceType); const tableConnections = useMemo( () => @@ -138,39 +158,43 @@ export const AdhocFilterEditForm = ({ )} - - - {isBroadcastEnabled && ( - - - - - + > + + + {overlappingFilters.length > 0 && ( + } + data-testid="adhoc-filter-overlap-warning" + > + Another ad hoc filter ( + {overlappingFilters.map(f => f.name).join(', ')}) already applies to + these sources. Clicking a value in a tile will update all of them. + )} - + ); }; diff --git a/packages/app/src/components/DashboardFiltersModal/DashboardFiltersList.tsx b/packages/app/src/components/DashboardFiltersModal/DashboardFiltersList.tsx index e2d1a64a11..2f7cd9ece6 100644 --- a/packages/app/src/components/DashboardFiltersModal/DashboardFiltersList.tsx +++ b/packages/app/src/components/DashboardFiltersModal/DashboardFiltersList.tsx @@ -2,8 +2,8 @@ import { getFilterBroadcastTarget, getFilterVariableName, isFilterGlobalRequirement, + isFilterReferenceableVariable, isFilterRequired, - isFilterVariableEnabled, } from '@hyperdx/common-utils/dist/filters'; import { DashboardFilter } from '@hyperdx/common-utils/dist/types'; import { @@ -169,7 +169,7 @@ export const DashboardFiltersList = ({ } const variableName = - showVariableOptions && isFilterVariableEnabled(filter) + showVariableOptions && isFilterReferenceableVariable(filter) ? getFilterVariableName(filter) : undefined; return ( diff --git a/packages/app/src/components/DashboardFiltersModal/VariableNameInput.tsx b/packages/app/src/components/DashboardFiltersModal/VariableNameInput.tsx index 72f8dbdf93..7b9623c10e 100644 --- a/packages/app/src/components/DashboardFiltersModal/VariableNameInput.tsx +++ b/packages/app/src/components/DashboardFiltersModal/VariableNameInput.tsx @@ -12,11 +12,20 @@ import { FilterFormControl } from './filterFormState'; interface VariableNameInputProps { control: FilterFormControl; otherFilters: DashboardFilter[]; + /** For filters whose name isn't a referenceable variable. */ + label?: string; + /** Replaces the tooltip, for filters whose name isn't a referenceable variable. */ + description?: string; + /** What validation errors call the field, e.g. "name". */ + noun?: string; } export const VariableNameInput = ({ control, otherFilters, + label = 'Variable name', + description, + noun, }: VariableNameInputProps) => { const { errors } = useFormState({ control }); const filterName = useWatch({ control, name: 'name' }); @@ -24,16 +33,19 @@ export const VariableNameInput = ({ return ( - validateVariableName({ value, otherFilters }) ?? true, + validateVariableName({ value, otherFilters, noun }) ?? true, })} /> diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/AdhocFilterEditForm.test.tsx b/packages/app/src/components/DashboardFiltersModal/__tests__/AdhocFilterEditForm.test.tsx new file mode 100644 index 0000000000..73a79b050d --- /dev/null +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/AdhocFilterEditForm.test.tsx @@ -0,0 +1,129 @@ +import { useForm } from 'react-hook-form'; +import { + AdhocDashboardFilter, + DashboardFilter, +} from '@hyperdx/common-utils/dist/types'; +import { screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { AdhocFilterEditForm } from '@/components/DashboardFiltersModal/AdhocFilterEditForm'; +import { + FilterFormValues, + toFormValues, +} from '@/components/DashboardFiltersModal/filterFormState'; + +jest.mock('@/source', () => ({ useSources: () => ({ data: [] }) })); +// The real inputs pull CodeMirror and source metadata into jsdom. +jest.mock('@/components/SearchInput/SearchWhereInput', () => ({ + __esModule: true, + default: () => null, + getStoredLanguage: () => undefined, +})); +jest.mock('@/components/SourceMultiSelect', () => ({ + SourceMultiSelectControlled: ({ name }: { name: string }) => ( +
+ ), +})); + +const adhoc = ( + overrides: Partial = {}, +): AdhocDashboardFilter => ({ + id: 'a1', + type: 'ADHOC', + name: 'Conditions', + sourceType: 'sql', + sources: ['logs'], + isBroadcastEnabled: true, + isVariableEnabled: true, + ...overrides, +}); + +function Harness({ + filter, + otherFilters, +}: { + filter: AdhocDashboardFilter; + otherFilters: DashboardFilter[]; +}) { + const { control, setValue } = useForm({ + defaultValues: toFormValues(filter), + mode: 'onChange', + }); + return ( + + ); +} + +const renderForm = ( + filter: AdhocDashboardFilter, + otherFilters: DashboardFilter[] = [], +) => renderWithMantine(); + +const warning = () => screen.queryByTestId('adhoc-filter-overlap-warning'); + +describe('AdhocFilterEditForm', () => { + it('always shows the broadcast scope, with no broadcast toggle', () => { + renderForm(adhoc()); + + expect( + screen.getByTestId('multi-select-appliesToSourceIds'), + ).toBeInTheDocument(); + expect( + screen.queryByTestId('filter-broadcast-checkbox'), + ).not.toBeInTheDocument(); + }); + + it('says the name is not a referenceable variable', () => { + renderForm(adhoc()); + + expect(screen.getByText('Unique name')).toBeInTheDocument(); + expect(screen.queryByText('Variable name')).not.toBeInTheDocument(); + expect( + screen.getByText(/can't be referenced as variables/), + ).toBeInTheDocument(); + }); + + it('calls the field a name, not a variable, in its errors', async () => { + renderForm(adhoc(), [ + adhoc({ id: 'a2', name: 'Other', variableName: 'taken' }), + ]); + + await userEvent.type( + screen.getByTestId('filter-variable-name-input'), + 'taken', + ); + + expect( + await screen.findByText( + 'This name is used by another filter on this dashboard (Other)', + ), + ).toBeInTheDocument(); + }); + + it('warns about another ad hoc filter reaching the same source', () => { + renderForm(adhoc(), [ + adhoc({ id: 'a2', name: 'Other', sources: ['traces'] }), + adhoc({ id: 'a3', name: 'Logs too', appliesToSourceIds: ['logs'] }), + ]); + + expect(warning()).toHaveTextContent('Another ad hoc filter (Logs too)'); + }); + + it('compares broadcast scopes rather than suggestion sources', () => { + renderForm(adhoc({ appliesToSourceIds: ['traces'] }), [ + adhoc({ id: 'a2', name: 'Other' }), + ]); + + expect(warning()).not.toBeInTheDocument(); + }); + + it('ignores ad hoc filters of the other source type', () => { + renderForm(adhoc(), [adhoc({ id: 'a2', sourceType: 'promql' })]); + + expect(warning()).not.toBeInTheDocument(); + }); +}); diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts index 699f02bba5..63e0497c84 100644 --- a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts @@ -89,7 +89,7 @@ describe('toFormValues', () => { sourceType: 'promql', sources: ['prom'], appliesToSourceIds: ['prom-2'], - isBroadcastEnabled: false, + isBroadcastEnabled: true, isVariableEnabled: true, variableName: 'conds', }); @@ -100,7 +100,7 @@ describe('toFormValues', () => { sources: ['prom'], appliesToSourceIds: ['prom-2'], variableName: 'conds', - isBroadcastEnabled: false, + isBroadcastEnabled: true, }); }); @@ -117,6 +117,7 @@ describe('toFormValues', () => { sources: ['logs'], where: 'Namespace:$namespace', whereLanguage: 'lucene', + isBroadcastEnabled: true, isVariableEnabled: true, }); @@ -294,7 +295,7 @@ describe('toSavedFilter', () => { expect(saved).not.toHaveProperty('whereLanguage'); }); - it('drops the ad hoc broadcast scope when broadcast is off', () => { + it('always broadcasts an ad hoc filter, even when switched from a non-broadcasting type', () => { const saved = toSavedFilter( formValues({ type: 'ADHOC', @@ -306,8 +307,8 @@ describe('toSavedFilter', () => { ); expect(saved).toMatchObject({ - isBroadcastEnabled: false, - appliesToSourceIds: undefined, + isBroadcastEnabled: true, + appliesToSourceIds: ['logs'], }); }); diff --git a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts index 7e450282eb..7b681fe2f5 100644 --- a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts +++ b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts @@ -149,7 +149,6 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { // Selection limits don't apply to conditions, so they aren't stored. if (values.type === 'ADHOC') { - const isBroadcastEnabled = isFilterBroadcastEnabled(values); return DashboardFilterSchema.parse({ id: values.id, type: values.type, @@ -158,10 +157,8 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { sources: values.sources, // Only SQL suggestions can be narrowed; the input is hidden otherwise ...(values.sourceType === 'sql' ? whereFields : {}), - isBroadcastEnabled, - // Hidden, and so unvalidated, while broadcast is off - appliesToSourceIds: - isBroadcastEnabled && appliesTo?.length ? appliesTo : undefined, + isBroadcastEnabled: true, + appliesToSourceIds: appliesTo?.length ? appliesTo : undefined, isVariableEnabled: true, variableName: getFilterVariableName(values), }); diff --git a/packages/app/src/components/FilterPill/__tests__/FilterConditionEditor.test.tsx b/packages/app/src/components/FilterPill/__tests__/FilterConditionEditor.test.tsx index 19e9740bbf..a1df5781c0 100644 --- a/packages/app/src/components/FilterPill/__tests__/FilterConditionEditor.test.tsx +++ b/packages/app/src/components/FilterPill/__tests__/FilterConditionEditor.test.tsx @@ -186,7 +186,13 @@ describe('FilterConditionEditor', () => { renderEditor({ operators: PROMQL_FILTER_OPERATORS }); await userEvent.click(screen.getByRole('combobox', { name: 'Operator' })); const options = await screen.findAllByRole('option', { hidden: true }); - expect(options.map(o => o.textContent)).toEqual(['=', '!=', '=~', '!~']); + expect(options.map(o => o.textContent)).toEqual([ + '=', + '!=', + '=~', + '!~', + '=|', + ]); }); it('disables Apply until a key is entered', async () => { diff --git a/packages/app/src/components/FilterPill/filterOperators.ts b/packages/app/src/components/FilterPill/filterOperators.ts index ece901cbf7..ad6a7488ca 100644 --- a/packages/app/src/components/FilterPill/filterOperators.ts +++ b/packages/app/src/components/FilterPill/filterOperators.ts @@ -23,14 +23,21 @@ export const SQL_FILTER_OPERATORS: FilterOperatorOption[] = [ { value: '!~', label: 'not regex', negated: true, ...REGEX_VALUE }, { value: 'LIKE', label: 'like', ...LIKE_VALUE }, { value: 'NOT LIKE', label: 'not like', negated: true, ...LIKE_VALUE }, + // One value per condition; the renderer ORs conditions sharing a key. + { + value: 'IN', + label: 'in', + valuePlaceholder: "OR'd with this key's other values", + }, ]; // Derived so the editor never offers an operator the PromQL broadcast skips. -// PromQL users know the operator syntax, so it doubles as the label. +// PromQL users know the operator syntax, so it doubles as the label. PromQL has +// no `IN`, so it borrows Grafana's `=|`. export const PROMQL_FILTER_OPERATORS: FilterOperatorOption[] = SQL_FILTER_OPERATORS.filter(op => PROMQL_ADHOC_FILTER_OPERATORS.includes(op.value), - ).map(op => ({ ...op, label: op.value })); + ).map(op => ({ ...op, label: op.value === 'IN' ? '=|' : op.value })); export function getFilterOperators( language: FilterLanguage, diff --git a/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx b/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx index 41f9223420..7e605b78a1 100644 --- a/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx +++ b/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx @@ -995,6 +995,7 @@ describe('useDashboardFilters', () => { const adhocFilter: AdhocDashboardFilter = { id: 'adhoc1', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Conditions', sourceType: 'sql', sources: ['logs'], @@ -1222,15 +1223,6 @@ describe('useDashboardFilters', () => { ).toEqual([conditionSql]); }); - it('applies nothing when broadcast is disabled', () => { - mockState = [{ type: 'adhoc', name: 'conds', conditions: [condition] }]; - const filters = [{ ...adhocFilter, isBroadcastEnabled: false }]; - - const { result } = renderHook(() => useDashboardFilters(filters)); - - expect(result.current.getFilterQueriesForSource('logs')).toEqual([]); - }); - describe('PromQL', () => { const promqlFilter: AdhocDashboardFilter = { ...adhocFilter, @@ -1274,14 +1266,6 @@ describe('useDashboardFilters', () => { ).toEqual([jobMatcher]); }); - it('applies nothing when broadcast is disabled', () => { - const filters = [{ ...promqlFilter, isBroadcastEnabled: false }]; - - const { result } = renderHook(() => useDashboardFilters(filters)); - - expect(result.current.getFilterQueriesForSource('prom')).toEqual([]); - }); - it('combines conditions across filters, deduplicated', () => { mockState = [ { diff --git a/packages/app/tests/e2e/features/dashboard-adhoc-filters.spec.ts b/packages/app/tests/e2e/features/dashboard-adhoc-filters.spec.ts index c2412e95ef..9f032a0b06 100644 --- a/packages/app/tests/e2e/features/dashboard-adhoc-filters.spec.ts +++ b/packages/app/tests/e2e/features/dashboard-adhoc-filters.spec.ts @@ -59,11 +59,13 @@ test.describe( dashboardPage.getAdhocFilterSourceTypeControl(), ).toBeVisible(); await expect(dashboardPage.getAdhocFilterSourcesInput()).toBeVisible(); - await expect(dashboardPage.broadcastFilterCheckbox).toBeChecked(); + // Always broadcasts, so the scope is shown without a checkbox. + await expect(dashboardPage.broadcastFilterCheckbox).toHaveCount(0); await expect(dashboardPage.appliesToSourceSelector).toBeVisible(); - // Always a variable, so the name is asked for rather than unlocked by - // a checkbox. await expect(dashboardPage.variableNameInput).toBeVisible(); + await expect( + form.getByText('Unique name', { exact: true }), + ).toBeVisible(); await expect(form.getByTestId('source-selector')).toHaveCount(0); await expect(form.getByText('Filter expression')).toHaveCount(0); @@ -114,7 +116,8 @@ test.describe( await expect(item).toContainText( `${DEFAULT_LOGS_SOURCE_NAME}, ${DEFAULT_TRACES_SOURCE_NAME}`, ); - await expect(item).toContainText('($conds)'); + // The name isn't a variable, so the list doesn't present it as one. + await expect(item).not.toContainText('$conds'); await expect( dashboardPage.getFilterBroadcastTarget('Conditions'), ).toHaveText( @@ -127,9 +130,8 @@ test.describe( await page.reload(); await dashboardPage.waitForLoaded(); await dashboardPage.openEditFiltersModal(); - await expect( - dashboardPage.getFilterItemByName('Conditions'), - ).toContainText('($conds)'); + await dashboardPage.openEditFilterForm('Conditions'); + await expect(dashboardPage.variableNameInput).toHaveValue('conds'); }); }); @@ -169,34 +171,19 @@ test.describe( await dashboardPage.variableNameInput.fill('where_clause'); await page.getByTestId('save-filter-button').click(); - await expect( - dashboardPage.getFilterItemByName('Conditions'), - ).toContainText('($where_clause)'); await expect( dashboardPage.getFilterBroadcastTarget('Conditions'), ).toHaveText(DEFAULT_TRACES_SOURCE_NAME); }); - await test.step('Turning broadcast off drops the broadcast attribute', async () => { - await dashboardPage.openEditFilterForm('Conditions'); - await dashboardPage.broadcastFilterCheckbox.uncheck(); - await expect(dashboardPage.appliesToSourceSelector).toHaveCount(0); - await page.getByTestId('save-filter-button').click(); - - await expect( - dashboardPage.getFilterItemByName('Conditions'), - ).toBeVisible(); - await expect( - dashboardPage.getFilterBroadcastTarget('Conditions'), - ).toHaveCount(0); - }); - await test.step('The edits survive a reload', async () => { await page.reload(); await dashboardPage.waitForLoaded(); await dashboardPage.openEditFiltersModal(); + await expect( + dashboardPage.getFilterBroadcastTarget('Conditions'), + ).toHaveText(DEFAULT_TRACES_SOURCE_NAME); await dashboardPage.openEditFilterForm('Conditions'); - await expect(dashboardPage.broadcastFilterCheckbox).not.toBeChecked(); await expect(dashboardPage.variableNameInput).toHaveValue( 'where_clause', ); diff --git a/packages/app/tests/e2e/features/dashboard-template-import.spec.ts b/packages/app/tests/e2e/features/dashboard-template-import.spec.ts index 6abeb69e86..5ee3f20415 100644 --- a/packages/app/tests/e2e/features/dashboard-template-import.spec.ts +++ b/packages/app/tests/e2e/features/dashboard-template-import.spec.ts @@ -134,6 +134,7 @@ function makeAdhocFilterTemplate({ { id: 'filter-1', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Conditions', sourceType: 'sql', sources, @@ -748,6 +749,7 @@ test.describe('Dashboard Template Import', { tag: ['@dashboard'] }, () => { expect(dashboard.filters).toHaveLength(1); expect(dashboard.filters[0]).toMatchObject({ type: 'ADHOC', + isBroadcastEnabled: true, sources: [logsSourceId, tracesSourceId], appliesToSourceIds: [tracesSourceId], }); @@ -841,6 +843,7 @@ test.describe('Dashboard Template Import', { tag: ['@dashboard'] }, () => { ); expect(dashboard.filters[0]).toMatchObject({ type: 'ADHOC', + isBroadcastEnabled: true, sources: [logsSourceId], appliesToSourceIds: [tracesSourceId], }); @@ -897,6 +900,7 @@ test.describe('Dashboard Template Import', { tag: ['@dashboard'] }, () => { ); expect(dashboard.filters[0]).toMatchObject({ type: 'ADHOC', + isBroadcastEnabled: true, sources: [tracesSourceId], }); }); @@ -990,6 +994,7 @@ test.describe('Dashboard Template Import', { tag: ['@dashboard'] }, () => { ); expect(dashboard.filters[0]).toMatchObject({ type: 'ADHOC', + isBroadcastEnabled: true, sources: [tracesSourceId, logsSourceId, sessionsSourceId], }); }); @@ -1047,6 +1052,7 @@ test.describe('Dashboard Template Import', { tag: ['@dashboard'] }, () => { ); expect(dashboard.filters[0]).toMatchObject({ type: 'ADHOC', + isBroadcastEnabled: true, sources: [logsSourceId], appliesToSourceIds: [logsSourceId], }); diff --git a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts index 0a3a177dd1..300e037754 100644 --- a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts +++ b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts @@ -907,6 +907,7 @@ describe('dashboardFilterValues', () => { ): AdhocDashboardFilter => ({ id: 'a1', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Conditions', sourceType: 'sql', sources: ['logs'], @@ -929,12 +930,6 @@ describe('dashboardFilterValues', () => { expect(ids(filters, builderTile, 'logs')).toEqual(['a1', 'a2']); }); - it('skips filters that do not broadcast', () => { - expect( - ids([adhoc({ isBroadcastEnabled: false })], builderTile, 'logs'), - ).toEqual([]); - }); - it('matches the filter language to the tile', () => { const filters = [ adhoc(), diff --git a/packages/common-utils/src/__tests__/filters.test.ts b/packages/common-utils/src/__tests__/filters.test.ts index c6cd27dca1..7c8c46a891 100644 --- a/packages/common-utils/src/__tests__/filters.test.ts +++ b/packages/common-utils/src/__tests__/filters.test.ts @@ -20,6 +20,7 @@ import { isAdhocConditionSupported, isFilterBroadcastEnabled, isFilterGlobalRequirement, + isFilterReferenceableVariable, isFilterRequired, isFilterVariableEnabled, isQueryExpressionFilter, @@ -871,6 +872,7 @@ describe('filters', () => { { id: 'conds', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Conditions', sourceType: 'sql', sources: ['logs'], @@ -895,6 +897,7 @@ describe('filters', () => { { id: 'conds', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Conditions', sourceType: 'promql', sources: ['metrics'], @@ -1749,14 +1752,12 @@ describe('filters', () => { name: 'Conditions', sourceType: 'sql', sources: ['logs', 'traces'], + isBroadcastEnabled: true, isVariableEnabled: true, }; expect(getFilterBroadcastTarget(adhoc)).toEqual({ appliesToSourceIds: ['logs', 'traces'], }); - expect( - getFilterBroadcastTarget({ ...adhoc, isBroadcastEnabled: false }), - ).toBeUndefined(); }); it('returns undefined when broadcasting is off', () => { @@ -1809,6 +1810,22 @@ describe('filters', () => { }); }); + describe('isFilterReferenceableVariable', () => { + it.each([ + ['QUERY_EXPRESSION', true, true], + ['STATIC_LIST', true, true], + ['QUERY_EXPRESSION', false, false], + ['ADHOC', true, false], + ] as const)( + '%s with variables %s: %s', + (type, isVariableEnabled, expected) => { + expect(isFilterReferenceableVariable({ type, isVariableEnabled })).toBe( + expected, + ); + }, + ); + }); + describe('isFilterRequired', () => { it('treats a missing or zero minimum as not required', () => { expect(isFilterRequired({})).toBe(false); @@ -1894,10 +1911,28 @@ describe('filters', () => { ['!~', "NOT match(toString(ServiceName), 'api')"], ['LIKE', "toString(ServiceName) LIKE 'api'"], ['NOT LIKE', "toString(ServiceName) NOT LIKE 'api'"], + ['IN', "toString(ServiceName) IN ('api')"], ])('renders %s', (operator, condition) => { expect(conditionFor(operator)).toEqual([{ type: 'sql', condition }]); }); + it('ORs IN conditions sharing a key, at the first one', () => { + expect( + adhocConditionsToFilters([ + { key: 'SeverityText', operator: '=', value: 'error' }, + { key: 'ServiceName', operator: 'IN', value: 'api' }, + { key: 'Env', operator: 'IN', value: 'prod' }, + { key: 'ServiceName', operator: 'IN', value: "it's" }, + { key: 'ServiceName', operator: '!=', value: 'web' }, + ]).map(filter => filter.condition), + ).toEqual([ + "toString(SeverityText) = 'error'", + "toString(ServiceName) IN ('api', 'it''s')", + "toString(Env) IN ('prod')", + "toString(ServiceName) != 'web'", + ]); + }); + it('passes LIKE patterns through as written', () => { expect(conditionFor('LIKE', '%err_r%')).toEqual([ { type: 'sql', condition: "toString(ServiceName) LIKE '%err_r%'" }, @@ -2073,10 +2108,21 @@ describe('filters', () => { ['!=', 'service!="api"'], ['=~', 'service=~"api"'], ['!~', 'service!~"api"'], + ['IN', 'service=~"api"'], ])('renders %s', (operator, matcher) => { expect(matcherFor(operator)).toEqual([matcher]); }); + it('ORs IN conditions sharing a label into one escaped regex', () => { + expect( + adhocConditionsToPromqlFilters([ + { key: 'service', operator: 'IN', value: 'api' }, + { key: 'job', operator: 'IN', value: 'node' }, + { key: 'service', operator: 'IN', value: 'a.b\\c' }, + ]).map(filter => filter.condition), + ).toEqual(['service=~"(api|a\\\\.b\\\\\\\\c)"', 'job=~"node"']); + }); + it.each(['LIKE', 'NOT LIKE'])( 'skips %s rather than throwing', operator => { @@ -2128,6 +2174,8 @@ describe('filters', () => { ['promql', 'NOT LIKE', false], ['promql', '=~', true], ['promql', '!=', true], + ['sql', 'IN', true], + ['promql', 'IN', true], ])('%s supports %s: %s', (sourceType, operator, expected) => { expect( isAdhocConditionSupported(sourceType, { @@ -2294,6 +2342,19 @@ describe('filters', () => { ).toEqual([]); }); + it('skips ad hoc filters, whose name is not referenceable', () => { + const adhoc: AdhocDashboardFilter = { + id: 'a1', + type: 'ADHOC', + name: 'Conditions', + sourceType: 'sql', + sources: ['logs'], + isBroadcastEnabled: true, + isVariableEnabled: true, + }; + expect(getDashboardVariableFilters([adhoc])).toEqual([]); + }); + it('skips a filter whose display name derives nothing usable', () => { expect( getDashboardVariableFilters([ @@ -2535,6 +2596,18 @@ describe('filters', () => { ); }); + it('names the field by the given noun', () => { + const other = [variableFilter({ name: 'Env', variableName: 'env' })]; + const validate = (value: string) => + validateVariableName({ value, otherFilters: other, noun: 'name' }); + + expect(validate('')).toBe('Name is required'); + expect(validate('1env')).toMatch(/^Names must start with a letter/); + expect(validate('env')).toBe( + 'This name is used by another filter on this dashboard (Env)', + ); + }); + it('compares names case-sensitively', () => { expect( validateVariableName({ diff --git a/packages/common-utils/src/__tests__/types.test.ts b/packages/common-utils/src/__tests__/types.test.ts index 4f5b3b2906..364f6fef1c 100644 --- a/packages/common-utils/src/__tests__/types.test.ts +++ b/packages/common-utils/src/__tests__/types.test.ts @@ -758,6 +758,7 @@ describe('DashboardFilterSchema ad hoc variant', () => { const adhocFilter = { id: 'f1', type: 'ADHOC' as const, + isBroadcastEnabled: true as const, name: 'Conditions', sourceType: 'sql' as const, sources: ['source-1'], @@ -782,6 +783,15 @@ describe('DashboardFilterSchema ad hoc variant', () => { }).success, ).toBe(false); }); + + it.each([false, undefined])('rejects isBroadcastEnabled: %s', value => { + expect( + DashboardFilterSchema.safeParse({ + ...adhocFilter, + isBroadcastEnabled: value, + }).success, + ).toBe(false); + }); }); // Preset dashboards are broadcast-only, so the preset schema extends the diff --git a/packages/common-utils/src/__tests__/utils.test.ts b/packages/common-utils/src/__tests__/utils.test.ts index 0f6687e09b..8485e745c7 100644 --- a/packages/common-utils/src/__tests__/utils.test.ts +++ b/packages/common-utils/src/__tests__/utils.test.ts @@ -1390,6 +1390,7 @@ describe('utils', () => { { id: 'filter-scoped', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Scoped', sourceType: 'sql', sources: ['source1', 'source2'], @@ -1400,6 +1401,7 @@ describe('utils', () => { { id: 'filter-unresolved', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Unresolved', sourceType: 'sql', sources: ['source1'], @@ -1416,6 +1418,7 @@ describe('utils', () => { { id: 'filter-scoped', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Scoped', sourceType: 'sql', sources: ['Logs', 'Traces'], @@ -1426,6 +1429,7 @@ describe('utils', () => { { id: 'filter-unresolved', type: 'ADHOC', + isBroadcastEnabled: true, name: 'Unresolved', sourceType: 'sql', sources: ['Logs'], diff --git a/packages/common-utils/src/filters.ts b/packages/common-utils/src/filters.ts index 260b8735ac..ed946aede5 100644 --- a/packages/common-utils/src/filters.ts +++ b/packages/common-utils/src/filters.ts @@ -24,6 +24,7 @@ import { } from '@/types'; import { escapePromqlStringValue, + formatVariableValues, getVariableReferences, substituteVariables, } from '@/variables'; @@ -904,6 +905,18 @@ export function isFilterVariableEnabled(filter: { return filter.isVariableEnabled === true; } +/** + * Whether tiles can reference a filter's selection as `$variableName`. An ad + * hoc filter is variable-enabled only so its name stays unique; the name just + * keys its conditions. + */ +export function isFilterReferenceableVariable(filter: { + type?: DashboardFilterKind; + isVariableEnabled?: boolean; +}): boolean { + return isFilterVariableEnabled(filter) && filter.type !== 'ADHOC'; +} + /** * Whether a filter must have at least one value selected before the tiles it * covers will load. @@ -1013,11 +1026,39 @@ export function isAdhocFilterValue( export const isAdhocComparableDataType = (type: string): boolean => !/\bDateTime/.test(type); +/** A condition with the values of every condition it was merged with. */ +type GroupedAdhocCondition = { + condition: AdhocFilterCondition; + values: string[]; +}; + +/** + * Merge the `IN` conditions that share a key into the first of them, so their + * values can be OR'd. Other conditions keep one value each. + */ +const groupAdhocConditionsByKey = ( + conditions: AdhocFilterCondition[], +): GroupedAdhocCondition[] => { + const valuesByKey = new Map(); + const grouped: GroupedAdhocCondition[] = []; + for (const condition of conditions) { + const isIn = condition.operator === 'IN'; + const existing = isIn ? valuesByKey.get(condition.key) : undefined; + if (existing) { + existing.push(condition.value); + continue; + } + const values = [condition.value]; + if (isIn) valuesByKey.set(condition.key, values); + grouped.push({ condition, values }); + } + return grouped; +}; + const renderAdhocConditionSql = ({ - key, - operator, - value, -}: AdhocFilterCondition): string => { + condition: { key, operator, value }, + values, +}: GroupedAdhocCondition): string => { // Stringified like broadcast filter selections, so Map/JSON/Dynamic values // compare as strings. const target = `toString(${key})`; @@ -1032,6 +1073,8 @@ const renderAdhocConditionSql = ({ return `match(${target}, ${literal})`; case '!~': return `NOT match(${target}, ${literal})`; + case 'IN': + return `${target} IN (${formatVariableValues({ values }, 'sqlstring')})`; default: operator satisfies never; throw new Error(`Unknown ad hoc filter operator '${operator}'`); @@ -1039,16 +1082,17 @@ const renderAdhocConditionSql = ({ }; /** - * Render the conditions of a SQL ad hoc filter as filters, one per condition. - * Keys are SQL expressions and are used verbatim. + * Render the conditions of a SQL ad hoc filter as filters, one per condition, + * except that `IN` conditions sharing a key become one. Keys are SQL + * expressions and are used verbatim. */ export function adhocConditionsToFilters( conditions: AdhocFilterCondition[], ): ConditionFilter[] { - return conditions.map( - (condition): ConditionFilter => ({ + return groupAdhocConditionsByKey(conditions).map( + (grouped): ConditionFilter => ({ type: 'sql', - condition: renderAdhocConditionSql(condition), + condition: renderAdhocConditionSql(grouped), }), ); } @@ -1109,10 +1153,9 @@ export function mergeAdhocConditions( const LEGACY_LABEL_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/; const renderAdhocMatcherPromql = ({ - key, - operator, - value, -}: AdhocFilterCondition): string => { + condition: { key, operator, value }, + values, +}: GroupedAdhocCondition): string => { // Label names outside the legacy charset must be quoted (Prometheus 3). const label = LEGACY_LABEL_NAME.test(key) ? key @@ -1123,6 +1166,10 @@ const renderAdhocMatcherPromql = ({ case '=~': case '!~': return `${label}${operator}"${escapePromqlStringValue(value)}"`; + case 'IN': { + const pattern = formatVariableValues({ values }, 'regex'); + return `${label}=~"${escapePromqlStringValue(pattern)}"`; + } case 'LIKE': case 'NOT LIKE': throw new Error( @@ -1155,20 +1202,22 @@ export function isAdhocConditionSupported( /** * Render the conditions of a PromQL ad hoc filter as label matchers, one per - * condition. Conditions PromQL can't express are skipped; callers report them + * condition, except that `IN` conditions sharing a label become one regex + * matcher. Conditions PromQL can't express are skipped; callers report them * using `isAdhocConditionSupported`. */ export function adhocConditionsToPromqlFilters( conditions: AdhocFilterCondition[], ): PromqlConditionFilter[] { - return conditions - .filter(condition => isAdhocConditionSupported('promql', condition)) - .map( - (condition): PromqlConditionFilter => ({ - type: 'promql', - condition: renderAdhocMatcherPromql(condition), - }), - ); + const supported = conditions.filter(condition => + isAdhocConditionSupported('promql', condition), + ); + return groupAdhocConditionsByKey(supported).map( + (grouped): PromqlConditionFilter => ({ + type: 'promql', + condition: renderAdhocMatcherPromql(grouped), + }), + ); } function isPromqlFilter( @@ -1258,6 +1307,7 @@ export type DashboardVariableDeclaration = Pick< /** Minimal projection of fields necessary to extract the variables a dashboard declares. */ export type FilterForVariableDeclaration = { + type?: DashboardFilterKind; name: string; expression?: string; variableName?: string; @@ -1276,7 +1326,7 @@ export function getDashboardVariableFilters< const takenNames = new Set(); for (const filter of filters ?? []) { - if (!isFilterVariableEnabled(filter)) continue; + if (!isFilterReferenceableVariable(filter)) continue; // There shouldn't be any duplicate names, but if there are then the first one wins. const name = getFilterVariableName(filter); @@ -1423,6 +1473,7 @@ export function getPendingFilterValuesVariables( export function validateVariableName({ value, otherFilters, + noun = 'variable name', }: { value: string | undefined; otherFilters: { @@ -1430,16 +1481,19 @@ export function validateVariableName({ variableName?: string; isVariableEnabled?: boolean; }[]; + /** What the messages call the field, for filters whose name isn't a variable. */ + noun?: string; }): string | undefined { + const capitalized = noun.charAt(0).toUpperCase() + noun.slice(1); const trimmed = (value ?? '').trim(); if (!trimmed) { - return 'Variable name is required'; + return `${capitalized} is required`; } if (trimmed.length > DASHBOARD_VARIABLE_NAME_MAX_LENGTH) { - return `Variable name must be ${DASHBOARD_VARIABLE_NAME_MAX_LENGTH} characters or fewer`; + return `${capitalized} must be ${DASHBOARD_VARIABLE_NAME_MAX_LENGTH} characters or fewer`; } if (!DASHBOARD_VARIABLE_NAME_PATTERN_ANCHORED.test(trimmed)) { - return 'Variable names must start with a letter and may contain only letters, numbers, and underscores'; + return `${capitalized}s must start with a letter and may contain only letters, numbers, and underscores`; } const clash = otherFilters.find( other => @@ -1447,7 +1501,7 @@ export function validateVariableName({ getFilterVariableName(other) === trimmed, ); if (clash) { - return `This variable name is used by another filter on this dashboard (${clash.name})`; + return `This ${noun} is used by another filter on this dashboard (${clash.name})`; } return undefined; } diff --git a/packages/common-utils/src/types.ts b/packages/common-utils/src/types.ts index 341fb09397..67a347e598 100644 --- a/packages/common-utils/src/types.ts +++ b/packages/common-utils/src/types.ts @@ -1343,10 +1343,15 @@ export const AdhocFilterOperatorSchema = z.enum([ '!~', 'LIKE', 'NOT LIKE', + 'IN', ]); export type AdhocFilterOperator = z.infer; +/** + * `IN` conditions sharing a key are OR'd together when rendered; every other + * condition is AND'd. + */ export const SQL_ADHOC_FILTER_OPERATORS: readonly AdhocFilterOperator[] = AdhocFilterOperatorSchema.options; @@ -1355,6 +1360,7 @@ export const PROMQL_ADHOC_FILTER_OPERATORS: readonly AdhocFilterOperator[] = [ '!=', '=~', '!~', + 'IN', ]; /** One `key operator value` condition picked in an ad hoc filter. */ @@ -2458,8 +2464,12 @@ export const AdhocDashboardFilterSchema = dashboardFilterBaseSchema * empty means the filter's `sources`. */ appliesToSourceIds: z.array(z.string().min(1)).optional(), - /** Undefined / missing means ENABLED, as for QUERY_EXPRESSION filters. */ - isBroadcastEnabled: z.boolean().optional(), + // Ad hoc conditions can't be referenced as variables, so broadcast is how they apply. + isBroadcastEnabled: z.literal(true), + /** + * Keeps `variableName` unique among the dashboard's variable names, which + * share the `filters=` param. Not referenceable as `$variableName`. + */ isVariableEnabled: z.literal(true), }) .strict(); From 6705e505dea2256009a9a00d48c9843c53ec02fd Mon Sep 17 00:00:00 2001 From: Aaron Knudtson <87577305+knudtty@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:49:56 -0500 Subject: [PATCH 25/55] feat(api): support ad hoc dashboard filters in the external API (#3659) --- .changeset/adhoc-filters-external-api.md | 10 + packages/api/openapi.json | 177 +++++++++++- .../src/mcp/tools/dashboards/getDashboard.ts | 1 + .../mcp/tools/dashboards/getDashboardTile.ts | 1 + .../mcp/tools/dashboards/patchDashboard.ts | 6 +- .../api/src/mcp/tools/dashboards/queryTile.ts | 1 + .../src/mcp/tools/dashboards/queryTiles.ts | 1 + .../src/mcp/tools/dashboards/saveDashboard.ts | 2 + .../src/mcp/tools/dashboards/validation.ts | 5 +- packages/api/src/routers/api/dashboards.ts | 58 +--- .../__tests__/dashboards.int.test.ts | 269 +++++++++++++++++- .../src/routers/external-api/v2/dashboards.ts | 143 +++++++++- .../v2/utils/__tests__/dashboards.test.ts | 37 +++ .../external-api/v2/utils/dashboards.ts | 98 ++++--- .../src/utils/__tests__/filterSources.test.ts | 108 +++++++ packages/api/src/utils/externalApi.ts | 31 +- packages/api/src/utils/filterSources.ts | 80 ++++++ packages/api/src/utils/zod.ts | 18 +- .../src/__tests__/dashboardValidation.test.ts | 24 ++ .../common-utils/src/dashboardValidation.ts | 21 ++ 20 files changed, 957 insertions(+), 134 deletions(-) create mode 100644 .changeset/adhoc-filters-external-api.md create mode 100644 packages/api/src/utils/__tests__/filterSources.test.ts create mode 100644 packages/api/src/utils/filterSources.ts diff --git a/.changeset/adhoc-filters-external-api.md b/.changeset/adhoc-filters-external-api.md new file mode 100644 index 0000000000..9edb98ee56 --- /dev/null +++ b/.changeset/adhoc-filters-external-api.md @@ -0,0 +1,10 @@ +--- +'@hyperdx/api': minor +--- + +feat: Create, read, and update ad hoc dashboard filters through the external API + +`/api/v2/dashboards` now accepts and returns `ADHOC` filters, with SQL and +PromQL source types, and their `adhoc` entries in `savedFilterValues`. Each +filter's sources must exist and be a kind its `sourceType` supports. MCP still +hides ad hoc filters. diff --git a/packages/api/openapi.json b/packages/api/openapi.json index 604e11c631..65ea9dff2b 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -959,13 +959,16 @@ "description": "Query language for the where clause." }, "SavedFilterValue": { - "description": "A single saved dashboard filter selection. Either a rendered SQL condition, or a selection addressed by the name of the dashboard variable it belongs to.\n", + "description": "A single saved dashboard filter selection. Either a rendered SQL condition, a selection addressed by the name of the dashboard variable it belongs to, or the conditions of an ADHOC filter.\n", "oneOf": [ { "$ref": "#/components/schemas/SqlSavedFilterValue" }, { "$ref": "#/components/schemas/VariableSavedFilterValue" + }, + { + "$ref": "#/components/schemas/AdhocSavedFilterValue" } ] }, @@ -1029,6 +1032,77 @@ } } }, + "AdhocSavedFilterValue": { + "type": "object", + "required": [ + "type", + "name", + "conditions" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "adhoc" + ], + "description": "Filter type.", + "example": "adhoc" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "The variableName of the ADHOC filter these conditions belong to.", + "example": "conditions" + }, + "conditions": { + "type": "array", + "maxItems": 100, + "description": "The filter's conditions.", + "items": { + "$ref": "#/components/schemas/AdhocFilterCondition" + } + } + } + }, + "AdhocFilterCondition": { + "type": "object", + "description": "One \"key operator value\" condition. Conditions are AND'd, except that IN conditions sharing a key are OR'd into one: IN (...) for sql filters, a =~\"a|b\" matcher for promql filters.\n", + "required": [ + "key", + "operator", + "value" + ], + "properties": { + "key": { + "type": "string", + "minLength": 1, + "maxLength": 10000, + "description": "A SQL expression (column or map access) for sql filters, or a label name for promql filters.", + "example": "ServiceName" + }, + "operator": { + "type": "string", + "enum": [ + "=", + "!=", + "=~", + "!~", + "LIKE", + "NOT LIKE", + "IN" + ], + "description": "Comparison operator. =~ and !~ match a regular expression. IN takes one value per condition. LIKE and NOT LIKE apply to sql filters only; a condition its filter's sourceType can't express is not applied.\n", + "example": "=" + }, + "value": { + "type": "string", + "maxLength": 10000, + "description": "Value, pattern, or regular expression to compare against.", + "example": "api" + } + } + }, "MetricDataType": { "type": "string", "enum": [ @@ -3954,6 +4028,9 @@ }, { "$ref": "#/components/schemas/SqlQueryFilterInput" + }, + { + "$ref": "#/components/schemas/AdhocFilterInput" } ], "discriminator": { @@ -3962,7 +4039,8 @@ "QUERY_EXPRESSION": "#/components/schemas/QueryExpressionFilterInput", "STATIC_LIST": "#/components/schemas/StaticListFilterInput", "PROMETHEUS_LABEL": "#/components/schemas/PrometheusLabelFilterInput", - "SQL_QUERY": "#/components/schemas/SqlQueryFilterInput" + "SQL_QUERY": "#/components/schemas/SqlQueryFilterInput", + "ADHOC": "#/components/schemas/AdhocFilterInput" } } }, @@ -4352,6 +4430,101 @@ } } }, + "AdhocFilterInput": { + "type": "object", + "description": "A filter holding free-form \"key operator value\" conditions, with keys\nand values suggested from its sources: columns and map keys for sql\nsources, labels for promql sources. Its conditions are always\nbroadcast to the tiles it applies to: as WHERE conditions on builder\ntiles and raw sql tiles using the $__filters macro, or as label\nmatchers on PromQL tiles. Its conditions are saved in\nsavedFilterValues as an \"adhoc\" entry. Ad hoc filters are a preview\nfeature.\n", + "required": [ + "type", + "name", + "sourceType", + "sources" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "ADHOC" + ], + "description": "Discriminator. Must be \"ADHOC\".", + "example": "ADHOC" + }, + "name": { + "type": "string", + "minLength": 1, + "description": "Display name for the dashboard filter", + "example": "Conditions" + }, + "sourceType": { + "type": "string", + "enum": [ + "sql", + "promql" + ], + "description": "The kind of sources the filter reads keys from and applies to: Log,\nTrace, or Session sources for sql, PromQL sources for promql.\n", + "example": "sql" + }, + "sources": { + "type": "array", + "minItems": 1, + "items": { + "type": "string" + }, + "description": "IDs of the sources whose keys and values the filter suggests, all of sourceType.", + "example": [ + "65f5e4a3b9e77c001a111111" + ] + }, + "where": { + "type": "string", + "description": "Optional condition narrowing the rows keys and values are suggested\nfrom. Never applied to tiles. May reference the dashboard's\nvariables. sql filters only: rejected when sourceType is promql.\n", + "example": "ServiceName:api" + }, + "whereLanguage": { + "type": "string", + "enum": [ + "sql", + "lucene" + ], + "description": "Language of the where condition. Rejected when sourceType is promql.", + "example": "lucene" + }, + "appliesToSourceIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "IDs of the sources whose tiles the conditions apply to, all of\nsourceType. Omit or send an empty array to apply to the tiles of\nthe filter's sources.\n", + "example": [ + "65f5e4a3b9e77c001a111111" + ] + }, + "isBroadcastEnabled": { + "type": "boolean", + "enum": [ + true + ], + "default": true, + "description": "Must be true or omitted.", + "example": true + }, + "isVariableEnabled": { + "type": "boolean", + "enum": [ + true + ], + "default": true, + "description": "Must be true or omitted.", + "example": true + }, + "variableName": { + "type": "string", + "maxLength": 64, + "pattern": "^[a-zA-Z][a-zA-Z0-9_]*$", + "description": "Unique name the filter's conditions are saved under, in\nsavedFilterValues and the dashboard URL. Tiles can't reference it\nas a variable. Defaults to the display name with whitespace\nreplaced by underscores and remaining illegal characters removed.\nMust be unique across a dashboard's variable-enabled filters.\n", + "example": "conditions" + } + } + }, "Filter": { "allOf": [ { diff --git a/packages/api/src/mcp/tools/dashboards/getDashboard.ts b/packages/api/src/mcp/tools/dashboards/getDashboard.ts index a18f09952b..2133ec09b3 100644 --- a/packages/api/src/mcp/tools/dashboards/getDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/getDashboard.ts @@ -63,6 +63,7 @@ export function registerGetDashboard({ } const externalDashboard = convertToExternalDashboard(dashboard, { hidePromql: !isPromqlEnabled(context), + hideAdhoc: true, }); return { content: [ diff --git a/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts b/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts index f9a4d2632f..7d331d965c 100644 --- a/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts +++ b/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts @@ -51,6 +51,7 @@ export function registerGetDashboardTile({ const externalDashboard = convertToExternalDashboard(dashboard, { hidePromql: !isPromqlEnabled(context), + hideAdhoc: true, }); const tile = externalDashboard.tiles.find(t => t.id === tileId); if (!tile) { diff --git a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts index aeea54d7bd..4488ca1c7b 100644 --- a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts @@ -15,7 +15,7 @@ import { isConfigTile, validateDashboardTiles, } from '@/routers/external-api/v2/utils/dashboards'; -import { getExternalCompatibleFilterValues } from '@/utils/externalApi'; +import { getMcpCompatibleFilterValues } from '@/utils/externalApi'; import type { ExternalDashboardTileWithId } from '@/utils/zod'; import { externalDashboardTileSchemaWithId } from '@/utils/zod'; @@ -127,7 +127,7 @@ export function registerPatchDashboard({ // Convert only for the error message (read-only, no write-back). const externalDashboard = convertToExternalDashboard( existingDashboard, - { hidePromql: !promqlEnabled }, + { hidePromql: !promqlEnabled, hideAdhoc: true }, ); return mcpUserError( `Tile not found: ${tileId}. Available tile IDs: ${externalDashboard.tiles.map(t => `${t.id} (${t.name})`).join(', ')}`, @@ -271,7 +271,7 @@ export function registerPatchDashboard({ tags: updatedDashboard.tags, ...(savedFilterValues !== undefined ? { - savedFilterValues: getExternalCompatibleFilterValues( + savedFilterValues: getMcpCompatibleFilterValues( updatedDashboard.savedFilterValues, ), } diff --git a/packages/api/src/mcp/tools/dashboards/queryTile.ts b/packages/api/src/mcp/tools/dashboards/queryTile.ts index b6cd385b57..0f9df6b116 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTile.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTile.ts @@ -78,6 +78,7 @@ export function registerQueryTile({ const externalDashboard = convertToExternalDashboard(dashboard, { hidePromql: !isPromqlEnabled(context), + hideAdhoc: true, }); const tile = externalDashboard.tiles.find(t => t.id === tileId); if (!tile) { diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index 44af35c950..9860ad768c 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -184,6 +184,7 @@ export function registerQueryTiles({ const externalDashboard = convertToExternalDashboard(dashboard, { hidePromql: !isPromqlEnabled(context), + hideAdhoc: true, }); const allTiles = externalDashboard.tiles; diff --git a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts index ba0c0d21e3..bde01373e8 100644 --- a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts @@ -236,6 +236,7 @@ async function createDashboard({ const externalDashboard = convertToExternalDashboard(newDashboard, { hidePromql: !promqlEnabled, + hideAdhoc: true, }); return { content: [ @@ -452,6 +453,7 @@ async function updateDashboard({ const externalDashboard = convertToExternalDashboard(updatedDashboard, { hidePromql: !promqlEnabled, + hideAdhoc: true, }); return { content: [ diff --git a/packages/api/src/mcp/tools/dashboards/validation.ts b/packages/api/src/mcp/tools/dashboards/validation.ts index 72f844579a..ff672ab5cd 100644 --- a/packages/api/src/mcp/tools/dashboards/validation.ts +++ b/packages/api/src/mcp/tools/dashboards/validation.ts @@ -19,6 +19,7 @@ import { TIME_RANGE_MACROS, } from '@hyperdx/common-utils/dist/macros'; import { + DashboardFilterValue, DisplayType, QueryExpressionDashboardFilter, SavedChartConfig, @@ -38,8 +39,6 @@ import { } from '@/routers/external-api/v2/utils/dashboards'; import type { ExternalDashboardTileWithId } from '@/utils/zod'; -import type { McpSavedFilterValues } from './schemas'; - /** * Returns one entry per raw SQL tile that uses a source-dependent macro but * does not set a `sourceId`, recording which macro(s) triggered it so callers @@ -264,7 +263,7 @@ export function getFilterVariableWarnings( * applies. Warn so the agent can fix the name or add the filter. */ export function getSavedFilterValueWarnings( - savedFilterValues: McpSavedFilterValues | undefined, + savedFilterValues: DashboardFilterValue[] | undefined, filters: FilterForVariableDeclaration[] | undefined, ): string[] { if (!savedFilterValues?.length) return []; diff --git a/packages/api/src/routers/api/dashboards.ts b/packages/api/src/routers/api/dashboards.ts index 0fb5d54f88..e88f39e324 100644 --- a/packages/api/src/routers/api/dashboards.ts +++ b/packages/api/src/routers/api/dashboards.ts @@ -3,12 +3,7 @@ import { validateDashboardFilterOptionUniqueness, validateDashboardFilterVariableNames, } from '@hyperdx/common-utils/dist/dashboardValidation'; -import { - getAdhocFilterSourceKinds, - isAdhocFilter, - isPrometheusLabelFilter, - isSqlQueryFilter, -} from '@hyperdx/common-utils/dist/filters'; +import { isSqlQueryFilter } from '@hyperdx/common-utils/dist/filters'; import { DashboardFilter, DashboardSchema, @@ -16,7 +11,6 @@ import { PresetDashboard, PresetDashboardFilterSchema, resolveChartPaletteToken, - SourceKind, walkRawDashboardTileColors, } from '@hyperdx/common-utils/dist/types'; import express from 'express'; @@ -41,6 +35,10 @@ import { import { getSources } from '@/controllers/sources'; import { getNonNullUserWithTeam } from '@/middleware/auth'; import type { ObjectId } from '@/models'; +import { + getChangedFilterSourceRefs, + getFilterSourceRefError, +} from '@/utils/filterSources'; import { objectIdSchema } from '@/utils/zod'; // create routes that will get and update dashboards @@ -66,22 +64,6 @@ const addFilterIssues = ( validateDashboardFilterOptionUniqueness(data.filters ?? [], ctx); }; -/** The sources a filter reads from, each with the kinds it must be. */ -function getFilterSourceRefs( - filter: DashboardFilter, -): { id: string; kinds: SourceKind[] }[] { - if (isPrometheusLabelFilter(filter)) { - return [{ id: filter.source, kinds: [SourceKind.Promql] }]; - } - if (isAdhocFilter(filter)) { - const kinds = getAdhocFilterSourceKinds(filter.sourceType); - return [...filter.sources, ...(filter.appliesToSourceIds ?? [])].map( - id => ({ id, kinds }), - ); - } - return []; -} - /** * Rejects PROMETHEUS_LABEL and ADHOC filters that reference a source that is * missing or of the wrong kind. Resolving these filters needs a live source of @@ -95,33 +77,9 @@ async function validateFilterSources( filters: DashboardFilter[] = [], existingFilters: DashboardFilter[] = [], ): Promise { - const refKey = ({ id, kinds }: { id: string; kinds: SourceKind[] }) => - `${id}:${kinds.join(',')}`; - const existingRefsById = new Map( - existingFilters.map(filter => [ - filter.id, - new Set(getFilterSourceRefs(filter).map(refKey)), - ]), - ); - const newRefs = filters.flatMap(filter => - getFilterSourceRefs(filter).filter( - ref => !existingRefsById.get(filter.id)?.has(refKey(ref)), - ), - ); - if (newRefs.length === 0) return null; - - const sources = await getSources(teamId.toString()); - const kindById = new Map(sources.map(s => [s._id.toString(), s.kind])); - const invalid = new Set( - newRefs - .filter(({ id, kinds }) => { - const kind = kindById.get(id); - return kind === undefined || !kinds.includes(kind); - }) - .map(({ id }) => id), - ); - if (invalid.size === 0) return null; - return `The following filter source IDs do not exist or are not a kind of source the filter supports: ${[...invalid].join(', ')}`; + const refs = getChangedFilterSourceRefs(filters, existingFilters); + if (refs.length === 0) return null; + return getFilterSourceRefError(refs, await getSources(teamId.toString())); } /** 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 5f4dabc483..92a72d9767 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 @@ -6546,7 +6546,7 @@ describe('External API v2 Dashboards - new format', () => { expect(response.status).toBe(400); expect(JSON.stringify(response.body)).toContain( - `PROMETHEUS_LABEL filters require a PromQL source. The following source IDs are not PromQL sources: ${traceSource._id.toString()}`, + `The following filter source IDs do not exist or are not a kind of source the filter supports: ${traceSource._id.toString()}`, ); }); @@ -6556,10 +6556,28 @@ describe('External API v2 Dashboards - new format', () => { expect(response.status).toBe(400); expect(JSON.stringify(response.body)).toContain( - `Could not find the following source IDs: ${sourceId}`, + `The following filter source IDs do not exist or are not a kind of source the filter supports: ${sourceId}`, ); }); + it('accepts a GET response PUT back after its source was deleted', async () => { + const dashboard = await createTestDashboard({ + filters: [ + { + ...omit(promqlFilterInput(), 'sourceId'), + source: new ObjectId().toString(), + }, + ], + }); + const { data } = ( + await authRequest('get', `${BASE_URL}/${dashboard._id}`).expect(200) + ).body; + + await authRequest('put', `${BASE_URL}/${dashboard._id}`) + .send({ ...omit(data, 'id'), name: 'Renamed' }) + .expect(200); + }); + it.each([ ['broadcast enabled', { isBroadcastEnabled: true }], ['not variable-enabled', { isVariableEnabled: false }], @@ -8510,9 +8528,16 @@ describe('External API v2 Dashboards - new format', () => { conditions: [{ key: 'ServiceName', operator: '=', value: 'api' }], }; - it('hides ad hoc filters and their saved values from GET', async () => { + const promqlAdhocFilter = () => ({ + ...adhocFilter(), + sourceType: 'promql' as const, + sources: [promqlSource._id.toString()], + }); + + it('returns ad hoc filters and their saved values from GET', async () => { + const filter = adhocFilter(); const dashboard = await createTestDashboard({ - filters: [adhocFilter()], + filters: [filter], savedFilterValues: [adhocValue], }); @@ -8521,25 +8546,249 @@ describe('External API v2 Dashboards - new format', () => { `${BASE_URL}/${dashboard._id}`, ).expect(200); - expect(response.body.data.filters).toEqual([]); - expect(response.body.data.savedFilterValues).toEqual([]); + expect(response.body.data.filters).toEqual([filter]); + expect(response.body.data.savedFilterValues).toEqual([adhocValue]); + }); + + it('creates SQL and PromQL ad hoc filters with saved conditions', async () => { + const promqlValue = { + type: 'adhoc' as const, + name: 'prom', + conditions: [{ key: 'job', operator: 'IN', value: 'api' }], + }; + const response = await authRequest('post', BASE_URL) + .send( + createMockDashboard(traceSource._id.toString(), { + filters: [ + omit( + { ...adhocFilter(), appliesToSourceIds: [traceSource._id] }, + 'id', + ), + // The mode flags default when omitted. + omit( + { ...promqlAdhocFilter(), name: 'Prom', variableName: 'prom' }, + 'id', + 'isBroadcastEnabled', + 'isVariableEnabled', + ), + ], + savedFilterValues: [adhocValue, promqlValue], + }), + ) + .expect(200); + + expect(response.body.data.filters).toEqual([ + { + ...adhocFilter(), + id: expect.any(String), + appliesToSourceIds: [traceSource._id.toString()], + }, + { + ...promqlAdhocFilter(), + id: expect.any(String), + name: 'Prom', + variableName: 'prom', + }, + ]); + expect(response.body.data.savedFilterValues).toEqual([ + adhocValue, + promqlValue, + ]); + + const stored = await Dashboard.findById(response.body.data.id).lean(); + expect(stored?.filters?.[1]).toMatchObject({ + type: 'ADHOC', + sourceType: 'promql', + sources: [promqlSource._id.toString()], + isBroadcastEnabled: true, + }); + }); + + it('round-trips a GET response through PUT', async () => { + const dashboard = await createTestDashboard({ + filters: [adhocFilter()], + savedFilterValues: [adhocValue], + }); + const { data } = ( + await authRequest('get', `${BASE_URL}/${dashboard._id}`).expect(200) + ).body; + + const response = await authRequest('put', `${BASE_URL}/${dashboard._id}`) + .send(omit(data, 'id')) + .expect(200); + + expect(response.body.data.filters).toEqual(data.filters); + expect(response.body.data.savedFilterValues).toEqual( + data.savedFilterValues, + ); + }); + + describe('with a source deleted since the filter was saved', () => { + const deleted = new ObjectId().toString(); + const createWithDeletedSource = () => + createTestDashboard({ + filters: [ + { + ...adhocFilter(), + sources: [traceSource._id.toString(), deleted], + }, + ], + }); + + it('accepts a GET response PUT back unchanged', async () => { + const dashboard = await createWithDeletedSource(); + const { data } = ( + await authRequest('get', `${BASE_URL}/${dashboard._id}`).expect(200) + ).body; + + await authRequest('put', `${BASE_URL}/${dashboard._id}`) + .send({ ...omit(data, 'id'), name: 'Renamed' }) + .expect(200); + }); + + it('rejects the source on a filter that did not reference it', async () => { + const dashboard = await createWithDeletedSource(); + const { data } = ( + await authRequest('get', `${BASE_URL}/${dashboard._id}`).expect(200) + ).body; + + const response = await authRequest( + 'put', + `${BASE_URL}/${dashboard._id}`, + ) + .send({ + ...omit(data, 'id'), + filters: [ + ...data.filters, + // A new filter, with a fresh ID, referencing the deleted source. + { + ...adhocFilter(), + name: 'New', + variableName: 'new', + appliesToSourceIds: [deleted], + }, + ], + }) + .expect(400); + + expect(response.body.message).toContain(deleted); + }); }); - it('rejects an ad hoc filter in a POST', async () => { + it.each([ + ['broadcast disabled', { isBroadcastEnabled: false }], + ['variables disabled', { isVariableEnabled: false }], + ['no sources', { sources: [] }], + ['an invalid source ID', { sources: ['not-an-id'] }], + ['an unknown source type', { sourceType: 'lucene' }], + ['a selection limit', { maxSelections: 1 }], + ['the external sourceId field', { sourceId: new ObjectId().toString() }], + ])('rejects an ad hoc filter with %s', async (_label, overrides) => { await authRequest('post', BASE_URL) .send( createMockDashboard(traceSource._id.toString(), { - filters: [omit(adhocFilter(), 'id')], + filters: [omit({ ...adhocFilter(), ...overrides }, 'id')], + }), + ) + .expect(400); + }); + + it.each([ + ['where', { where: 'job:api' }], + ['whereLanguage', { whereLanguage: 'sql' }], + ])('rejects %s on a PromQL ad hoc filter', async (field, overrides) => { + const response = await authRequest('post', BASE_URL) + .send( + createMockDashboard(traceSource._id.toString(), { + filters: [omit({ ...promqlAdhocFilter(), ...overrides }, 'id')], }), ) .expect(400); + + expect(response.body.message).toContain(`sets ${field}`); }); - it('rejects ad hoc saved values in a POST', async () => { + it('drops a stored where from a PromQL ad hoc filter, so GET -> PUT round-trips', async () => { + const dashboard = await createTestDashboard({ + filters: [ + { ...promqlAdhocFilter(), where: 'job:api', whereLanguage: 'lucene' }, + ], + }); + const { data } = ( + await authRequest('get', `${BASE_URL}/${dashboard._id}`).expect(200) + ).body; + expect(data.filters[0]).not.toHaveProperty('where'); + expect(data.filters[0]).not.toHaveProperty('whereLanguage'); + + await authRequest('put', `${BASE_URL}/${dashboard._id}`) + .send(omit(data, 'id')) + .expect(200); + }); + + it('rejects an ad hoc filter over a missing source', async () => { + const missing = new ObjectId().toString(); + const response = await authRequest('post', BASE_URL) + .send( + createMockDashboard(traceSource._id.toString(), { + filters: [omit({ ...adhocFilter(), sources: [missing] }, 'id')], + }), + ) + .expect(400); + + expect(response.body.message).toContain(missing); + }); + + it.each([ + ['a SQL filter over a PromQL source', () => adhocFilter(), 'promql'], + ['a SQL filter over a Metric source', () => adhocFilter(), 'metric'], + ['a PromQL filter over a Trace source', promqlAdhocFilter, 'trace'], + ] as const)('rejects %s', async (_label, makeFilter, kind) => { + const sourceId = { + promql: promqlSource, + metric: metricSource, + trace: traceSource, + }[kind]._id.toString(); + const response = await authRequest('post', BASE_URL) + .send( + createMockDashboard(traceSource._id.toString(), { + filters: [omit({ ...makeFilter(), sources: [sourceId] }, 'id')], + }), + ) + .expect(400); + + expect(response.body.message).toContain(sourceId); + }); + + it('rejects an ad hoc filter applying to a source of the wrong kind', async () => { + const response = await authRequest('post', BASE_URL) + .send( + createMockDashboard(traceSource._id.toString(), { + filters: [ + omit( + { + ...adhocFilter(), + appliesToSourceIds: [promqlSource._id.toString()], + }, + 'id', + ), + ], + }), + ) + .expect(400); + + expect(response.body.message).toContain(promqlSource._id.toString()); + }); + + it('rejects ad hoc saved values with an unknown operator', async () => { await authRequest('post', BASE_URL) .send( createMockDashboard(traceSource._id.toString(), { - savedFilterValues: [adhocValue], + savedFilterValues: [ + { + ...adhocValue, + conditions: [{ key: 'a', operator: '>', value: '1' }], + }, + ], }), ) .expect(400); diff --git a/packages/api/src/routers/external-api/v2/dashboards.ts b/packages/api/src/routers/external-api/v2/dashboards.ts index 3f47a774d3..0b6bacea09 100644 --- a/packages/api/src/routers/external-api/v2/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/dashboards.ts @@ -57,11 +57,12 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * SavedFilterValue: * description: > * A single saved dashboard filter selection. Either a rendered SQL - * condition, or a selection addressed by the name of the dashboard - * variable it belongs to. + * condition, a selection addressed by the name of the dashboard + * variable it belongs to, or the conditions of an ADHOC filter. * oneOf: * - $ref: '#/components/schemas/SqlSavedFilterValue' * - $ref: '#/components/schemas/VariableSavedFilterValue' + * - $ref: '#/components/schemas/AdhocSavedFilterValue' * SqlSavedFilterValue: * type: object * required: [condition] @@ -102,6 +103,55 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * type: string * maxLength: 10000 * example: ["hdx-oss-dev-api"] + * AdhocSavedFilterValue: + * type: object + * required: [type, name, conditions] + * properties: + * type: + * type: string + * enum: [adhoc] + * description: Filter type. + * example: "adhoc" + * name: + * type: string + * minLength: 1 + * maxLength: 1024 + * description: The variableName of the ADHOC filter these conditions belong to. + * example: "conditions" + * conditions: + * type: array + * maxItems: 100 + * description: The filter's conditions. + * items: + * $ref: '#/components/schemas/AdhocFilterCondition' + * AdhocFilterCondition: + * type: object + * description: > + * One "key operator value" condition. Conditions are AND'd, except that + * IN conditions sharing a key are OR'd into one: IN (...) for sql + * filters, a =~"a|b" matcher for promql filters. + * required: [key, operator, value] + * properties: + * key: + * type: string + * minLength: 1 + * maxLength: 10000 + * description: A SQL expression (column or map access) for sql filters, or a label name for promql filters. + * example: "ServiceName" + * operator: + * type: string + * enum: ["=", "!=", "=~", "!~", "LIKE", "NOT LIKE", "IN"] + * description: > + * Comparison operator. =~ and !~ match a regular expression. IN + * takes one value per condition. LIKE and NOT LIKE apply to sql + * filters only; a condition its filter's sourceType can't express + * is not applied. + * example: "=" + * value: + * type: string + * maxLength: 10000 + * description: Value, pattern, or regular expression to compare against. + * example: "api" * MetricDataType: * type: string * enum: [sum, gauge, histogram, summary, exponential histogram] @@ -2369,6 +2419,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * - $ref: '#/components/schemas/StaticListFilterInput' * - $ref: '#/components/schemas/PrometheusLabelFilterInput' * - $ref: '#/components/schemas/SqlQueryFilterInput' + * - $ref: '#/components/schemas/AdhocFilterInput' * discriminator: * propertyName: type * mapping: @@ -2376,6 +2427,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * STATIC_LIST: '#/components/schemas/StaticListFilterInput' * PROMETHEUS_LABEL: '#/components/schemas/PrometheusLabelFilterInput' * SQL_QUERY: '#/components/schemas/SqlQueryFilterInput' + * ADHOC: '#/components/schemas/AdhocFilterInput' * * QueryExpressionFilterInput: * type: object @@ -2763,6 +2815,92 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * description: Set to 1 to make the filter single-select. * example: 1 * + * AdhocFilterInput: + * type: object + * description: | + * A filter holding free-form "key operator value" conditions, with keys + * and values suggested from its sources: columns and map keys for sql + * sources, labels for promql sources. Its conditions are always + * broadcast to the tiles it applies to: as WHERE conditions on builder + * tiles and raw sql tiles using the $__filters macro, or as label + * matchers on PromQL tiles. Its conditions are saved in + * savedFilterValues as an "adhoc" entry. Ad hoc filters are a preview + * feature. + * required: + * - type + * - name + * - sourceType + * - sources + * properties: + * type: + * type: string + * enum: [ADHOC] + * description: Discriminator. Must be "ADHOC". + * example: "ADHOC" + * name: + * type: string + * minLength: 1 + * description: Display name for the dashboard filter + * example: "Conditions" + * sourceType: + * type: string + * enum: [sql, promql] + * description: | + * The kind of sources the filter reads keys from and applies to: Log, + * Trace, or Session sources for sql, PromQL sources for promql. + * example: "sql" + * sources: + * type: array + * minItems: 1 + * items: + * type: string + * description: IDs of the sources whose keys and values the filter suggests, all of sourceType. + * example: ["65f5e4a3b9e77c001a111111"] + * where: + * type: string + * description: | + * Optional condition narrowing the rows keys and values are suggested + * from. Never applied to tiles. May reference the dashboard's + * variables. sql filters only: rejected when sourceType is promql. + * example: "ServiceName:api" + * whereLanguage: + * type: string + * enum: [sql, lucene] + * description: Language of the where condition. Rejected when sourceType is promql. + * example: "lucene" + * appliesToSourceIds: + * type: array + * items: + * type: string + * description: | + * IDs of the sources whose tiles the conditions apply to, all of + * sourceType. Omit or send an empty array to apply to the tiles of + * the filter's sources. + * example: ["65f5e4a3b9e77c001a111111"] + * isBroadcastEnabled: + * type: boolean + * enum: [true] + * default: true + * description: Must be true or omitted. + * example: true + * isVariableEnabled: + * type: boolean + * enum: [true] + * default: true + * description: Must be true or omitted. + * example: true + * variableName: + * type: string + * maxLength: 64 + * pattern: '^[a-zA-Z][a-zA-Z0-9_]*$' + * description: | + * Unique name the filter's conditions are saved under, in + * savedFilterValues and the dashboard URL. Tiles can't reference it + * as a variable. Defaults to the display name with whitespace + * replaced by underscores and remaining illegal characters removed. + * Must be unique across a dashboard's variable-enabled filters. + * example: "conditions" + * * Filter: * allOf: * - $ref: '#/components/schemas/FilterInput' @@ -3682,6 +3820,7 @@ router.put( tiles, filters, existingTiles: existingDashboard.tiles ?? [], + existingFilters: existingDashboard.filters ?? [], containers: effectiveContainers, }); if (validationError) { diff --git a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts index dc8882183e..dec4319981 100644 --- a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts +++ b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts @@ -508,6 +508,43 @@ describe('convertToExternalDashboard orphan-ref heal', () => { expect(hidden.filters?.map(f => f.id)).toEqual(['static-filter']); }); + it('hides ad hoc filters and their saved conditions only when asked', () => { + const adhoc = { + id: 'adhoc-filter', + type: 'ADHOC' as const, + name: 'Conditions', + sourceType: 'sql' as const, + sources: [new mongoose.Types.ObjectId().toString()], + isBroadcastEnabled: true as const, + isVariableEnabled: true as const, + variableName: 'conds', + }; + const variableValue = { + type: 'variable' as const, + name: 'env', + values: ['prod'], + }; + const adhocValue = { + type: 'adhoc' as const, + name: 'conds', + conditions: [ + { key: 'ServiceName', operator: '=' as const, value: 'api' }, + ], + }; + const doc = makeDoc({ + filters: [adhoc], + savedFilterValues: [variableValue, adhocValue], + }); + + const shown = convertToExternalDashboard(doc); + expect(shown.filters).toEqual([adhoc]); + expect(shown.savedFilterValues).toEqual([variableValue, adhocValue]); + + const hidden = convertToExternalDashboard(doc, { hideAdhoc: true }); + expect(hidden.filters).toEqual([]); + expect(hidden.savedFilterValues).toEqual([variableValue]); + }); + // seriesLimit is three-state (matching the internal schema): omitted = // default cap, 0 = unlimited, positive N = top-N. All three must survive a // GET->PUT round-trip: 0 and N pass through, null maps to absent (the diff --git a/packages/api/src/routers/external-api/v2/utils/dashboards.ts b/packages/api/src/routers/external-api/v2/utils/dashboards.ts index 27af9366e4..da0b400a91 100644 --- a/packages/api/src/routers/external-api/v2/utils/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/utils/dashboards.ts @@ -13,7 +13,10 @@ import { validateDashboardFilterVariableNames, validateDashboardTileContainerRefs, } from '@hyperdx/common-utils/dist/dashboardValidation'; -import { isPrometheusLabelFilter } from '@hyperdx/common-utils/dist/filters'; +import { + isPrometheusLabelFilter, + isQueryExpressionFilter, +} from '@hyperdx/common-utils/dist/filters'; import { isBuilderSavedChartConfig, isHeatmapCompatibleSource, @@ -27,12 +30,12 @@ import { DASHBOARD_MAX_CONTAINERS, DashboardContainer, DashboardContainerSchema, + DashboardFilter, DisplayType, HeatmapMode, isLogSource, isOnClickDashboardById, isOnClickSearchById, - isPromqlSource, isTraceSource, NumberTileColorCondition, NumberTileColorConditionSchema, @@ -40,6 +43,7 @@ import { RawSqlSavedChartConfig, resolveChartPaletteToken, SavedChartConfig, + SourceKind, } from '@hyperdx/common-utils/dist/types'; import { SearchConditionLanguageSchema as whereLanguageSchema } from '@hyperdx/common-utils/dist/types'; import { pick } from 'lodash'; @@ -52,12 +56,17 @@ import { getConnectionsByTeam } from '@/controllers/connection'; import { getSources } from '@/controllers/sources'; import Dashboard, { DashboardDocument } from '@/models/dashboard'; import { - getExternalCompatibleFilters, - getExternalCompatibleFilterValues, + getMcpCompatibleFilters, + getMcpCompatibleFilterValues, translateExternalChartToTileConfig, translateExternalFilterToFilter, translateFilterToExternalFilter, } from '@/utils/externalApi'; +import { + getChangedFilterSourceRefs, + getFilterSourceRefError, + getInvalidSourceIds, +} from '@/utils/filterSources'; import logger from '@/utils/logger'; import { ExternalDashboardBuilderTileConfig, @@ -770,10 +779,13 @@ export function convertToExternalDashboard( dashboard: DashboardDocument, { hidePromql = false, + hideAdhoc = false, }: { // MCP hides PromQL tiles and PROMETHEUS_LABEL filters while PromQL is // disabled on the deployment. hidePromql?: boolean; + // MCP doesn't expose ad hoc filters or their saved conditions yet. + hideAdhoc?: boolean; } = {}, ): ExternalDashboard { const containers = dashboard.containers ?? []; @@ -795,14 +807,17 @@ export function convertToExternalDashboard( convertTileToExternalChart(tile, containerById, dashboardId), ), tags: dashboard.tags || [], - filters: getExternalCompatibleFilters(dashboard.filters) + filters: (hideAdhoc + ? getMcpCompatibleFilters(dashboard.filters) + : (dashboard.filters ?? []) + ) .filter(filter => !(hidePromql && isPrometheusLabelFilter(filter))) .map(translateFilterToExternalFilter), savedQuery: dashboard.savedQuery ?? null, savedQueryLanguage: dashboard.savedQueryLanguage ?? null, - savedFilterValues: getExternalCompatibleFilterValues( - dashboard.savedFilterValues, - ), + savedFilterValues: hideAdhoc + ? getMcpCompatibleFilterValues(dashboard.savedFilterValues) + : (dashboard.savedFilterValues ?? []), // Mongoose persists missing arrays as []. Only emit containers when // the user actually saved one or more, so dashboards without the // organization layer round-trip with the field absent. @@ -1304,12 +1319,10 @@ function getMissingSources( } } - if (filters?.length) { - for (const filter of filters) { - if ('sourceId' in filter) { - sourceIds.add(filter.sourceId); - } - } + for (const filter of filters ?? []) { + // PROMETHEUS_LABEL and ADHOC sources are checked with the stored filter's + // references skipped; see `validateDashboardTiles`. + if (isQueryExpressionFilter(filter)) sourceIds.add(filter.sourceId); } const existingSourceIds = new Set( @@ -1350,25 +1363,6 @@ function getHeatmapTilesWithIncompatibleSources( return { distribution: [...distribution], series: [...series] }; } -/** - * Returns an error message string if any of the referenced source IDs is not - * a valid PromQL source, or null if all of them are. `subject` names what - * referenced them, e.g. "PromQL tiles". - */ -function getNonPromqlSourceError( - sources: SourceForValidation[], - referencedSourceIds: string[], - subject: string, -): string | null { - const sourceById = new Map(sources.map(s => [s._id.toString(), s])); - const invalid = [...new Set(referencedSourceIds)].filter(id => { - const source = sourceById.get(id); - return source === undefined || !isPromqlSource(source); - }); - if (invalid.length === 0) return null; - return `${subject} require a PromQL source. The following source IDs are not PromQL sources: ${invalid.join(', ')}`; -} - /** * Returns source IDs referenced by formula tiles that exist but are not * formula-capable. Formulas render on metric and log/trace sources; other @@ -1733,6 +1727,8 @@ export type TileValidationContext = { filters?: (ExternalDashboardFilter | ExternalDashboardFilterWithId)[]; /** Existing internal tiles for scoping heatmap change detection (update paths). */ existingTiles?: DashboardDocument['tiles']; + /** Existing filters, whose source references aren't re-checked (update paths). */ + existingFilters?: DashboardFilter[]; /** Container set to validate tile containerId/tabId refs against. */ containers: DashboardContainer[]; }; @@ -1749,7 +1745,8 @@ export type TileValidationContext = { export async function validateDashboardTiles( ctx: TileValidationContext, ): Promise { - const { teamId, tiles, filters, existingTiles, containers } = ctx; + const { teamId, tiles, filters, existingTiles, existingFilters, containers } = + ctx; // Container/tab ref resolution. const tileRefIssues = collectTileContainerRefIssues(containers, tiles); @@ -1817,22 +1814,33 @@ export async function validateDashboardTiles( return `Tiles with formulas require a Metric, Log, or Trace source. The following source IDs are not formula-capable: ${formulaIncompatibleSources.join(', ')}`; } - // PromQL tiles and PROMETHEUS_LABEL filters query through their source's - // connection and TimeSeries table, which only a PromQL source carries. - const promqlTileError = getNonPromqlSourceError( + // PromQL tiles query through their source's connection and TimeSeries + // table, which only a PromQL source carries. + const nonPromqlTileSourceIds = getInvalidSourceIds( + getChangedPromqlTileSourceIds(tiles, existingTiles).map(id => ({ + id, + kinds: [SourceKind.Promql], + })), sources, - getChangedPromqlTileSourceIds(tiles, existingTiles), - 'PromQL tiles', ); - if (promqlTileError != null) return promqlTileError; + if (nonPromqlTileSourceIds.length > 0) { + return `PromQL tiles require a PromQL source. The following source IDs are not PromQL sources: ${nonPromqlTileSourceIds.join(', ')}`; + } - const promqlLabelFilters = (filters ?? []).filter(isPrometheusLabelFilter); - const promqlLabelFilterError = getNonPromqlSourceError( + // PROMETHEUS_LABEL and ADHOC filters need live sources of the right kind. As + // in the internal API, references the stored filter already made are not + // re-checked, so a since-deleted source doesn't block unrelated saves. + const filterSourceError = getFilterSourceRefError( + getChangedFilterSourceRefs( + // Create bodies carry no filter IDs; an empty one matches no stored filter. + (filters ?? []).map(filter => + translateExternalFilterToFilter({ id: '', ...filter }), + ), + existingFilters, + ), sources, - promqlLabelFilters.map(f => f.sourceId), - 'PROMETHEUS_LABEL filters', ); - if (promqlLabelFilterError != null) return promqlLabelFilterError; + if (filterSourceError != null) return filterSourceError; if (missingOnClickDashboards.length > 0) { return `Could not find the following onClick dashboard IDs: ${missingOnClickDashboards.join(', ')}`; diff --git a/packages/api/src/utils/__tests__/filterSources.test.ts b/packages/api/src/utils/__tests__/filterSources.test.ts new file mode 100644 index 0000000000..10d8d2a4b4 --- /dev/null +++ b/packages/api/src/utils/__tests__/filterSources.test.ts @@ -0,0 +1,108 @@ +import { DashboardFilter, SourceKind } from '@hyperdx/common-utils/dist/types'; + +import { + getChangedFilterSourceRefs, + getFilterSourceRefError, +} from '@/utils/filterSources'; + +const adhoc = ( + overrides: Partial> = {}, +): DashboardFilter => ({ + id: 'a1', + type: 'ADHOC', + name: 'Conditions', + sourceType: 'sql', + sources: ['logs'], + isBroadcastEnabled: true, + isVariableEnabled: true, + ...overrides, +}); + +const label: DashboardFilter = { + id: 'l1', + type: 'PROMETHEUS_LABEL', + name: 'Job', + source: 'prom', + label: 'job', + isBroadcastEnabled: false, + isVariableEnabled: true, +}; + +const sql = [SourceKind.Log, SourceKind.Trace, SourceKind.Session]; + +describe('getChangedFilterSourceRefs', () => { + it('returns every reference without stored filters', () => { + expect( + getChangedFilterSourceRefs([ + adhoc({ appliesToSourceIds: ['traces'] }), + label, + ]), + ).toEqual([ + { id: 'logs', kinds: sql }, + { id: 'traces', kinds: sql }, + { id: 'prom', kinds: [SourceKind.Promql] }, + ]); + }); + + it('skips references the stored filter with the same ID already made', () => { + expect( + getChangedFilterSourceRefs( + [adhoc({ sources: ['logs', 'traces'] }), label], + [adhoc(), label], + ), + ).toEqual([{ id: 'traces', kinds: sql }]); + }); + + it('re-checks a reference whose required kinds changed', () => { + expect( + getChangedFilterSourceRefs([adhoc({ sourceType: 'promql' })], [adhoc()]), + ).toEqual([{ id: 'logs', kinds: [SourceKind.Promql] }]); + }); + + it('checks a filter without an ID, or with a new one', () => { + const { id: _id, ...withoutId } = adhoc(); + expect( + getChangedFilterSourceRefs( + [withoutId as DashboardFilter, adhoc({ id: 'new' })], + [adhoc()], + ), + ).toEqual([ + { id: 'logs', kinds: sql }, + { id: 'logs', kinds: sql }, + ]); + }); +}); + +describe('getFilterSourceRefError', () => { + const sources = [ + { _id: 'logs', kind: SourceKind.Log }, + { _id: 'prom', kind: SourceKind.Promql }, + ]; + + it('accepts references to existing sources of the right kind', () => { + expect( + getFilterSourceRefError( + [ + { id: 'logs', kinds: sql }, + { id: 'prom', kinds: [SourceKind.Promql] }, + ], + sources, + ), + ).toBeNull(); + }); + + it('names missing sources and sources of the wrong kind once each', () => { + expect( + getFilterSourceRefError( + [ + { id: 'prom', kinds: sql }, + { id: 'gone', kinds: sql }, + { id: 'gone', kinds: sql }, + ], + sources, + ), + ).toBe( + 'The following filter source IDs do not exist or are not a kind of source the filter supports: prom, gone', + ); + }); +}); diff --git a/packages/api/src/utils/externalApi.ts b/packages/api/src/utils/externalApi.ts index 4422bcf908..789055c2c0 100644 --- a/packages/api/src/utils/externalApi.ts +++ b/packages/api/src/utils/externalApi.ts @@ -240,32 +240,22 @@ export function translateExternalChartToTileConfig( }; } -/** Filter types the external API and MCP don't expose yet. */ -type InternalOnlyDashboardFilter = Extract; -export type ExternalCompatibleDashboardFilter = Exclude< - DashboardFilter, - InternalOnlyDashboardFilter ->; - -/** The filters the external API and MCP may read. */ -export function getExternalCompatibleFilters( +/** The filters MCP may read; it doesn't expose ad hoc filters yet. */ +export function getMcpCompatibleFilters( filters: DashboardFilter[] | undefined, -): ExternalCompatibleDashboardFilter[] { - return (filters ?? []).filter( - (filter): filter is ExternalCompatibleDashboardFilter => - !isAdhocFilter(filter), - ); +): DashboardFilter[] { + return (filters ?? []).filter(filter => !isAdhocFilter(filter)); } -/** Saved filter values the external API and MCP may read. */ -export function getExternalCompatibleFilterValues( +/** Saved filter values MCP may read; it doesn't expose ad hoc filters yet. */ +export function getMcpCompatibleFilterValues( values: IDashboard['savedFilterValues'], ): NonNullable { return (values ?? []).filter(value => !isAdhocFilterValue(value)); } export function translateFilterToExternalFilter( - filter: ExternalCompatibleDashboardFilter, + filter: DashboardFilter, ): ExternalDashboardFilterWithId { // Omitted from responses unless the filter is required, so a GET response // can be PUT back verbatim. @@ -277,6 +267,12 @@ export function translateFilterToExternalFilter( case 'STATIC_LIST': return omit(filter, ...omittedKeys); + case 'ADHOC': + // Only sql filters read `where`; the internal API may have stored one. + return filter.sourceType === 'promql' + ? omit(filter, 'where', 'whereLanguage') + : filter; + case 'PROMETHEUS_LABEL': return { ...omit(filter, 'source', ...omittedKeys), @@ -315,6 +311,7 @@ export function translateExternalFilterToFilter( ): DashboardFilter { switch (filter.type) { case 'STATIC_LIST': + case 'ADHOC': return filter; case 'PROMETHEUS_LABEL': diff --git a/packages/api/src/utils/filterSources.ts b/packages/api/src/utils/filterSources.ts new file mode 100644 index 0000000000..2cc2df23fa --- /dev/null +++ b/packages/api/src/utils/filterSources.ts @@ -0,0 +1,80 @@ +import { + getAdhocFilterSourceKinds, + isAdhocFilter, + isPrometheusLabelFilter, +} from '@hyperdx/common-utils/dist/filters'; +import { DashboardFilter, SourceKind } from '@hyperdx/common-utils/dist/types'; + +/** A filter as stored or as sent on create, when it has no ID yet. */ +type FilterWithOptionalId = T extends unknown + ? Omit & { id?: string } + : never; + +/** A source a reference points at, and the kinds it must be. */ +export type SourceRef = { id: string; kinds: SourceKind[] }; + +/** The sources a filter reads from, each with the kinds it must be. */ +function getFilterSourceRefs(filter: FilterWithOptionalId): SourceRef[] { + if (isPrometheusLabelFilter(filter)) { + return [{ id: filter.source, kinds: [SourceKind.Promql] }]; + } + if (isAdhocFilter(filter)) { + const kinds = getAdhocFilterSourceKinds(filter.sourceType); + return [...filter.sources, ...(filter.appliesToSourceIds ?? [])].map( + id => ({ id, kinds }), + ); + } + return []; +} + +/** + * The source references in `filters` that the stored filter with the same ID + * didn't already make, so a since-deleted source doesn't block unrelated saves. + */ +export function getChangedFilterSourceRefs( + filters: FilterWithOptionalId[] = [], + existingFilters: DashboardFilter[] = [], +): SourceRef[] { + const refKey = ({ id, kinds }: SourceRef) => `${id}:${kinds.join(',')}`; + const existingRefsById = new Map( + existingFilters.map(filter => [ + filter.id, + new Set(getFilterSourceRefs(filter).map(refKey)), + ]), + ); + return filters.flatMap(filter => + getFilterSourceRefs(filter).filter( + ref => + filter.id === undefined || + !existingRefsById.get(filter.id)?.has(refKey(ref)), + ), + ); +} + +/** The referenced source IDs that are missing or of the wrong kind, once each. */ +export function getInvalidSourceIds( + refs: SourceRef[], + sources: { _id: { toString(): string }; kind: SourceKind }[], +): string[] { + const kindById = new Map(sources.map(s => [s._id.toString(), s.kind])); + const invalid = refs + .filter(({ id, kinds }) => { + const kind = kindById.get(id); + return kind === undefined || !kinds.includes(kind); + }) + .map(({ id }) => id); + return [...new Set(invalid)]; +} + +/** + * An error naming the referenced sources that are missing or of the wrong + * kind, or null when there are none. + */ +export function getFilterSourceRefError( + refs: SourceRef[], + sources: Parameters[1], +): string | null { + const invalid = getInvalidSourceIds(refs, sources); + if (invalid.length === 0) return null; + return `The following filter source IDs do not exist or are not a kind of source the filter supports: ${invalid.join(', ')}`; +} diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index ff46115eee..a53e083d96 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -1,6 +1,8 @@ import { validateChartConfigFormulas } from '@hyperdx/common-utils/dist/dashboardValidation'; import { addDuplicateTileIdIssues, + AdhocDashboardFilterSchema, + AdhocFilterValueSchema, AggregateFunctionSchema, AlertChartConfigSchema, alertDisplayNameSchema, @@ -200,6 +202,14 @@ const externalSqlQueryFilterShape = SqlQueryDashboardFilterSchema.omit({ isVariableEnabled: z.literal(true).default(true), }); +// Field names match the stored filter, so it needs no translation. +const externalAdhocFilterShape = AdhocDashboardFilterSchema.extend({ + sources: z.array(objectIdSchema).min(1), + appliesToSourceIds: z.array(objectIdSchema).optional(), + isBroadcastEnabled: z.literal(true).default(true), + isVariableEnabled: z.literal(true).default(true), +}); + export const externalDashboardFilterSchemaWithId = z.discriminatedUnion( 'type', [ @@ -207,6 +217,7 @@ export const externalDashboardFilterSchemaWithId = z.discriminatedUnion( externalStaticListFilterShape.strict(), externalPromqlLabelFilterShape.strict(), externalSqlQueryFilterShape.strict(), + externalAdhocFilterShape.strict(), ], ); @@ -224,6 +235,7 @@ export const externalDashboardFilterSchema = z.discriminatedUnion('type', [ externalStaticListFilterShape.omit({ id: true }).strict(), externalPromqlLabelFilterShape.omit({ id: true }).strict(), externalSqlQueryFilterShape.omit({ id: true }).strict(), + externalAdhocFilterShape.omit({ id: true }).strict(), ]); export type ExternalDashboardFilter = z.infer< @@ -231,8 +243,9 @@ export type ExternalDashboardFilter = z.infer< >; /** - * One entry in a dashboard's `savedFilterValues`: either a rendered SQL - * predicate, or a selection addressed by the dashboard variable it belongs to. + * One entry in a dashboard's `savedFilterValues`: a rendered SQL predicate, a + * selection addressed by the dashboard variable it belongs to, or an ad hoc + * filter's conditions addressed by its variable name. */ export const externalSqlSavedFilterValueSchema = z.object({ type: z.literal('sql').optional().default('sql'), @@ -245,6 +258,7 @@ export const externalVariableSavedFilterValueSchema = export const externalDashboardSavedFilterValueSchema = z.union([ externalSqlSavedFilterValueSchema, externalVariableSavedFilterValueSchema, + AdhocFilterValueSchema.strict(), ]); // ================================ diff --git a/packages/common-utils/src/__tests__/dashboardValidation.test.ts b/packages/common-utils/src/__tests__/dashboardValidation.test.ts index ad823b40be..fc36b51057 100644 --- a/packages/common-utils/src/__tests__/dashboardValidation.test.ts +++ b/packages/common-utils/src/__tests__/dashboardValidation.test.ts @@ -284,6 +284,10 @@ describe('validateDashboardFilterModes', () => { type GatingFilter = ModeFilter & { variableName?: string; appliesToSourceIds?: string[]; + type?: string; + sourceType?: string; + where?: string; + whereLanguage?: string; }; const collectGatingIssues = ( @@ -304,6 +308,26 @@ describe('validateDashboardFilterFieldGating', () => { expect(collectGatingIssues([])).toEqual([]); }); + it('rejects where and whereLanguage on a PromQL ad hoc filter only', () => { + const adhoc = (sourceType: string) => ({ + name: sourceType, + type: 'ADHOC', + sourceType, + isBroadcastEnabled: true, + where: 'Namespace:api', + whereLanguage: 'lucene', + }); + const issues = collectGatingIssues([adhoc('sql'), adhoc('promql')]); + + expect(issues.map(issue => issue.path)).toEqual([ + ['filters', 1, 'where'], + ['filters', 1, 'whereLanguage'], + ]); + expect(issues[0].message).toBe( + 'Filter "promql" sets where, which only ad hoc filters with sourceType "sql" use; drop where', + ); + }); + it('accepts a filter that carries neither field', () => { expect(collectGatingIssues([{ name: 'Service' }])).toEqual([]); }); diff --git a/packages/common-utils/src/dashboardValidation.ts b/packages/common-utils/src/dashboardValidation.ts index 8a88bf999e..57faefa10f 100644 --- a/packages/common-utils/src/dashboardValidation.ts +++ b/packages/common-utils/src/dashboardValidation.ts @@ -30,6 +30,10 @@ type FilterForModeValidation = { type FilterForGatingValidation = FilterForModeValidation & { variableName?: string; appliesToSourceIds?: string[]; + type?: string; + sourceType?: string; + where?: string; + whereLanguage?: string; }; /** @@ -238,6 +242,8 @@ export function validateDashboardFilterModes( * Issues raised: * - `variableName` on a filter that is not variable-enabled (path `[i].variableName`). * - A non-empty `appliesToSourceIds` on a filter that does not broadcast (path `[i].appliesToSourceIds`). + * - `where` or `whereLanguage` on a PromQL ad hoc filter, which only SQL ad hoc + * filters read (path `[i].where` / `.whereLanguage`). */ export function validateDashboardFilterFieldGating< T extends FilterForGatingValidation, @@ -268,6 +274,21 @@ export function validateDashboardFilterFieldGating< path: [...filtersPath, filterIdx, 'appliesToSourceIds'], }); } + + if (filter.type === 'ADHOC' && filter.sourceType === 'promql') { + const fields = [ + ['where', filter.where], + ['whereLanguage', filter.whereLanguage], + ] as const; + for (const [field, value] of fields) { + if (value === undefined) continue; + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `Filter "${filter.name}" sets ${field}, which only ad hoc filters with sourceType "sql" use; drop ${field}`, + path: [...filtersPath, filterIdx, field], + }); + } + } }); } From b681cec85c53143c045e1a2599f2caed0711234e Mon Sep 17 00:00:00 2001 From: Aaron Knudtson <87577305+knudtty@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:49:56 -0500 Subject: [PATCH 26/55] feat(mcp): support ad hoc dashboard filters in the MCP dashboard tools (#3660) --- .changeset/adhoc-filters-mcp.md | 12 ++ .../dashboards/promqlTiles.int.test.ts | 147 ++++++++++++++++++ .../dashboards/saveDashboard.int.test.ts | 105 +++++++++++++ .../api/src/mcp/prompts/dashboards/content.ts | 20 ++- .../mcp/prompts/dashboards/promqlContent.ts | 1 + .../src/mcp/tools/dashboards/getDashboard.ts | 1 - .../mcp/tools/dashboards/getDashboardTile.ts | 1 - .../mcp/tools/dashboards/patchDashboard.ts | 9 +- .../api/src/mcp/tools/dashboards/queryTile.ts | 1 - .../src/mcp/tools/dashboards/queryTiles.ts | 1 - .../src/mcp/tools/dashboards/saveDashboard.ts | 14 +- .../api/src/mcp/tools/dashboards/schemas.ts | 146 ++++++++++++++++- .../src/mcp/tools/dashboards/validation.ts | 50 +++++- .../v2/utils/__tests__/dashboards.test.ts | 36 ++--- .../external-api/v2/utils/dashboards.ts | 29 ++-- packages/api/src/utils/externalApi.ts | 16 -- packages/api/src/utils/zod.ts | 5 +- 17 files changed, 508 insertions(+), 86 deletions(-) create mode 100644 .changeset/adhoc-filters-mcp.md diff --git a/.changeset/adhoc-filters-mcp.md b/.changeset/adhoc-filters-mcp.md new file mode 100644 index 0000000000..ef20b14cb6 --- /dev/null +++ b/.changeset/adhoc-filters-mcp.md @@ -0,0 +1,12 @@ +--- +'@hyperdx/api': minor +--- + +feat(mcp): Create, read, and update ad hoc dashboard filters through the MCP dashboard tools + +`clickstack_save_dashboard`, `clickstack_get_dashboard`, and +`clickstack_patch_dashboard` now handle `ADHOC` filters and their `adhoc` +saved conditions. PromQL ad hoc filters are offered only while PromQL is +enabled, and are hidden and kept on update otherwise. Saved conditions that +name no ad hoc filter, or use an operator their filter can't apply, produce a +warning. diff --git a/packages/api/src/mcp/__tests__/dashboards/promqlTiles.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/promqlTiles.int.test.ts index 55f7c7e5ad..61250c8c09 100644 --- a/packages/api/src/mcp/__tests__/dashboards/promqlTiles.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/promqlTiles.int.test.ts @@ -63,6 +63,19 @@ describe('MCP Dashboard Tools - PromQL tiles and label filters', () => { isVariableEnabled: true as const, }); + const storedAdhocFilter = (sourceType: 'sql' | 'promql') => ({ + id: `${sourceType}-adhoc`, + type: 'ADHOC' as const, + name: `${sourceType} conditions`, + sourceType, + sources: [ + sourceType === 'promql' ? promqlSourceId : ctx.traceSource._id.toString(), + ], + isBroadcastEnabled: true as const, + isVariableEnabled: true as const, + variableName: `${sourceType}_conditions`, + }); + const createStoredDashboard = () => new Dashboard({ name: 'PromQL dashboard', @@ -71,6 +84,14 @@ describe('MCP Dashboard Tools - PromQL tiles and label filters', () => { team: ctx.team._id, }).save(); + const createStoredAdhocDashboard = () => + new Dashboard({ + name: 'Ad hoc dashboard', + tiles: [], + filters: [storedAdhocFilter('sql'), storedAdhocFilter('promql')], + team: ctx.team._id, + }).save(); + const parseOutput = (result: Awaited>) => JSON.parse(getFirstText(result)); @@ -242,6 +263,85 @@ describe('MCP Dashboard Tools - PromQL tiles and label filters', () => { expect(parseOutput(saved).filters).toEqual(filters); }); + it('round-trips a PromQL ad hoc filter', async () => { + const { sources, sourceType, name, variableName } = + storedAdhocFilter('promql'); + const created = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Ad hoc', + tiles: [], + filters: [{ type: 'ADHOC', name, sourceType, sources, variableName }], + savedFilterValues: [ + { + type: 'adhoc', + name: variableName, + conditions: [{ key: 'job', operator: 'IN', value: 'api' }], + }, + ], + }); + expect(created.isError).toBeFalsy(); + const { id, filters, warnings } = parseOutput(created); + expect(warnings ?? []).toEqual([]); + expect(filters).toEqual([ + { ...storedAdhocFilter('promql'), id: expect.any(String) }, + ]); + + const saved = await callTool(ctx.client!, 'clickstack_save_dashboard', { + id, + name: 'Ad hoc', + tiles: [], + filters, + }); + expect(saved.isError).toBeFalsy(); + expect(parseOutput(saved).filters).toEqual(filters); + }); + + it('warns about saved conditions a PromQL filter cannot apply', async () => { + const { sources, sourceType, name, variableName } = + storedAdhocFilter('promql'); + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Ad hoc', + tiles: [], + filters: [{ type: 'ADHOC', name, sourceType, sources, variableName }], + savedFilterValues: [ + { + type: 'adhoc', + name: variableName, + conditions: [{ key: 'job', operator: 'LIKE', value: '%api%' }], + }, + ], + }); + + expect(result.isError).toBeFalsy(); + expect(parseOutput(result).warnings).toEqual([ + expect.stringContaining('using LIKE'), + ]); + }); + + it.each([ + ['a sql filter over a promql source', 'sql', () => promqlSourceId], + [ + 'a promql filter over a trace source', + 'promql', + () => ctx.traceSource._id.toString(), + ], + ] as const)('rejects %s', async (_label, sourceType, sourceId) => { + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Wrong kind', + tiles: [], + filters: [ + { + type: 'ADHOC', + name: 'Conditions', + sourceType, + sources: [sourceId()], + }, + ], + }); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain(sourceId()); + }); + it('rejects a PromQL tile on a source that is not a promql source', async () => { const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { name: 'Wrong source', @@ -415,6 +515,53 @@ describe('MCP Dashboard Tools - PromQL tiles and label filters', () => { expect(stored?.tiles).toHaveLength(2); }); + it('hides PromQL ad hoc filters from clickstack_get_dashboard', async () => { + const dashboard = await createStoredAdhocDashboard(); + + const result = await callTool(ctx.client!, 'clickstack_get_dashboard', { + id: dashboard._id.toString(), + }); + + expect(result.isError).toBeFalsy(); + expect(parseOutput(result).filters).toEqual([storedAdhocFilter('sql')]); + }); + + it('keeps hidden PromQL ad hoc filters when clickstack_save_dashboard updates the dashboard', async () => { + const dashboard = await createStoredAdhocDashboard(); + + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + id: dashboard._id.toString(), + name: 'Ad hoc dashboard', + tiles: [], + filters: [{ ...storedAdhocFilter('sql'), name: 'Renamed' }], + }); + + expect(result.isError).toBeFalsy(); + const stored = await Dashboard.findById(dashboard._id).lean(); + expect(stored?.filters).toEqual([ + { ...storedAdhocFilter('sql'), name: 'Renamed' }, + storedAdhocFilter('promql'), + ]); + }); + + it('rejects a PromQL ad hoc filter', async () => { + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'PromQL off', + tiles: [], + filters: [ + { + type: 'ADHOC', + name: 'Labels', + sourceType: 'promql', + sources: [promqlSourceId], + }, + ], + }); + + expect(result.isError).toBe(true); + expect(await Dashboard.countDocuments({ team: ctx.team._id })).toBe(0); + }); + it('rejects a PromQL tile', async () => { const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { name: 'PromQL off', diff --git a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts index 4940948fd0..9624eca73e 100644 --- a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts @@ -4027,4 +4027,109 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { expect(getFirstText(patchResult)).toContain('savedFilterValues'); }); }); + + describe('ad hoc filters', () => { + const adhocFilter = () => ({ + type: 'ADHOC' as const, + name: 'Conditions', + sourceType: 'sql' as const, + sources: [ctx.traceSource._id.toString()], + variableName: 'conditions', + }); + const adhocValue = { + type: 'adhoc' as const, + name: 'conditions', + conditions: [ + { key: 'ServiceName', operator: 'IN' as const, value: 'api' }, + { key: 'ServiceName', operator: 'IN' as const, value: 'web' }, + ], + }; + const parse = (result: Awaited>) => + JSON.parse(getFirstText(result)); + + it('round-trips an ad hoc filter and its saved conditions through save, get and save', async () => { + const created = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Ad hoc', + tiles: [], + filters: [adhocFilter()], + savedFilterValues: [adhocValue], + }); + expect(created.isError).toBeFalsy(); + const { id, warnings } = parse(created); + expect(warnings ?? []).toEqual([]); + + const read = parse( + await callTool(ctx.client!, 'clickstack_get_dashboard', { id }), + ); + expect(read.filters).toEqual([ + { + ...adhocFilter(), + id: expect.any(String), + isBroadcastEnabled: true, + isVariableEnabled: true, + }, + ]); + expect(read.savedFilterValues).toEqual([adhocValue]); + + const storedBefore = await Dashboard.findById(id).lean(); + const saved = await callTool(ctx.client!, 'clickstack_save_dashboard', { + id, + name: 'Ad hoc', + tiles: [], + filters: read.filters, + savedFilterValues: read.savedFilterValues, + }); + expect(saved.isError).toBeFalsy(); + const storedAfter = await Dashboard.findById(id).lean(); + expect(storedAfter?.filters).toEqual(storedBefore?.filters); + expect(storedAfter?.savedFilterValues).toEqual([adhocValue]); + }); + + it('saves back a filter whose source was deleted since it was stored', async () => { + const dashboard = await new Dashboard({ + name: 'Deleted source', + tiles: [], + team: ctx.team._id, + filters: [ + { + ...adhocFilter(), + id: 'adhoc-1', + sources: [ + ctx.traceSource._id.toString(), + '65f5e4a3b9e77c001a999999', + ], + isBroadcastEnabled: true, + isVariableEnabled: true, + }, + ], + }).save(); + const id = dashboard._id.toString(); + const read = parse( + await callTool(ctx.client!, 'clickstack_get_dashboard', { id }), + ); + + const saved = await callTool(ctx.client!, 'clickstack_save_dashboard', { + id, + name: 'Renamed', + tiles: [], + filters: read.filters, + }); + + expect(saved.isError).toBeFalsy(); + }); + + it('warns about saved conditions that no ad hoc filter matches', async () => { + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Bad defaults', + tiles: [], + filters: [adhocFilter()], + savedFilterValues: [{ ...adhocValue, name: 'conditons' }], + }); + + expect(result.isError).toBeFalsy(); + expect(parse(result).warnings).toEqual([ + expect.stringContaining('"conditons"'), + ]); + }); + }); }); diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index 74e2d4e030..bbfb7167de 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -135,6 +135,8 @@ Apply these before calling clickstack_save_dashboard. Each rule is enforced by t 9g. SET savedFilterValues TO GIVE THE DASHBOARD A DEFAULT SELECTION. Pass savedFilterValues on clickstack_save_dashboard or clickstack_patch_dashboard to pre-select filter values whenever the dashboard opens. Pair this with a required filter (9e) so the dashboard opens scoped rather than blocked. +9h. USE AN ADHOC FILTER TO LET THE USER BUILD FREE-FORM CONDITIONS. filters: [{ type: "ADHOC", name, sourceType: "sql", sources: [""], variableName? }] adds an input where the user picks any column or map key, an operator, and a value; clicking a value in a tile adds a condition too. Every condition is ANDed onto the tiles of its sources (or of appliesToSourceIds) with no per-tile wiring. It is never a variable: its variableName only names the entry its conditions are saved under. Seed conditions with savedFilterValues: [{ type: "adhoc", name: "", conditions: [{ key: "ServiceName", operator: "IN", value: "api" }] }]; IN conditions on the same key are ORed. Declare at most one ad hoc filter per source, since a click updates every ad hoc filter on the clicked tile's source. + 10. UPDATE IS REPLACE, NOT MERGE. clickstack_save_dashboard with an id overwrites tiles, containers, and filters in their entirety. Call clickstack_get_dashboard first when you only want to add or rename one entry; do not send a partial set or you will silently drop everything you omitted. 11. GROUP RELATED TILES INTO CONTAINERS. REQUIRED at five or more tiles, no exceptions. An ungrouped wall of nine or ten tiles is a readability failure even when each tile is correct in isolation. Containers are the right way to introduce structure; markdown tiles for section labels are not. @@ -196,7 +198,8 @@ Dashboards open with a 15-minute default window. There is no dashboard-level fie - Using $__filter or $__conditionalAll in a Lucene where (they are matched as literal text; switch to whereLanguage: "sql", or write ServiceName:$var). - Chaining a filter's where off a filter that is not variable-enabled. Only isVariableEnabled: true publishes the $variableName token; without it the reference resolves to nothing and the downstream dropdown is unscoped or empty. - Referencing a filter's OWN variable in its where. That narrows its dropdown to the values already picked, so the rest of the options vanish from a multi-select. Reference a sibling filter's variable instead. -- Mixing filter-type fields: expression/sourceId/where belong to QUERY_EXPRESSION filters, options to STATIC_LIST filters, connectionId/sqlTemplate to SQL_QUERY filters. +- Mixing filter-type fields: expression/sourceId/where belong to QUERY_EXPRESSION filters, options to STATIC_LIST filters, connectionId/sqlTemplate to SQL_QUERY filters, sourceType/sources to ADHOC filters. +- Referencing an ADHOC filter's variableName in a tile. Ad hoc conditions reach tiles only by broadcast; the name is not a variable. - Expecting a STATIC_LIST filter to broadcast. It cannot; a tile must reference its $variableName (via $__filter with the column passed explicitly) or nothing changes when the user picks a value.`; } @@ -1168,7 +1171,7 @@ Rules: Optional dashboard-level filter declarations. Each entry adds a dropdown to the dashboard header. Use this for focused per-dimension dashboards (per-service, per-tenant, per-endpoint) instead of hardcoding the dimension into every tile's where clause. -Filter types: QUERY_EXPRESSION queries its dropdown values from a source column. STATIC_LIST declares them inline as a hand-authored options list, and SQL_QUERY reads them from a ClickHouse query; both are always variable-only (see their shapes below). +Filter types: QUERY_EXPRESSION queries its dropdown values from a source column. STATIC_LIST declares them inline as a hand-authored options list, and SQL_QUERY reads them from a ClickHouse query; both are always variable-only (see their shapes below). ADHOC holds free-form conditions the user builds, and always broadcasts them (see the ad hoc filter shape below). A QUERY_EXPRESSION filter does one of two things with the value the user picks, or both: @@ -1220,6 +1223,19 @@ Example (SQL query, narrowed by another filter's variable): { type: "SQL_QUERY", name: "Environment", connectionId: "", sqlTemplate: "SELECT DISTINCT env FROM default.envs WHERE $__filter(cloud, $cloud) ORDER BY env", variableName: "env" } ] +Ad hoc filter shape: + { type: "ADHOC", name, sourceType, sources, where?, whereLanguage?, appliesToSourceIds?, variableName? } + + sourceType "sql": keys are the columns and map keys of Log, Trace, or Session sources. + sources IDs of the sources whose keys and values the input suggests, all of sourceType. + where Optional condition narrowing the rows keys and values are suggested from. sql only, never applied to a tile. + appliesToSourceIds Optional IDs of the sources whose tiles the conditions apply to. Omit to use the filter's sources. + variableName The name its conditions are saved under in savedFilterValues. NOT a variable: tiles cannot reference it. + + No mode flags or selection limits: an ad hoc filter always broadcasts and is never a variable. The user adds conditions in the filter bar or by clicking values in tiles; seed them with an "adhoc" savedFilterValues entry: + savedFilterValues: [{ type: "adhoc", name: "conditions", conditions: [{ key: "SeverityText", operator: "=", value: "error" }] }] + Operators: =, !=, =~ (regex), !~, LIKE, NOT LIKE, and IN. Conditions are ANDed, except that IN conditions on the same key are ORed into one IN (...). + Example (broadcast to every tile, the common case): filters: [ { type: "QUERY_EXPRESSION", name: "Service", expression: "ServiceName", sourceId: "" } diff --git a/packages/api/src/mcp/prompts/dashboards/promqlContent.ts b/packages/api/src/mcp/prompts/dashboards/promqlContent.ts index 88d4cb813b..5b3b016a57 100644 --- a/packages/api/src/mcp/prompts/dashboards/promqlContent.ts +++ b/packages/api/src/mcp/prompts/dashboards/promqlContent.ts @@ -49,5 +49,6 @@ Sources with kind "promql" hold Prometheus metrics. Chart them with PROMQL tiles - displayType works as for builder tiles. line, stacked_bar and stacked_line plot every expression; number, table, pie and bar query only the first and can set queryType "instant" to evaluate once at the end of the range. - legendTemplate names each series from its labels, e.g. "{{job}} / {{instance}}". - Filter with a PROMETHEUS_LABEL dashboard filter: { "type": "PROMETHEUS_LABEL", "name": "Job", "sourceId": "", "label": "job", "variableName": "job" }. Tiles reference it in a matcher: {job=~"$job"} (multi-select) or {job="$job"} with maxSelections: 1. clickstack_describe_source lists the label names. + - For free-form label conditions, use an ADHOC filter with sourceType "promql": { "type": "ADHOC", "name": "Labels", "sourceType": "promql", "sources": [""] }. Its conditions are added as label matchers to every selector in the PromQL tiles on those sources, with no tile wiring. Operators: =, !=, =~, !~, and IN (shown as =| in the filter bar); IN conditions on the same label are ORed into one =~"a|b" matcher. Seed them via savedFilterValues as for sql ad hoc filters. - Draft each expression with clickstack_promql first, then validate the saved tile with clickstack_query_tile. PromQL tiles cannot have alerts. - Fetch the query_guide prompt for the PromQL syntax notes (rate(), histogram_quantile, the $__rate_interval macro).`; diff --git a/packages/api/src/mcp/tools/dashboards/getDashboard.ts b/packages/api/src/mcp/tools/dashboards/getDashboard.ts index 2133ec09b3..a18f09952b 100644 --- a/packages/api/src/mcp/tools/dashboards/getDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/getDashboard.ts @@ -63,7 +63,6 @@ export function registerGetDashboard({ } const externalDashboard = convertToExternalDashboard(dashboard, { hidePromql: !isPromqlEnabled(context), - hideAdhoc: true, }); return { content: [ diff --git a/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts b/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts index 7d331d965c..f9a4d2632f 100644 --- a/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts +++ b/packages/api/src/mcp/tools/dashboards/getDashboardTile.ts @@ -51,7 +51,6 @@ export function registerGetDashboardTile({ const externalDashboard = convertToExternalDashboard(dashboard, { hidePromql: !isPromqlEnabled(context), - hideAdhoc: true, }); const tile = externalDashboard.tiles.find(t => t.id === tileId); if (!tile) { diff --git a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts index 4488ca1c7b..36d5f43a21 100644 --- a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts @@ -15,7 +15,6 @@ import { isConfigTile, validateDashboardTiles, } from '@/routers/external-api/v2/utils/dashboards'; -import { getMcpCompatibleFilterValues } from '@/utils/externalApi'; import type { ExternalDashboardTileWithId } from '@/utils/zod'; import { externalDashboardTileSchemaWithId } from '@/utils/zod'; @@ -127,7 +126,7 @@ export function registerPatchDashboard({ // Convert only for the error message (read-only, no write-back). const externalDashboard = convertToExternalDashboard( existingDashboard, - { hidePromql: !promqlEnabled, hideAdhoc: true }, + { hidePromql: !promqlEnabled }, ); return mcpUserError( `Tile not found: ${tileId}. Available tile IDs: ${externalDashboard.tiles.map(t => `${t.id} (${t.name})`).join(', ')}`, @@ -270,11 +269,7 @@ export function registerPatchDashboard({ name: updatedDashboard.name, tags: updatedDashboard.tags, ...(savedFilterValues !== undefined - ? { - savedFilterValues: getMcpCompatibleFilterValues( - updatedDashboard.savedFilterValues, - ), - } + ? { savedFilterValues: updatedDashboard.savedFilterValues ?? [] } : {}), ...(frontendUrl ? { url: `${frontendUrl}/dashboards/${updatedDashboard._id}` } diff --git a/packages/api/src/mcp/tools/dashboards/queryTile.ts b/packages/api/src/mcp/tools/dashboards/queryTile.ts index 0f9df6b116..b6cd385b57 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTile.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTile.ts @@ -78,7 +78,6 @@ export function registerQueryTile({ const externalDashboard = convertToExternalDashboard(dashboard, { hidePromql: !isPromqlEnabled(context), - hideAdhoc: true, }); const tile = externalDashboard.tiles.find(t => t.id === tileId); if (!tile) { diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index 9860ad768c..44af35c950 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -184,7 +184,6 @@ export function registerQueryTiles({ const externalDashboard = convertToExternalDashboard(dashboard, { hidePromql: !isPromqlEnabled(context), - hideAdhoc: true, }); const allTiles = externalDashboard.tiles; diff --git a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts index bde01373e8..58adbb0738 100644 --- a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts @@ -1,7 +1,6 @@ import { getFilterVariableName, isFilterVariableEnabled, - isPrometheusLabelFilter, } from '@hyperdx/common-utils/dist/filters'; import { isPromqlSavedChartConfig } from '@hyperdx/common-utils/dist/guards'; import type { DashboardContainer } from '@hyperdx/common-utils/dist/types'; @@ -22,6 +21,7 @@ import { convertExternalTilesToInternal, convertToExternalDashboard, createDashboardBodySchema, + isPromqlFilter, resolveSavedQueryLanguage, updateDashboardBodySchema, validateDashboardTiles, @@ -236,7 +236,6 @@ async function createDashboard({ const externalDashboard = convertToExternalDashboard(newDashboard, { hidePromql: !promqlEnabled, - hideAdhoc: true, }); return { content: [ @@ -325,6 +324,7 @@ async function updateDashboard({ tiles: tilesWithId, filters, existingTiles: existingDashboard.tiles ?? [], + existingFilters: existingDashboard.filters ?? [], containers: effectiveContainers, }); if (validationError) { @@ -358,9 +358,9 @@ async function updateDashboard({ tilesWithId, existingTileIds, ); - // With PromQL disabled, reads hide PromQL tiles and PROMETHEUS_LABEL - // filters, so the agent's lists never contain them. Keep them rather than - // delete what it could not see. A request tile that reuses a hidden tile's + // With PromQL disabled, reads hide PromQL tiles and PromQL filters, so the + // agent's lists never contain them. Keep them rather than delete what it + // could not see. A request tile that reuses a hidden tile's // id replaces it. const requestTileIds = new Set(requestTiles.map(tile => tile.id)); const internalTiles = promqlEnabled @@ -393,8 +393,7 @@ async function updateDashboard({ const hiddenFilters = promqlEnabled ? [] : (existingDashboard.filters ?? []).filter( - filter => - isPrometheusLabelFilter(filter) && !requestFilterIds.has(filter.id), + filter => isPromqlFilter(filter) && !requestFilterIds.has(filter.id), ); // The body schema checks that variable names are unique only across the @@ -453,7 +452,6 @@ async function updateDashboard({ const externalDashboard = convertToExternalDashboard(updatedDashboard, { hidePromql: !promqlEnabled, - hideAdhoc: true, }); return { content: [ diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index a195efa154..090d00522b 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -3,6 +3,9 @@ // separator (e.g. "Source ID – call clickstack_list_sources") for LLM // readability. Reformatting all separators is out of scope here. import { + ADHOC_FILTER_MAX_CONDITIONS, + AdhocFilterConditionSchema, + AdhocFilterSourceTypeSchema, AggregateFunctionSchema, BackgroundChartSchema, ChartPaletteTokenSchema, @@ -35,6 +38,7 @@ import { } from '@/mcp/tools/query/schemas'; import { QUERYABLE_METRIC_KINDS } from '@/mcp/tools/sources/metricKinds'; import { + externalAdhocSavedFilterValueSchema, externalSqlSavedFilterValueSchema, externalVariableSavedFilterValueSchema, objectIdSchema, @@ -1819,17 +1823,93 @@ const mcpPromqlLabelFilterSchema = z 'default multi-select, or {job="$job"} with maxSelections: 1.', ); +// Selection limits and requirements have no meaning for a list of conditions, +// so the ad hoc shape doesn't carry them. +const mcpAdhocFilterSchema = z + .object({ + id: mcpDashboardFilterBaseShape.id, + name: mcpDashboardFilterBaseShape.name, + variableName: variableNameSchema.describe( + "Unique name the filter's conditions are saved under in savedFilterValues. " + + 'Tiles CANNOT reference it as a variable. A default is derived from the ' + + "display name when omitted. Must be unique across the dashboard's " + + 'variable-enabled filters.', + ), + type: z + .literal(DashboardFilterType.enum.ADHOC) + .describe( + 'Filter type discriminator for a filter holding free-form key / operator / value conditions.', + ), + sourceType: z + .literal('sql') + .describe( + '"sql": keys are the columns and map keys of Log, Trace, or Session sources.', + ), + sources: z + .array(objectIdSchema) + .min(1) + .describe( + 'IDs of the Log, Trace, or Session sources (from clickstack_list_sources) ' + + 'whose keys and values the filter suggests.', + ), + where: z + .string() + .optional() + .describe( + 'Optional condition narrowing the rows keys and values are suggested from. ' + + "Never applied to tiles. May reference other filters' variables.", + ), + whereLanguage: SearchConditionTrimmedLanguageSchema.describe( + 'Query language of `where`.', + ), + appliesToSourceIds: z + .array(objectIdSchema) + .optional() + .describe( + 'IDs of the sources whose tiles the conditions apply to, of the same kind ' + + "as `sources`. Omit to apply to the tiles of the filter's `sources`.", + ), + }) + .describe( + 'An ad hoc filter: the user picks any number of key / operator / value ' + + 'conditions in the filter bar, or clicks values in tiles, and every ' + + 'condition is ANDed onto the tiles the filter applies to. Always ' + + 'broadcasts and is never a variable. Seed its conditions with an ' + + '"adhoc" entry in savedFilterValues.', + ); + +const mcpPromqlAdhocFilterSchema = mcpAdhocFilterSchema.extend({ + sourceType: AdhocFilterSourceTypeSchema.describe( + '"sql": keys are the columns and map keys of Log, Trace, or Session sources. ' + + '"promql": keys are the labels of promql sources, and conditions are added ' + + 'as label matchers to every selector in PromQL tiles.', + ), + sources: z + .array(objectIdSchema) + .min(1) + .describe( + 'IDs of the sources (from clickstack_list_sources) whose keys and values ' + + 'the filter suggests: Log, Trace, or Session sources for sourceType ' + + '"sql", promql sources for "promql".', + ), + where: mcpAdhocFilterSchema.shape.where.describe( + `${mcpAdhocFilterSchema.shape.where.description} sourceType "sql" only; rejected when sourceType is "promql".`, + ), +}); + const mcpDashboardFilterSchema = z .discriminatedUnion('type', [ mcpQueryExpressionFilterSchema, mcpStaticListFilterSchema, mcpSqlQueryFilterSchema, + mcpAdhocFilterSchema, ]) .describe( 'A dashboard-level filter the user can adjust in the dashboard filter bar. ' + 'QUERY_EXPRESSION queries its dropdown values from a source column; ' + 'STATIC_LIST declares them inline; SQL_QUERY reads them from a SQL query. ' + - 'STATIC_LIST and SQL_QUERY are always variable-only.', + 'STATIC_LIST and SQL_QUERY are always variable-only. ADHOC holds free-form ' + + 'conditions and always broadcasts.', ); const mcpPromqlDashboardFilterSchema = z @@ -1838,13 +1918,15 @@ const mcpPromqlDashboardFilterSchema = z mcpStaticListFilterSchema, mcpSqlQueryFilterSchema, mcpPromqlLabelFilterSchema, + mcpPromqlAdhocFilterSchema, ]) .describe( 'A dashboard-level filter the user can adjust in the dashboard filter bar. ' + 'QUERY_EXPRESSION queries its dropdown values from a source column; ' + 'STATIC_LIST declares them inline; SQL_QUERY reads them from a SQL query; ' + - 'PROMETHEUS_LABEL lists the values of a label on a promql source. All but ' + - 'QUERY_EXPRESSION are always variable-only.', + 'PROMETHEUS_LABEL lists the values of a label on a promql source. Those three ' + + 'are always variable-only. ADHOC holds free-form conditions on SQL or promql ' + + 'sources and always broadcasts.', ); export type McpDashboardFilter = z.infer; @@ -1860,7 +1942,9 @@ const mcpFiltersParam = z 'Filter types: QUERY_EXPRESSION queries its dropdown values from a source column. ' + 'STATIC_LIST declares them inline via `options`, and SQL_QUERY reads them from the ' + 'first column of a ClickHouse query; both are always variable-only (they have no ' + - 'expression to broadcast).\n\n' + + 'expression to broadcast). ADHOC lets the user build any number of ' + + 'key / operator / value conditions, with keys and values suggested from its ' + + '`sources`, and always broadcasts them; it is never a variable.\n\n' + 'A QUERY_EXPRESSION filter runs in one of two modes (or both). BROADCAST (the default) applies the ' + 'selected value as a condition on matching tiles with no per-tile wiring. VARIABLE ' + '(isVariableEnabled) exposes the value to tile queries as $variableName, which the tile ' + @@ -1918,7 +2002,16 @@ const mcpFiltersParam = z ']\n' + "A filter's `where` scopes only the values ITS dropdown offers; it is not applied to " + 'any tile. That is why Service keeps broadcasting here: its variable is read by the ' + - 'Endpoint dropdown, not by a tile, so the value is never applied twice.', + 'Endpoint dropdown, not by a tile, so the value is never applied twice.\n\n' + + 'Example (ad hoc: free-form conditions on the log and trace tiles, seeded via ' + + 'savedFilterValues):\n' + + '[\n' + + ' { "type": "ADHOC", "name": "Conditions", "sourceType": "sql",\n' + + ' "sources": ["", ""], "variableName": "conditions" }\n' + + ']\n' + + 'with savedFilterValues: [{ "type": "adhoc", "name": "conditions", "conditions": ' + + '[{ "key": "ServiceName", "operator": "IN", "value": "api" }, ' + + '{ "key": "ServiceName", "operator": "IN", "value": "web" }] }].', ); const PROMQL_FILTERS_EXAMPLE = @@ -1929,7 +2022,10 @@ const PROMQL_FILTERS_EXAMPLE = ' { "type": "PROMETHEUS_LABEL", "name": "Job", "sourceId": "",\n' + ' "label": "job", "variableName": "job" }\n' + ']\n' + - 'A PromQL tile references it as rate(http_requests_total{job=~"$job"}[$__rate_interval]).'; + 'A PromQL tile references it as rate(http_requests_total{job=~"$job"}[$__rate_interval]).\n\n' + + 'An ADHOC filter with sourceType "promql" reads label keys and values from promql ' + + '`sources` and adds its conditions as label matchers to every selector in the PromQL ' + + 'tiles it applies to; no tile wiring is needed.'; /** PROMETHEUS_LABEL filters are offered only while PromQL is enabled. */ export function buildMcpFiltersParam(promqlEnabled: boolean) { @@ -1969,9 +2065,45 @@ const mcpVariableSavedFilterValueSchema = ), }); +const adhocValueShape = externalAdhocSavedFilterValueSchema.shape; +const mcpAdhocSavedFilterValueSchema = + externalAdhocSavedFilterValueSchema.extend({ + type: adhocValueShape.type.describe( + 'Entry kind: the conditions of an ADHOC filter.', + ), + name: adhocValueShape.name.describe( + 'The variableName of the ADHOC filter these conditions belong to.', + ), + conditions: z + .array( + AdhocFilterConditionSchema.extend({ + key: AdhocFilterConditionSchema.shape.key.describe( + 'A SQL expression (column or map access, e.g. "ServiceName" or ' + + '"SpanAttributes[\'http.method\']") for a sql filter, or a label ' + + 'name for a promql filter.', + ), + operator: AdhocFilterConditionSchema.shape.operator.describe( + '=, !=, =~ (regex), !~ (not regex), and IN. sql filters also take ' + + 'LIKE and NOT LIKE. Conditions are ANDed, except that IN conditions ' + + 'on the same key are ORed into one IN (...) for a sql filter or ' + + '=~"a|b" matcher for a promql filter, so each carries one value.', + ), + value: AdhocFilterConditionSchema.shape.value.describe( + 'The value, LIKE pattern, or regular expression to compare against.', + ), + }), + ) + .max(ADHOC_FILTER_MAX_CONDITIONS) + .describe("The filter's conditions."), + }); + export const mcpSavedFilterValuesParam = z .array( - z.union([mcpSqlSavedFilterValueSchema, mcpVariableSavedFilterValueSchema]), + z.union([ + mcpSqlSavedFilterValueSchema, + mcpVariableSavedFilterValueSchema, + mcpAdhocSavedFilterValueSchema, + ]), ) .describe( 'Default filter selections restored every time the dashboard is opened. ' + diff --git a/packages/api/src/mcp/tools/dashboards/validation.ts b/packages/api/src/mcp/tools/dashboards/validation.ts index ff672ab5cd..d678b37729 100644 --- a/packages/api/src/mcp/tools/dashboards/validation.ts +++ b/packages/api/src/mcp/tools/dashboards/validation.ts @@ -4,6 +4,7 @@ import type { FilterForVariableDeclaration } from '@hyperdx/common-utils/dist/fi import { getDashboardVariableDeclarations, getFilterVariableName, + isAdhocConditionSupported, isFilterVariableEnabled, validateSqlQueryFilterTemplate, } from '@hyperdx/common-utils/dist/filters'; @@ -19,6 +20,8 @@ import { TIME_RANGE_MACROS, } from '@hyperdx/common-utils/dist/macros'; import { + AdhocFilterSourceType, + AdhocFilterValue, DashboardFilterValue, DisplayType, QueryExpressionDashboardFilter, @@ -257,14 +260,17 @@ export function getFilterVariableWarnings( } /** - * Non-blocking check: a saved filter value of type 'variable' whose `name` - * matches no variable-enabled filter is silently ignored when the dashboard - * loads, so a typo'd variable name looks like a saved default but never - * applies. Warn so the agent can fix the name or add the filter. + * Non-blocking check: a saved filter value of type 'variable' or 'adhoc' whose + * `name` matches no filter of its kind, or an ad hoc condition its filter's + * source type can't express, is silently ignored when the dashboard loads, so + * it looks like a saved default but never applies. Warn so the agent can fix + * it. */ export function getSavedFilterValueWarnings( savedFilterValues: DashboardFilterValue[] | undefined, - filters: FilterForVariableDeclaration[] | undefined, + filters: + | (FilterForVariableDeclaration & { sourceType?: AdhocFilterSourceType })[] + | undefined, ): string[] { if (!savedFilterValues?.length) return []; const declaredNames = new Set( @@ -272,8 +278,19 @@ export function getSavedFilterValueWarnings( declaration => declaration.name, ), ); + const adhocSourceTypeByName = new Map( + (filters ?? []).flatMap(filter => + filter.type === 'ADHOC' && filter.sourceType + ? [[getFilterVariableName(filter), filter.sourceType] as const] + : [], + ), + ); const warnings: string[] = []; for (const value of savedFilterValues) { + if (value.type === 'adhoc') { + warnings.push(...getAdhocValueWarnings(value, adhocSourceTypeByName)); + continue; + } if (value.type !== 'variable') continue; const name = value.name.trim(); if (!name || declaredNames.has(name)) continue; @@ -287,6 +304,29 @@ export function getSavedFilterValueWarnings( return warnings; } +function getAdhocValueWarnings( + value: AdhocFilterValue, + sourceTypeByName: ReadonlyMap, +): string[] { + const sourceType = sourceTypeByName.get(value.name.trim()); + if (sourceType === undefined) { + return [ + `savedFilterValues has ad hoc conditions for "${value.name}", which no ADHOC ` + + "filter's variableName matches. They are ignored when the dashboard loads: " + + 'fix the name or remove the entry.', + ]; + } + const unsupported = value.conditions.filter( + condition => !isAdhocConditionSupported(sourceType, condition), + ); + if (unsupported.length === 0) return []; + return [ + `savedFilterValues has ad hoc conditions for "${value.name}" using ` + + `${[...new Set(unsupported.map(c => c.operator))].join(', ')}, which a ` + + `${sourceType} filter cannot apply. They are not applied to tiles.`, + ]; +} + function variableIssueSubject(language: TemplateLanguage): string { switch (language) { case 'sql': diff --git a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts index dec4319981..9ab3802983 100644 --- a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts +++ b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts @@ -508,41 +508,35 @@ describe('convertToExternalDashboard orphan-ref heal', () => { expect(hidden.filters?.map(f => f.id)).toEqual(['static-filter']); }); - it('hides ad hoc filters and their saved conditions only when asked', () => { - const adhoc = { - id: 'adhoc-filter', + it('returns ad hoc filters and their saved conditions, hiding PromQL ones with PromQL', () => { + const adhoc = (sourceType: 'sql' | 'promql') => ({ + id: `${sourceType}-adhoc`, type: 'ADHOC' as const, - name: 'Conditions', - sourceType: 'sql' as const, - sources: [new mongoose.Types.ObjectId().toString()], + name: sourceType, + sourceType, + sources: ['65f5e4a3b9e77c001a111111'], isBroadcastEnabled: true as const, isVariableEnabled: true as const, - variableName: 'conds', - }; - const variableValue = { - type: 'variable' as const, - name: 'env', - values: ['prod'], - }; + }); const adhocValue = { type: 'adhoc' as const, - name: 'conds', + name: 'sql', conditions: [ { key: 'ServiceName', operator: '=' as const, value: 'api' }, ], }; const doc = makeDoc({ - filters: [adhoc], - savedFilterValues: [variableValue, adhocValue], + filters: [adhoc('sql'), adhoc('promql')], + savedFilterValues: [adhocValue], }); const shown = convertToExternalDashboard(doc); - expect(shown.filters).toEqual([adhoc]); - expect(shown.savedFilterValues).toEqual([variableValue, adhocValue]); + expect(shown.filters).toEqual([adhoc('sql'), adhoc('promql')]); + expect(shown.savedFilterValues).toEqual([adhocValue]); - const hidden = convertToExternalDashboard(doc, { hideAdhoc: true }); - expect(hidden.filters).toEqual([]); - expect(hidden.savedFilterValues).toEqual([variableValue]); + const hidden = convertToExternalDashboard(doc, { hidePromql: true }); + expect(hidden.filters).toEqual([adhoc('sql')]); + expect(hidden.savedFilterValues).toEqual([adhocValue]); }); // seriesLimit is three-state (matching the internal schema): omitted = diff --git a/packages/api/src/routers/external-api/v2/utils/dashboards.ts b/packages/api/src/routers/external-api/v2/utils/dashboards.ts index da0b400a91..0590b30fc3 100644 --- a/packages/api/src/routers/external-api/v2/utils/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/utils/dashboards.ts @@ -14,6 +14,7 @@ import { validateDashboardTileContainerRefs, } from '@hyperdx/common-utils/dist/dashboardValidation'; import { + isAdhocFilter, isPrometheusLabelFilter, isQueryExpressionFilter, } from '@hyperdx/common-utils/dist/filters'; @@ -56,8 +57,6 @@ import { getConnectionsByTeam } from '@/controllers/connection'; import { getSources } from '@/controllers/sources'; import Dashboard, { DashboardDocument } from '@/models/dashboard'; import { - getMcpCompatibleFilters, - getMcpCompatibleFilterValues, translateExternalChartToTileConfig, translateExternalFilterToFilter, translateFilterToExternalFilter, @@ -775,17 +774,22 @@ function convertTileToExternalChart( }; } +/** Whether a filter only works while PromQL is enabled. */ +export function isPromqlFilter(filter: DashboardFilter): boolean { + return ( + isPrometheusLabelFilter(filter) || + (isAdhocFilter(filter) && filter.sourceType === 'promql') + ); +} + export function convertToExternalDashboard( dashboard: DashboardDocument, { hidePromql = false, - hideAdhoc = false, }: { - // MCP hides PromQL tiles and PROMETHEUS_LABEL filters while PromQL is - // disabled on the deployment. + // MCP hides PromQL tiles and PromQL filters while PromQL is disabled on + // the deployment. hidePromql?: boolean; - // MCP doesn't expose ad hoc filters or their saved conditions yet. - hideAdhoc?: boolean; } = {}, ): ExternalDashboard { const containers = dashboard.containers ?? []; @@ -807,17 +811,12 @@ export function convertToExternalDashboard( convertTileToExternalChart(tile, containerById, dashboardId), ), tags: dashboard.tags || [], - filters: (hideAdhoc - ? getMcpCompatibleFilters(dashboard.filters) - : (dashboard.filters ?? []) - ) - .filter(filter => !(hidePromql && isPrometheusLabelFilter(filter))) + filters: (dashboard.filters ?? []) + .filter(filter => !(hidePromql && isPromqlFilter(filter))) .map(translateFilterToExternalFilter), savedQuery: dashboard.savedQuery ?? null, savedQueryLanguage: dashboard.savedQueryLanguage ?? null, - savedFilterValues: hideAdhoc - ? getMcpCompatibleFilterValues(dashboard.savedFilterValues) - : (dashboard.savedFilterValues ?? []), + savedFilterValues: dashboard.savedFilterValues ?? [], // Mongoose persists missing arrays as []. Only emit containers when // the user actually saved one or more, so dashboards without the // organization layer round-trip with the field absent. diff --git a/packages/api/src/utils/externalApi.ts b/packages/api/src/utils/externalApi.ts index 789055c2c0..a626c5e49f 100644 --- a/packages/api/src/utils/externalApi.ts +++ b/packages/api/src/utils/externalApi.ts @@ -1,7 +1,5 @@ import { TIME_SERIES_DISPLAY_TYPE_BY_NAME } from '@hyperdx/common-utils/dist/core/utils'; import { - isAdhocFilter, - isAdhocFilterValue, isFilterBroadcastEnabled, isFilterRequired, isFilterVariableEnabled, @@ -240,20 +238,6 @@ export function translateExternalChartToTileConfig( }; } -/** The filters MCP may read; it doesn't expose ad hoc filters yet. */ -export function getMcpCompatibleFilters( - filters: DashboardFilter[] | undefined, -): DashboardFilter[] { - return (filters ?? []).filter(filter => !isAdhocFilter(filter)); -} - -/** Saved filter values MCP may read; it doesn't expose ad hoc filters yet. */ -export function getMcpCompatibleFilterValues( - values: IDashboard['savedFilterValues'], -): NonNullable { - return (values ?? []).filter(value => !isAdhocFilterValue(value)); -} - export function translateFilterToExternalFilter( filter: DashboardFilter, ): ExternalDashboardFilterWithId { diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index a53e083d96..05cd5c23d8 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -255,10 +255,13 @@ export const externalSqlSavedFilterValueSchema = z.object({ export const externalVariableSavedFilterValueSchema = VariableFilterValueSchema.strict(); +export const externalAdhocSavedFilterValueSchema = + AdhocFilterValueSchema.strict(); + export const externalDashboardSavedFilterValueSchema = z.union([ externalSqlSavedFilterValueSchema, externalVariableSavedFilterValueSchema, - AdhocFilterValueSchema.strict(), + externalAdhocSavedFilterValueSchema, ]); // ================================ From bfb5c834ff36eb98be72c484bdce36f9846cd079 Mon Sep 17 00:00:00 2001 From: Ntms Pavan Date: Tue, 17 Nov 2026 11:46:22 -0800 Subject: [PATCH 27/55] fix(api): use log body fallback in MCP and alert queries (#3681) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Closes #2355. A log source can define `bodyExpression` without a separate `implicitColumnExpression`. Bare-text Lucene searches already fall back to that body field in the UI, but several MCP and alert query builders omit it, so the same search fails there. This passes the log source's body expression through MCP builder queries, raw SQL tile hydration, pattern sampling/counting and drill-down filters, event-deltas sampling, and alert alias rendering. Notification samples already use the shared search-config builder; the new tests cover that path too. The existing serializer still decides which field to search. An explicit implicit column keeps priority, and trace sources receive no body fallback. There are no API or schema changes. ### How to reproduce **Starting point:** a local checkout with the integration-test services (`make dev-int-build` followed by `make dev-int`), or a full `yarn dev` stack. This requires the API; the frontend-only demo cannot exercise these paths. **On `main`:** 1. Configure a log source with `bodyExpression: Body` and no `implicitColumnExpression`. 2. Insert one log whose Body contains `needle`, plus another whose ServiceName contains `needle` but whose Body does not. 3. Call `clickstack_search` with `where: needle`, `whereLanguage: lucene`, and a time range covering those logs. It fails with “Can not search bare text without an implicit column set.” The pattern/comparison tools and saved-search alert alias rendering have the same gap. **On this branch:** 1. Repeat the search. It returns the body-matching row. 2. Set the source's implicit column to ServiceName and repeat it. The ServiceName-matching row is returned instead. 3. Run `make dev-int FILE=bodyExpressionFallback`: all 14 cases pass, including rejection when neither search field is configured and unchanged trace behavior. ### Tests Run in a Node 22 container with MongoDB 5.0.32 and ClickHouse 26.10.3.7: - `yarn lint:fix` - `yarn lint-staged` - `make ci-lint` - `make ci-unit` - Affected integration suites: **168 tests passed**, including the 14 fallback cases. These cover absent/empty implicit columns, explicit-column precedence, map-valued body expressions, raw SQL source hydration and filtered rows, pattern counts and drill-downs, both comparison windows, alert aliases, notification samples, rejection without either search field, and unchanged trace behavior. The integration command used was: ```sh cd packages/api yarn ci:int src/mcp/__tests__/queryTool.int.test.ts \ src/mcp/__tests__/deltasTool.int.test.ts \ src/mcp/__tests__/emergingSignalsTool.int.test.ts \ src/mcp/__tests__/dashboards/queryTile.int.test.ts \ bodyExpressionFallback.int.test.ts ``` ### Risks and limitations This changes previously failing bare-text filters on body-only log sources into working body searches in the listed paths. It reuses existing expression rendering and adds no SQL parser or new query endpoint. The raw SQL test executes the MCP-hydrated config with a Lucene filter against ClickHouse at the query-client boundary: `query_tile` currently exposes variables but no runtime dashboard-filter input. The full integration and browser E2E suites were not run. The pre-existing omissions in tile/inline-alert evaluation and denoise queries remain separate follow-ups. This PR follows the issue's named call sites and the repository's review-scope rules. ### How to test on Vercel preview N/A — API-only change. ### References - Issue: #2355 - Original UI fallback: #2354 --- .changeset/log-body-search-fallback.md | 6 + .../bodyExpressionFallback.int.test.ts | 274 ++++++++++++++++++ .../api/src/mcp/tools/query/eventDeltas.ts | 2 + packages/api/src/mcp/tools/query/helpers.ts | 5 + .../src/mcp/tools/query/patternDrilldown.ts | 3 + .../src/mcp/tools/query/runEventPatterns.ts | 7 +- .../bodyExpressionFallback.int.test.ts | 148 ++++++++++ packages/api/src/tasks/checkAlerts/index.ts | 2 + 8 files changed, 446 insertions(+), 1 deletion(-) create mode 100644 .changeset/log-body-search-fallback.md create mode 100644 packages/api/src/mcp/__tests__/bodyExpressionFallback.int.test.ts create mode 100644 packages/api/src/tasks/checkAlerts/__tests__/bodyExpressionFallback.int.test.ts diff --git a/.changeset/log-body-search-fallback.md b/.changeset/log-body-search-fallback.md new file mode 100644 index 0000000000..10397cf1ba --- /dev/null +++ b/.changeset/log-body-search-fallback.md @@ -0,0 +1,6 @@ +--- +'@hyperdx/api': patch +--- + +Use the log source body expression for bare-text MCP searches, pattern filters, +event deltas, and alert alias queries when no implicit search column is set. diff --git a/packages/api/src/mcp/__tests__/bodyExpressionFallback.int.test.ts b/packages/api/src/mcp/__tests__/bodyExpressionFallback.int.test.ts new file mode 100644 index 0000000000..69ae7232bc --- /dev/null +++ b/packages/api/src/mcp/__tests__/bodyExpressionFallback.int.test.ts @@ -0,0 +1,274 @@ +import { ClickhouseClient } from '@hyperdx/common-utils/dist/clickhouse/node'; +import { isRawSqlChartConfig } from '@hyperdx/common-utils/dist/guards'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; + +import * as config from '@/config'; +import { + bulkInsertLogs, + DEFAULT_DATABASE, + DEFAULT_LOGS_TABLE, + getLoggedInAgent, + getServer, +} from '@/fixtures'; +import Connection from '@/models/connection'; +import { LogSource, Source, SourceDocument } from '@/models/source'; + +import { callTool, createTestClient, getFirstText } from './mcpTestUtils'; + +describe('log body fallback for bare-text MCP filters', () => { + const server = getServer(); + let client: Client; + let source: SourceDocument; + let connectionId: string; + let now: number; + + beforeAll(async () => { + await server.start(); + }); + + beforeEach(async () => { + const { team, user } = await getLoggedInAgent(server); + const connection = await Connection.create({ + team: team._id, + name: 'Body fallback', + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + connectionId = connection.id; + source = await Source.create({ + kind: SourceKind.Log, + team: team._id, + connection: connection._id, + name: 'Logs', + from: { databaseName: DEFAULT_DATABASE, tableName: DEFAULT_LOGS_TABLE }, + timestampValueExpression: 'Timestamp', + bodyExpression: 'Body', + }); + client = await createTestClient({ + teamId: team._id.toString(), + userId: user._id.toString(), + }); + now = Date.now(); + await bulkInsertLogs( + [2, 7].flatMap(minutes => [ + { + Body: 'needle in body', + ServiceName: 'api', + SeverityText: 'error', + LogAttributes: { message: 'other' }, + Timestamp: new Date(now - minutes * 60_000), + }, + { + Body: 'other', + ServiceName: 'needle', + SeverityText: 'info', + LogAttributes: { message: 'needle in map' }, + Timestamp: new Date(now - minutes * 60_000), + }, + ]), + ); + }); + + afterEach(async () => { + await client.close(); + await server.clearDBs(); + }); + + afterAll(async () => { + await server.stop(); + }); + + const currentWindow = () => ({ + startTime: new Date(now - 5 * 60_000).toISOString(), + endTime: new Date(now).toISOString(), + }); + + it.each([ + { implicitColumnExpression: undefined, expectedBody: 'needle in body' }, + { implicitColumnExpression: '', expectedBody: 'needle in body' }, + { implicitColumnExpression: 'ServiceName', expectedBody: 'other' }, + ])( + 'searches the correct field with implicitColumnExpression=$implicitColumnExpression', + async ({ implicitColumnExpression, expectedBody }) => { + await LogSource.updateOne( + { _id: source._id }, + implicitColumnExpression === undefined + ? { $unset: { implicitColumnExpression: '' } } + : { $set: { implicitColumnExpression } }, + ); + const result = await callTool(client, 'clickstack_search', { + sourceId: source._id.toString(), + where: 'needle', + ...currentWindow(), + }); + expect(result.isError).toBeFalsy(); + const output = JSON.parse(getFirstText(result)); + expect(output.result.data).toEqual([ + expect.objectContaining({ Body: expectedBody }), + ]); + }, + ); + + it('uses a map-valued body expression for bare-text search', async () => { + await LogSource.updateOne( + { _id: source._id }, + { $set: { bodyExpression: "LogAttributes['message']" } }, + ); + const result = await callTool(client, 'clickstack_search', { + sourceId: source._id.toString(), + where: 'needle', + ...currentWindow(), + }); + expect(result.isError).toBeFalsy(); + expect(JSON.parse(getFirstText(result)).result.data).toEqual([ + expect.objectContaining({ Body: 'other' }), + ]); + }); + + it('rejects bare-text search without an implicit column or body expression', async () => { + await LogSource.updateOne( + { _id: source._id }, + { $unset: { implicitColumnExpression: '', bodyExpression: '' } }, + ); + const result = await callTool(client, 'clickstack_search', { + sourceId: source._id.toString(), + where: 'needle', + ...currentWindow(), + }); + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain( + 'Can not search bare text without an implicit column set.', + ); + }); + + it('does not introduce a body fallback for MCP trace searches', async () => { + const traceSource = await Source.create({ + kind: SourceKind.Trace, + team: source.team, + connection: source.connection, + name: 'Traces', + from: { databaseName: 'default', tableName: 'otel_traces' }, + timestampValueExpression: 'Timestamp', + spanNameExpression: 'SpanName', + }); + const result = await callTool(client, 'clickstack_search', { + sourceId: traceSource._id.toString(), + where: 'needle', + ...currentWindow(), + }); + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain( + 'Can not search bare text without an implicit column set.', + ); + }); + + it('uses raw SQL tile hydration to filter by the log body expression', async () => { + const saved = await callTool(client, 'clickstack_save_dashboard', { + name: 'Body fallback', + tiles: [ + { + name: 'Matching logs', + config: { + configType: 'sql', + displayType: 'table', + connectionId, + sourceId: source._id.toString(), + sqlTemplate: + 'SELECT Body FROM $__sourceTable WHERE $__timeFilter(Timestamp) AND $__filters', + }, + }, + ], + }); + expect(saved.isError).toBeFalsy(); + const dashboard = JSON.parse(getFirstText(saved)); + const query = jest.spyOn(ClickhouseClient.prototype, 'queryChartConfig'); + try { + const result = await callTool(client, 'clickstack_query_tile', { + dashboardId: dashboard.id, + tileId: dashboard.tiles[0].id, + ...currentWindow(), + }); + expect(result.isError).toBeFalsy(); + expect(query).toHaveBeenCalledTimes(1); + const [queryOptions] = query.mock.calls[0]; + if (!isRawSqlChartConfig(queryOptions.config)) { + throw new Error('Expected a raw SQL tile query'); + } + const clickhouseClient = new ClickhouseClient({ + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + // query_tile exposes variables but not runtime dashboard filters. + const filtered = await clickhouseClient.queryChartConfig({ + ...queryOptions, + config: { + ...queryOptions.config, + filters: [{ type: 'lucene', condition: 'needle' }], + }, + }); + expect(filtered.data).toEqual([{ Body: 'needle in body' }]); + } finally { + query.mockRestore(); + } + }); + + it('uses the fallback for pattern samples, counts and drill-down filters', async () => { + const result = await callTool(client, 'clickstack_event_patterns', { + sourceId: source._id.toString(), + where: 'needle', + ...currentWindow(), + }); + expect(result.isError).toBeFalsy(); + const output = JSON.parse(getFirstText(result)); + expect(output.summary.totalCount).toBe(1); + expect(output.summary.sampledCount).toBe(1); + expect(output.patterns).toHaveLength(1); + expect(output.patterns[0].whereSnippet).toContain('Body'); + const drilldown = await callTool(client, 'clickstack_search', { + sourceId: source._id.toString(), + where: output.patterns[0].whereSnippet, + whereLanguage: 'sql', + ...currentWindow(), + }); + expect(drilldown.isError).toBeFalsy(); + expect(JSON.parse(getFirstText(drilldown)).result.data).toEqual([ + expect.objectContaining({ Body: 'needle in body' }), + ]); + }); + + it('uses the fallback in both emerging-signals windows', async () => { + const result = await callTool(client, 'clickstack_emerging_signals', { + sourceId: source._id.toString(), + where: 'needle', + currentStartTime: currentWindow().startTime, + currentEndTime: currentWindow().endTime, + baselineStartTime: new Date(now - 10 * 60_000).toISOString(), + baselineEndTime: currentWindow().startTime, + }); + expect(result.isError).toBeFalsy(); + const output = JSON.parse(getFirstText(result)); + expect(output.summary.currentWindow.total).toBe(1); + expect(output.summary.currentWindow.sampled).toBe(1); + expect(output.summary.baselineWindow.total).toBe(1); + expect(output.summary.baselineWindow.sampled).toBe(1); + }); + + it('uses the fallback in both event-deltas samples', async () => { + const result = await callTool(client, 'clickstack_event_deltas', { + sourceId: source._id.toString(), + target: { ...currentWindow(), where: 'needle' }, + baseline: { + startTime: new Date(now - 10 * 60_000).toISOString(), + endTime: currentWindow().startTime, + where: 'needle', + }, + }); + expect(result.isError).toBeFalsy(); + const output = JSON.parse(getFirstText(result)); + expect(output.summary.targetSampleCount).toBe(1); + expect(output.summary.baselineSampleCount).toBe(1); + }); +}); diff --git a/packages/api/src/mcp/tools/query/eventDeltas.ts b/packages/api/src/mcp/tools/query/eventDeltas.ts index bed6345f9c..603267551c 100644 --- a/packages/api/src/mcp/tools/query/eventDeltas.ts +++ b/packages/api/src/mcp/tools/query/eventDeltas.ts @@ -296,6 +296,8 @@ export function registerEventDeltas({ context, registerTool }: ToolRegistrar) { 'implicitColumnExpression' in source ? source.implicitColumnExpression : undefined, + bodyExpression: + source.kind === SourceKind.Log ? source.bodyExpression : undefined, orderBy: stableSampleExpr, limit: { limit: sampleSize }, dateRange: [startDate, endDate], diff --git a/packages/api/src/mcp/tools/query/helpers.ts b/packages/api/src/mcp/tools/query/helpers.ts index 282bf2f056..63f5d9a668 100644 --- a/packages/api/src/mcp/tools/query/helpers.ts +++ b/packages/api/src/mcp/tools/query/helpers.ts @@ -678,6 +678,8 @@ export async function runConfigTile( connection: source.connection.toString(), timestampValueExpression: source.timestampValueExpression, implicitColumnExpression: implicitColumn, + bodyExpression: + source.kind === SourceKind.Log ? source.bodyExpression : undefined, useTextIndexForImplicitColumn, dateRange: [startDate, endDate] as [Date, Date], variables: options?.variables, @@ -738,6 +740,7 @@ export async function runConfigTile( let sourceFields: { from?: { databaseName: string; tableName: string }; implicitColumnExpression?: string; + bodyExpression?: string; useTextIndexForImplicitColumn?: UseTextIndex; metricTables?: MetricTable; } = {}; @@ -752,6 +755,8 @@ export async function runConfigTile( 'implicitColumnExpression' in source ? source.implicitColumnExpression : undefined, + bodyExpression: + source.kind === SourceKind.Log ? source.bodyExpression : undefined, useTextIndexForImplicitColumn: 'useTextIndexForImplicitColumn' in source ? source.useTextIndexForImplicitColumn diff --git a/packages/api/src/mcp/tools/query/patternDrilldown.ts b/packages/api/src/mcp/tools/query/patternDrilldown.ts index 5e85cb6c00..b8ee1edd22 100644 --- a/packages/api/src/mcp/tools/query/patternDrilldown.ts +++ b/packages/api/src/mcp/tools/query/patternDrilldown.ts @@ -80,6 +80,7 @@ export async function userWhereAsSql({ tableName, connectionId, implicitColumnExpression, + bodyExpression, useTextIndexForImplicitColumn, }: { where: string; @@ -90,6 +91,7 @@ export async function userWhereAsSql({ tableName: string; connectionId: string; implicitColumnExpression?: string; + bodyExpression?: string; useTextIndexForImplicitColumn?: UseTextIndex; }): Promise { if (!where.trim()) return ''; @@ -103,6 +105,7 @@ export async function userWhereAsSql({ from: { databaseName, tableName }, connectionId, implicitColumnExpression, + bodyExpression, useTextIndexForImplicitColumn, }); } diff --git a/packages/api/src/mcp/tools/query/runEventPatterns.ts b/packages/api/src/mcp/tools/query/runEventPatterns.ts index f92e423956..c20ba29e9d 100644 --- a/packages/api/src/mcp/tools/query/runEventPatterns.ts +++ b/packages/api/src/mcp/tools/query/runEventPatterns.ts @@ -11,7 +11,7 @@ import type { ChartConfigWithDateRange, ChartVariable, } from '@hyperdx/common-utils/dist/types'; -import { DisplayType } from '@hyperdx/common-utils/dist/types'; +import { DisplayType, SourceKind } from '@hyperdx/common-utils/dist/types'; import { trace } from '@opentelemetry/api'; import { ClickhouseClient } from '@/clickhouse'; @@ -168,6 +168,8 @@ export async function mineWindowPatterns( 'implicitColumnExpression' in source ? source.implicitColumnExpression : undefined; + const bodyExpression = + source.kind === SourceKind.Log ? source.bodyExpression : undefined; const useTextIndexForImplicitColumn = 'useTextIndexForImplicitColumn' in source ? source.useTextIndexForImplicitColumn @@ -190,6 +192,7 @@ export async function mineWindowPatterns( connection: source.connection.toString(), timestampValueExpression: source.timestampValueExpression, implicitColumnExpression: implicitColumn, + bodyExpression, useTextIndexForImplicitColumn, orderBy: [{ ordering: 'DESC' as const, valueExpression: 'rand()' }], limit: { limit: sampleSize, offset: 0 }, @@ -211,6 +214,7 @@ export async function mineWindowPatterns( connection: source.connection.toString(), timestampValueExpression: source.timestampValueExpression, implicitColumnExpression: implicitColumn, + bodyExpression, useTextIndexForImplicitColumn, limit: { limit: 1, offset: 0 }, dateRange: [startDate, endDate] as [Date, Date], @@ -232,6 +236,7 @@ export async function mineWindowPatterns( tableName: source.from.tableName, connectionId: source.connection.toString(), implicitColumnExpression: implicitColumn, + bodyExpression, useTextIndexForImplicitColumn, }).catch(err => { if (queriesFailed || options.abortSignal?.aborted) return null; diff --git a/packages/api/src/tasks/checkAlerts/__tests__/bodyExpressionFallback.int.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/bodyExpressionFallback.int.test.ts new file mode 100644 index 0000000000..b766831a19 --- /dev/null +++ b/packages/api/src/tasks/checkAlerts/__tests__/bodyExpressionFallback.int.test.ts @@ -0,0 +1,148 @@ +import { ClickhouseClient } from '@hyperdx/common-utils/dist/clickhouse/node'; +import { + getMetadata, + Metadata, +} from '@hyperdx/common-utils/dist/core/metadata'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; + +import * as config from '@/config'; +import { createTeam } from '@/controllers/team'; +import { bulkInsertLogs, getServer } from '@/fixtures'; +import Connection from '@/models/connection'; +import { ISource, LogSource, Source } from '@/models/source'; +import { computeAliasWithClauses } from '@/tasks/checkAlerts'; +import { fetchSampleLines } from '@/tasks/checkAlerts/template'; + +describe('log body fallback in alert queries', () => { + const server = getServer(); + let source: ISource; + let clickhouseClient: ClickhouseClient; + let metadata: Metadata; + const savedSearch = { + id: 'body-fallback', + select: 'Body AS message', + where: 'needle', + whereLanguage: 'lucene' as const, + }; + let startTime: Date; + let endTime: Date; + + beforeAll(async () => { + await server.start(); + }); + + beforeEach(async () => { + const team = await createTeam({ name: 'Body fallback' }); + const connection = await Connection.create({ + team: team._id, + name: 'Default', + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + source = await LogSource.create({ + team: team._id, + connection: connection._id, + name: 'Logs', + from: { databaseName: 'default', tableName: 'otel_logs' }, + timestampValueExpression: 'Timestamp', + bodyExpression: 'Body', + }); + clickhouseClient = new ClickhouseClient({ + host: connection.host, + username: connection.username, + password: connection.password, + }); + metadata = getMetadata(clickhouseClient); + const now = new Date(); + startTime = new Date(now.getTime() - 60_000); + endTime = new Date(now.getTime() + 60_000); + await bulkInsertLogs([ + { + Body: 'needle in body', + ServiceName: 'api', + SeverityText: 'error', + Timestamp: now, + }, + { + Body: 'other', + ServiceName: 'needle', + SeverityText: 'info', + Timestamp: now, + }, + ]); + }); + + afterEach(async () => { + await clickhouseClient.close(); + await server.clearDBs(); + }); + + afterAll(async () => { + await server.stop(); + }); + + it('renders saved-search aliases with a body-only source', async () => { + const clauses = await computeAliasWithClauses( + savedSearch, + source, + metadata, + ); + expect(clauses).toEqual( + expect.arrayContaining([expect.objectContaining({ name: 'message' })]), + ); + }); + + it('includes only matching body rows in notification samples', async () => { + const sample = await fetchSampleLines({ + clickhouseClient, + metadata, + source, + savedSearch, + startTime, + endTime, + }); + expect(sample).toContain('needle in body'); + expect(sample).not.toContain('other'); + }); + + it('keeps an explicit implicit column ahead of the body for notification samples', async () => { + await LogSource.updateOne( + { _id: source.id }, + { $set: { implicitColumnExpression: 'ServiceName' } }, + ); + const updated = await Source.findById(source.id); + expect(updated).not.toBeNull(); + const sample = await fetchSampleLines({ + clickhouseClient, + metadata, + source: updated!, + savedSearch, + startTime, + endTime, + }); + expect(sample).toContain('other'); + expect(sample).not.toContain('needle in body'); + }); + + it('does not introduce a body fallback for trace sources', async () => { + const traceSource = await Source.create({ + kind: SourceKind.Trace, + team: source.team, + connection: source.connection, + name: 'Traces', + from: { databaseName: 'default', tableName: 'otel_traces' }, + timestampValueExpression: 'Timestamp', + spanNameExpression: 'SpanName', + }); + await expect( + computeAliasWithClauses( + { ...savedSearch, select: 'SpanName AS span' }, + traceSource, + metadata, + ), + ).rejects.toThrow( + 'Can not search bare text without an implicit column set.', + ); + }); +}); diff --git a/packages/api/src/tasks/checkAlerts/index.ts b/packages/api/src/tasks/checkAlerts/index.ts index 18ece93b57..b4bc6b5bf0 100644 --- a/packages/api/src/tasks/checkAlerts/index.ts +++ b/packages/api/src/tasks/checkAlerts/index.ts @@ -187,6 +187,8 @@ export async function computeAliasWithClauses( source.kind === SourceKind.Log || source.kind === SourceKind.Trace ? source.implicitColumnExpression : undefined, + bodyExpression: + source.kind === SourceKind.Log ? source.bodyExpression : undefined, useTextIndexForImplicitColumn: source.kind === SourceKind.Log || source.kind === SourceKind.Trace ? source.useTextIndexForImplicitColumn From 50129d13d4bc04b035733e1bd3f90a13dec7da40 Mon Sep 17 00:00:00 2001 From: Willie Engelbrecht Date: Tue, 17 Nov 2026 21:43:29 +0100 Subject: [PATCH 28/55] fix: keep time chart series colors stable across refreshes (#3646) ## Summary Line colours on panels are assigned by series position, and ClickHouse returns groups in a different order as the time window moves, based on which blocks were processed at that particular point in time. This PR resolves by sorting the series alphabetically first, and then assigning the colour based on the now sorted alphabetical sorted list. Refreshing a graph now keeps the series colours consistent. ### Screenshots Before: Here you can see the colours assigned to each series. When reloading a page, or updating the time interval to a new internal, the series colours are assigned at somewhat random order: image After a second refresh: image And another refresh: image After: Now the colours assigned to each series remains the same, no matter how many times you refresh the page or update the time picker. image ### How to reproduce Before: Open a graph with multiple lines, and change the time picker to "last 15 minutes". Watch the colours selected on the graph. Keep repeating this process and you'll see after a few refreshes that the colours are seemingly assigned in random order to the same series. This is because ClickHouse does not guarantee the order of the returned series. After: Do the same as above, but now the series colours remain the same no matter how many times you refresh. This creates a richer user experience as a user might expect the graph to remain the same colours as they are used. --- .changeset/stable-series-colors.md | 6 ++ packages/app/src/ChartUtils.tsx | 10 ++- packages/app/src/__tests__/ChartUtils.test.ts | 86 ++++++++++++------- 3 files changed, 71 insertions(+), 31 deletions(-) create mode 100644 .changeset/stable-series-colors.md diff --git a/.changeset/stable-series-colors.md b/.changeset/stable-series-colors.md new file mode 100644 index 0000000000..cc21ce4856 --- /dev/null +++ b/.changeset/stable-series-colors.md @@ -0,0 +1,6 @@ +--- +'@hyperdx/app': patch +--- + +fix: time chart series keep the same color across refreshes; series are now +ordered by name instead of by the order ClickHouse returned them diff --git a/packages/app/src/ChartUtils.tsx b/packages/app/src/ChartUtils.tsx index fbbd1c4faf..839c421dac 100644 --- a/packages/app/src/ChartUtils.tsx +++ b/packages/app/src/ChartUtils.tsx @@ -869,10 +869,18 @@ export function formatResponseForTimeChart({ } const logLevelColorOrder = getLogLevelColorOrder(); + // Series are otherwise ordered by first appearance in the response, which + // ClickHouse does not keep stable between runs. Colors are assigned by + // position, so tie-break by key to keep each series' color stable. let sortedLineData = Object.values(lineDataMap).sort((a, b) => { return ( logLevelColorOrder.findIndex(color => color === a.color) - - logLevelColorOrder.findIndex(color => color === b.color) + logLevelColorOrder.findIndex(color => color === b.color) || + (a.currentPeriodKey < b.currentPeriodKey + ? -1 + : a.currentPeriodKey > b.currentPeriodKey + ? 1 + : 0) ); }); diff --git a/packages/app/src/__tests__/ChartUtils.test.ts b/packages/app/src/__tests__/ChartUtils.test.ts index 54fc44697c..78c70e0503 100644 --- a/packages/app/src/__tests__/ChartUtils.test.ts +++ b/packages/app/src/__tests__/ChartUtils.test.ts @@ -69,6 +69,32 @@ describe('ChartUtils', () => { ); }); + it('should assign the same color to a series regardless of row order', () => { + const meta = [ + { name: 'count()', type: 'UInt64' }, + { name: 'ServiceName', type: 'String' }, + { name: '__hdx_time_bucket', type: 'DateTime' }, + ]; + const row = (ServiceName: string) => ({ + 'count()': 1, + ServiceName, + __hdx_time_bucket: '2025-11-26T11:12:00Z', + }); + const colorsByService = (services: string[]) => + Object.fromEntries( + formatResponseForTimeChart({ + currentPeriodResponse: { data: services.map(row), meta }, + dateRange: [new Date(), new Date()], + granularity: '1 minute', + generateEmptyBuckets: false, + }).lineData.map(line => [line.dataKey, line.color]), + ); + + const colors = colorsByService(['cart', 'checkout', 'email']); + expect(new Set(Object.values(colors)).size).toBe(3); + expect(colorsByService(['email', 'cart', 'checkout'])).toEqual(colors); + }); + it('should return empty results for an empty response', () => { const res = { data: [], @@ -252,16 +278,6 @@ describe('ChartUtils', () => { }, { color: COLORS[1], - dataKey: 'max · checkout', - currentPeriodKey: 'max · checkout', - previousPeriodKey: 'max · checkout (previous)', - displayName: 'max · checkout', - valueColumnName: 'max', - groupValues: ['checkout'], - isDashed: false, - }, - { - color: COLORS[2], dataKey: 'AVG(toFloat64OrDefault(toString(Duration))) · shipping', currentPeriodKey: 'AVG(toFloat64OrDefault(toString(Duration))) · shipping', @@ -272,6 +288,16 @@ describe('ChartUtils', () => { groupValues: ['shipping'], isDashed: false, }, + { + color: COLORS[2], + dataKey: 'max · checkout', + currentPeriodKey: 'max · checkout', + previousPeriodKey: 'max · checkout (previous)', + displayName: 'max · checkout', + valueColumnName: 'max', + groupValues: ['checkout'], + isDashed: false, + }, { color: COLORS[3], dataKey: 'max · shipping', @@ -334,16 +360,6 @@ describe('ChartUtils', () => { }); expect(actual.lineData).toEqual([ - { - color: SEMANTIC_INFO_HEX, - dataKey: 'info', - currentPeriodKey: 'info', - previousPeriodKey: 'info (previous)', - displayName: 'info', - valueColumnName: 'count()', - groupValues: ['info'], - isDashed: false, - }, { color: SEMANTIC_INFO_HEX, dataKey: 'debug', @@ -354,6 +370,16 @@ describe('ChartUtils', () => { groupValues: ['debug'], isDashed: false, }, + { + color: SEMANTIC_INFO_HEX, + dataKey: 'info', + currentPeriodKey: 'info', + previousPeriodKey: 'info (previous)', + displayName: 'info', + valueColumnName: 'count()', + groupValues: ['info'], + isDashed: false, + }, { color: SEMANTIC_ERROR_HEX, dataKey: 'error', @@ -457,16 +483,6 @@ describe('ChartUtils', () => { }, { color: COLORS[1], - dataKey: 'max · checkout', - currentPeriodKey: 'max · checkout', - previousPeriodKey: 'max · checkout (previous)', - displayName: 'max · checkout', - valueColumnName: 'max', - groupValues: ['checkout'], - isDashed: false, - }, - { - color: COLORS[2], dataKey: 'AVG(toFloat64OrDefault(toString(Duration))) · shipping', currentPeriodKey: 'AVG(toFloat64OrDefault(toString(Duration))) · shipping', @@ -477,6 +493,16 @@ describe('ChartUtils', () => { groupValues: ['shipping'], isDashed: false, }, + { + color: COLORS[2], + dataKey: 'max · checkout', + currentPeriodKey: 'max · checkout', + previousPeriodKey: 'max · checkout (previous)', + displayName: 'max · checkout', + valueColumnName: 'max', + groupValues: ['checkout'], + isDashed: false, + }, { color: COLORS[3], dataKey: 'max · shipping', From 3a10f625f11b85b50bd18abd56ee77bb1d8a9d0b Mon Sep 17 00:00:00 2001 From: "Javier O." Date: Tue, 17 Nov 2026 21:51:34 +0100 Subject: [PATCH 29/55] fix(app): select the source selector label on click so typing replaces it (#3696) ## Summary The source selector is a searchable Mantine Select, and clicking it puts the caret wherever the pointer lands inside the current label. Typing `Data plane` over `ControlPlane Logs` produces `ControlData planePlane Logs`, the dropdown filters to nothing, and the user has to clear the box by hand before every switch. This PR selects the whole label on the click that focuses the selector, so typing replaces it. **A second click into an already focused selector places the caret as usual**, and Escape or clicking away still restores the previous label. The handlers live in `useSelectAllOnFocus` and only `SourceSelectControlled` uses them, so the aggregation, database, table and filter dropdowns are unchanged. A unit test pins replace-on-click and the second-click caret. ### Screenshots or video Not captured: this change was made without a browser. A short video of click-then-type on the source box shows it best. | Before | After | | :----- | :---- | | Search---Observability-ezgif com-video-to-gif-converter | Search---ClickStacknew-ezgif com-video-to-gif-converter | ### How to reproduce **Starting point:** https://play.hyperdx.io/search, or `yarn app:dev:local` connected to the demo server. **On `main`:** 1. Click in the middle of the source selector text (placeholder **Data Source**), between two letters of the current source name. 2. Type `tra`. 3. The box shows the old name with `tra` inserted in the middle and the dropdown has no matching source. **On this branch:** 1. Click anywhere in the source selector text. 2. The whole name is highlighted. Type `tra`. 3. The box shows only `tra` and the dropdown lists the sources whose name or section contains it. 4. Click the box again: the caret lands where you clicked instead of selecting all. 5. Press Escape: the previous source name is back. ### How to test on Vercel preview **Preview routes:** /search **Steps:** 1. Click in the middle of the source selector input with placeholder **Data Source**. 2. Type `tra`. 3. Verify the input value is exactly `tra` and the dropdown lists at least one source whose name contains "Tra". 4. Press Escape and verify the input shows the previously selected source name again. ### References - Linear Issue: n/a - Related PRs: n/a --- .../source-select-select-all-on-focus.md | 6 ++++ packages/app/src/components/SourceSelect.tsx | 3 ++ .../__tests__/SourceSelect.test.tsx | 32 ++++++++++++++++- packages/app/src/hooks/useSelectAllOnFocus.ts | 34 +++++++++++++++++++ 4 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 .changeset/source-select-select-all-on-focus.md create mode 100644 packages/app/src/hooks/useSelectAllOnFocus.ts diff --git a/.changeset/source-select-select-all-on-focus.md b/.changeset/source-select-select-all-on-focus.md new file mode 100644 index 0000000000..ef5c4aca48 --- /dev/null +++ b/.changeset/source-select-select-all-on-focus.md @@ -0,0 +1,6 @@ +--- +'@hyperdx/app': patch +--- + +fix: clicking the source selector selects its current label so typing replaces +it instead of inserting into the middle of the old name diff --git a/packages/app/src/components/SourceSelect.tsx b/packages/app/src/components/SourceSelect.tsx index c17bfae308..2d5baeb780 100644 --- a/packages/app/src/components/SourceSelect.tsx +++ b/packages/app/src/components/SourceSelect.tsx @@ -27,6 +27,7 @@ import { useFilteredSortedSourceItems, useSourceKindMap, } from '@/components/sourceSelectUtils'; +import { useSelectAllOnFocus } from '@/hooks/useSelectAllOnFocus'; import { useSources } from '@/source'; import styles from '@styles/SourceSelectControlled.module.scss'; @@ -192,6 +193,7 @@ function SourceSelectControlledComponent({ ); const sourceKindMap = useSourceKindMap(data); + const selectAllOnFocus = useSelectAllOnFocus(); // Mantine passes `checked` to renderOption for the currently selected // option; render a trailing check so the active source is obvious in the @@ -249,6 +251,7 @@ function SourceSelectControlledComponent({ renderOption={renderOption} filter={sourceSelectFilter} searchable + {...selectAllOnFocus} placeholder="Data Source" leftSection={leftIcon} maxDropdownHeight={280} diff --git a/packages/app/src/components/__tests__/SourceSelect.test.tsx b/packages/app/src/components/__tests__/SourceSelect.test.tsx index 85414ef9a8..de098a16cf 100644 --- a/packages/app/src/components/__tests__/SourceSelect.test.tsx +++ b/packages/app/src/components/__tests__/SourceSelect.test.tsx @@ -183,10 +183,14 @@ describe('SourceSelectControlled (grouped rendering + tag-style search)', () => function SelectHarness({ isSourceAllowed, + defaultSource, }: { isSourceAllowed?: (source: TSource) => boolean; + defaultSource?: string; } = {}) { - const { control } = useForm(); + const { control } = useForm({ + defaultValues: { source: defaultSource }, + }); return ( expect(screen.queryByText('Control Plane Prod')).not.toBeInTheDocument(); }); + it('selects the current label on a focusing click so typing replaces it', async () => { + asMock(useSources).mockReturnValue({ data: SECTIONED_SOURCES }); + renderWithMantine(); + const input = screen.getByPlaceholderText('Data Source'); + expect(input).toHaveValue('Billing Logs'); + + await userEvent.click(input); + expect(input.selectionStart).toBe(0); + expect(input.selectionEnd).toBe('Billing Logs'.length); + + await userEvent.keyboard('prod'); + expect(input).toHaveValue('prod'); + expect(await screen.findByText('Prod Logs')).toBeInTheDocument(); + expect(screen.queryByText('Billing Logs')).not.toBeInTheDocument(); + }); + + it('places the caret normally on a click into an already focused input', async () => { + asMock(useSources).mockReturnValue({ data: SECTIONED_SOURCES }); + renderWithMantine(); + const input = screen.getByPlaceholderText('Data Source'); + + await userEvent.click(input); + await userEvent.click(input); + expect(input.selectionStart).toBe(input.selectionEnd); + }); + it('hides sources rejected by isSourceAllowed, along with sections left empty', async () => { asMock(useSources).mockReturnValue({ data: SECTIONED_SOURCES }); renderWithMantine( diff --git a/packages/app/src/hooks/useSelectAllOnFocus.ts b/packages/app/src/hooks/useSelectAllOnFocus.ts new file mode 100644 index 0000000000..2761bf4b3b --- /dev/null +++ b/packages/app/src/hooks/useSelectAllOnFocus.ts @@ -0,0 +1,34 @@ +import { MouseEvent, useCallback, useRef } from 'react'; +import type { FocusEvent } from 'react'; + +const selectAll = (input: HTMLInputElement) => + input.setSelectionRange(0, input.value.length); + +/** + * Handlers that select a text input's whole value when it gains focus, so + * typing replaces the value instead of inserting at the click point. + * + * Browsers collapse the selection to the pointer position on the mouseup + * that completes a focusing click, so that mouseup is cancelled. A click on + * an input that already has focus places the caret as usual. + */ +export function useSelectAllOnFocus() { + const focusingByMouseRef = useRef(false); + + const onMouseDown = useCallback((event: MouseEvent) => { + focusingByMouseRef.current = document.activeElement !== event.currentTarget; + }, []); + + const onMouseUp = useCallback((event: MouseEvent) => { + if (!focusingByMouseRef.current) return; + focusingByMouseRef.current = false; + event.preventDefault(); + selectAll(event.currentTarget); + }, []); + + const onFocus = useCallback((event: FocusEvent) => { + selectAll(event.currentTarget); + }, []); + + return { onFocus, onMouseDown, onMouseUp }; +} From 6256667e1106fd45177faa6084fab8fbf7cb9405 Mon Sep 17 00:00:00 2001 From: Brandon Pereira Date: Tue, 17 Nov 2026 15:06:50 -0600 Subject: [PATCH 30/55] fix(mcp): shorten trace_top_time_consuming_operations to trace_top_time_consuming_ops (#3698) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Renames the MCP tool `clickstack_trace_top_time_consuming_operations` (46 chars) to `clickstack_trace_top_time_consuming_ops` (39 chars). It was our longest tool name. Some MCP clients cap tool name length (and many prefix the server name on top), so the long name could be truncated or rejected. The shorter name keeps it inside the safe range for most clients. Updates the registration, error message, cross-references in other tool descriptions, integration tests, and `MCP.md`. Historical CHANGELOG entries are left as-is. **Breaking for callers using the old name** — agents discover tools via `tools/list`, so most clients pick up the new name automatically. ### How to reproduce **Starting point:** `yarn dev`, connect an MCP client to the API's `/mcp` endpoint. **On `main`:** 1. List tools; `clickstack_trace_top_time_consuming_operations` is present. **On this branch:** 1. List tools; `clickstack_trace_top_time_consuming_ops` is present and behaves the same. ### How to test on Vercel preview N/A — non-UI change. --- .changeset/mcp-shorten-trace-ops-tool-name.md | 9 ++ MCP.md | 139 +++++++++--------- .../api/src/mcp/__tests__/trace.int.test.ts | 39 +++-- .../api/src/mcp/tools/query/builderCatalog.ts | 2 +- .../mcp/tools/query/serviceHealth/index.ts | 2 +- packages/api/src/mcp/tools/trace/breakdown.ts | 6 +- packages/api/src/mcp/tools/trace/waterfall.ts | 2 +- 7 files changed, 108 insertions(+), 91 deletions(-) create mode 100644 .changeset/mcp-shorten-trace-ops-tool-name.md diff --git a/.changeset/mcp-shorten-trace-ops-tool-name.md b/.changeset/mcp-shorten-trace-ops-tool-name.md new file mode 100644 index 0000000000..12153bc44e --- /dev/null +++ b/.changeset/mcp-shorten-trace-ops-tool-name.md @@ -0,0 +1,9 @@ +--- +'@hyperdx/api': patch +--- + +fix(mcp): Rename `clickstack_trace_top_time_consuming_operations` to `clickstack_trace_top_time_consuming_ops` + +The old name was the longest MCP tool name and exceeded the tool-name length +limit some MCP clients enforce. Clients that call the tool by its old name +need to switch to the new one. diff --git a/MCP.md b/MCP.md index b5b070344d..57ec8dfdfb 100644 --- a/MCP.md +++ b/MCP.md @@ -134,56 +134,59 @@ with: ## Available Tools -| Tool | Description | -| ----------------------------- | -------------------------------------------------------------------------------------------- | -| `clickstack_list_sources` | List all data sources and connections as a lightweight catalog (IDs, names, kinds) | -| `clickstack_describe_source` | Full column schema, attribute keys, sampled low-cardinality values, and a round-trippable `config` block (the exact shape `clickstack_save_source` accepts, incl. correlation IDs) for a single source; for metric sources also returns a per-kind metric-name sample | -| `clickstack_describe_table` | Inspect a ClickHouse table that is not a registered source: columns, keys, engine, skipping indices, approximate size, and an optional row sample. Without a table, lists the tables in a database (paginated) | -| `clickstack_save_source` | Create (omit id) or update (provide id) a data source (log, trace, session, metric, or promql) so shipped telemetry becomes queryable. To clone a source, read its `config` from `clickstack_describe_source`, drop `id`, and pass it here | -| `clickstack_delete_source` | Permanently delete a data source by ID | -| `clickstack_list_metrics` | Paginated catalog of metric names on a metric source with optional kind / namePattern / time-window filters | -| `clickstack_describe_metric` | Per-metric drill-down: kind(s), unit, description, attribute keys per map column, and sampled values | -| `clickstack_service_health` | One-call service health on a trace source: throughput, error rate, p50/p95 and top errors per service, compared with yesterday and ranked worst first | -| `clickstack_timeseries` | Plot metrics over time as a line or stacked bar chart (works on log, trace, and metric sources) | -| `clickstack_table` | Compute aggregated metrics as a table, single number, or pie chart (works on log, trace, and metric sources) | -| `clickstack_search` | Browse individual log, event, or trace rows | -| `clickstack_event_patterns` | Discover the most common log messages and event patterns using Drain clustering | -| `clickstack_event_deltas` | Compare two row groups and rank properties by how their value distributions differ | -| `clickstack_emerging_signals` | Detect NEW or GONE log/event patterns between a baseline and a current window (two-window Drain novelty diff) | -| `clickstack_sql` | Execute raw ClickHouse SQL for advanced queries (JOINs, CTEs, sub-queries); pass `queries` to run up to 10 in parallel | -| `clickstack_promql` | Run a PromQL expression (range or instant) against a PromQL source. Only registered when PromQL is enabled | -| `clickstack_get_dashboard` | List all dashboards or get full detail for a specific dashboard | -| `clickstack_save_dashboard` | Create or update a dashboard with tiles (charts, tables, numbers, search, markdown) | -| `clickstack_delete_dashboard` | Permanently delete a dashboard and its attached alerts | -| `clickstack_query_tile` | Execute the query for a specific dashboard tile to validate results | -| `clickstack_query_tiles` | Batch-validate many dashboard tiles in one call, returning a per-tile success/failure summary | -| `clickstack_get_saved_search` | List all saved searches or get full detail for a specific saved search | -| `clickstack_save_saved_search` | Create or update a saved search (reusable query against a data source) | -| `clickstack_get_alert` | List alerts (summary) or get full detail with evaluation history; filter by state | -| `clickstack_save_alert` | Create a new alert or update an existing one | -| `clickstack_trace_waterfall` | Fetch all spans in a single trace as a parent/child waterfall tree with optional correlated logs | -| `clickstack_trace_top_time_consuming_operations` | Aggregate breakdown of child operations by cumulative time across matching parent traces | -| `clickstack_get_webhook` | List available webhook destinations for use as alert notification channels | -| `clickstack_save_webhook` | Create (omit id) or update (provide id) a webhook notification destination (slack, generic, or incidentio) | -| `clickstack_delete_webhook` | Permanently delete a webhook by ID (blocked while alerts still reference it) | +| Tool | Description | +| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `clickstack_list_sources` | List all data sources and connections as a lightweight catalog (IDs, names, kinds) | +| `clickstack_describe_source` | Full column schema, attribute keys, sampled low-cardinality values, and a round-trippable `config` block (the exact shape `clickstack_save_source` accepts, incl. correlation IDs) for a single source; for metric sources also returns a per-kind metric-name sample | +| `clickstack_describe_table` | Inspect a ClickHouse table that is not a registered source: columns, keys, engine, skipping indices, approximate size, and an optional row sample. Without a table, lists the tables in a database (paginated) | +| `clickstack_save_source` | Create (omit id) or update (provide id) a data source (log, trace, session, metric, or promql) so shipped telemetry becomes queryable. To clone a source, read its `config` from `clickstack_describe_source`, drop `id`, and pass it here | +| `clickstack_delete_source` | Permanently delete a data source by ID | +| `clickstack_list_metrics` | Paginated catalog of metric names on a metric source with optional kind / namePattern / time-window filters | +| `clickstack_describe_metric` | Per-metric drill-down: kind(s), unit, description, attribute keys per map column, and sampled values | +| `clickstack_service_health` | One-call service health on a trace source: throughput, error rate, p50/p95 and top errors per service, compared with yesterday and ranked worst first | +| `clickstack_timeseries` | Plot metrics over time as a line or stacked bar chart (works on log, trace, and metric sources) | +| `clickstack_table` | Compute aggregated metrics as a table, single number, or pie chart (works on log, trace, and metric sources) | +| `clickstack_search` | Browse individual log, event, or trace rows | +| `clickstack_event_patterns` | Discover the most common log messages and event patterns using Drain clustering | +| `clickstack_event_deltas` | Compare two row groups and rank properties by how their value distributions differ | +| `clickstack_emerging_signals` | Detect NEW or GONE log/event patterns between a baseline and a current window (two-window Drain novelty diff) | +| `clickstack_sql` | Execute raw ClickHouse SQL for advanced queries (JOINs, CTEs, sub-queries); pass `queries` to run up to 10 in parallel | +| `clickstack_promql` | Run a PromQL expression (range or instant) against a PromQL source. Only registered when PromQL is enabled | +| `clickstack_get_dashboard` | List all dashboards or get full detail for a specific dashboard | +| `clickstack_save_dashboard` | Create or update a dashboard with tiles (charts, tables, numbers, search, markdown) | +| `clickstack_delete_dashboard` | Permanently delete a dashboard and its attached alerts | +| `clickstack_query_tile` | Execute the query for a specific dashboard tile to validate results | +| `clickstack_query_tiles` | Batch-validate many dashboard tiles in one call, returning a per-tile success/failure summary | +| `clickstack_get_saved_search` | List all saved searches or get full detail for a specific saved search | +| `clickstack_save_saved_search` | Create or update a saved search (reusable query against a data source) | +| `clickstack_get_alert` | List alerts (summary) or get full detail with evaluation history; filter by state | +| `clickstack_save_alert` | Create a new alert or update an existing one | +| `clickstack_trace_waterfall` | Fetch all spans in a single trace as a parent/child waterfall tree with optional correlated logs | +| `clickstack_trace_top_time_consuming_ops` | Aggregate breakdown of child operations by cumulative time across matching parent traces | +| `clickstack_get_webhook` | List available webhook destinations for use as alert notification channels | +| `clickstack_save_webhook` | Create (omit id) or update (provide id) a webhook notification destination (slack, generic, or incidentio) | +| `clickstack_delete_webhook` | Permanently delete a webhook by ID (blocked while alerts still reference it) | > **Maintainers:** when adding/removing/renaming a query tool, update this table > and — for builder (non-SQL) tools — the hand-curated `BUILDER_TOOLS_LIST` in -> `packages/api/src/mcp/tools/query/builderCatalog.ts`. It isn't auto-derived, so -> it drifts silently. +> `packages/api/src/mcp/tools/query/builderCatalog.ts`. It isn't auto-derived, +> so it drifts silently. ### Metric Sources `clickstack_timeseries`, `clickstack_table`, and the dashboard builder tile -tools accept metric sources transparently. Each `select` item on a metric -query must set `metricType` (`"gauge"`, `"sum"`, `"histogram"`, or -`"exponential histogram"`) and -`metricName` (the OTel metric name, e.g. `system.cpu.utilization`). -`valueExpression` defaults to `"Value"` when omitted, so a typical metric -series looks like: +tools accept metric sources transparently. Each `select` item on a metric query +must set `metricType` (`"gauge"`, `"sum"`, `"histogram"`, or +`"exponential histogram"`) and `metricName` (the OTel metric name, e.g. +`system.cpu.utilization`). `valueExpression` defaults to `"Value"` when omitted, +so a typical metric series looks like: ```jsonc -{ "aggFn": "avg", "metricType": "gauge", "metricName": "system.cpu.utilization" } +{ + "aggFn": "avg", + "metricType": "gauge", + "metricName": "system.cpu.utilization", +} ``` Per-kind aggregation guidance: @@ -191,36 +194,34 @@ Per-kind aggregation guidance: - **Gauge**: `avg`, `last_value`, `min`, or `max`. Set `"isDelta": true` for Prometheus-style delta over each bucket. - **Sum (counter)**: `"increase"` returns the per-bucket counter increase - (reset-aware), or `sum` / `avg` on the computed rate. `increase` combined - with `groupBy` is capped at the top 20 groups by the renderer; the tool - emits a neutral hint when the cap may apply. + (reset-aware), or `sum` / `avg` on the computed rate. `increase` combined with + `groupBy` is capped at the top 20 groups by the renderer; the tool emits a + neutral hint when the cap may apply. - **Histogram**: `"quantile"` with `level` ∈ {0.5, 0.9, 0.95, 0.99} for percentiles, or `"count"` for the total bucket count. -- **Exponential histogram**: `"quantile"` with `level` ∈ - {0.5, 0.9, 0.95, 0.99} for percentiles, or `"count"` for the total bucket - count. +- **Exponential histogram**: `"quantile"` with `level` ∈ {0.5, 0.9, 0.95, 0.99} + for percentiles, or `"count"` for the total bucket count. `summary` metrics are not yet supported by the query renderer. Discovery workflow for metrics: -1. `clickstack_list_sources` to find the metric source ID and its - `metricTables` map. -2. `clickstack_describe_source` to see columns, attribute keys, and a - per-kind metric-name sample. -3. `clickstack_list_metrics` for paginated catalog access with optional - kind / namePattern / time-window filters; pass `nextCursor` unchanged - for the next page. -4. `clickstack_describe_metric` to drill into a specific metric and - discover its attribute keys + sampled values before authoring queries. +1. `clickstack_list_sources` to find the metric source ID and its `metricTables` + map. +2. `clickstack_describe_source` to see columns, attribute keys, and a per-kind + metric-name sample. +3. `clickstack_list_metrics` for paginated catalog access with optional kind / + namePattern / time-window filters; pass `nextCursor` unchanged for the next + page. +4. `clickstack_describe_metric` to drill into a specific metric and discover its + attribute keys + sampled values before authoring queries. 5. `clickstack_timeseries` / `clickstack_table` to chart the metric. ### PromQL Sources Available when PromQL is enabled for the deployment (self-hosted: the API's -`ENABLE_PROMQL` setting). With it off, PromQL sources, tiles, label filters, -the `clickstack_promql` tool and the PromQL prompt sections are all hidden -from MCP. +`ENABLE_PROMQL` setting). With it off, PromQL sources, tiles, label filters, the +`clickstack_promql` tool and the PromQL prompt sections are all hidden from MCP. A source with `kind: "promql"` holds Prometheus metrics, either on a Prometheus-compatible endpoint or in a ClickHouse `TimeSeries` table. The @@ -231,23 +232,23 @@ builder tools do not read it; use PromQL: 2. `clickstack_describe_source` lists its metric names and label names. 3. `clickstack_promql` runs an expression. A `range` query (default) returns `{ __hdx_time_bucket, series_name, value }` rows plus `seriesLabels`; an - `instant` query evaluates at `endTime` and returns one row per series with - a column per label. `granularity` sets the step and `$__interval` in the - same `" "` format PromQL tiles use. + `instant` query evaluates at `endTime` and returns one row per series with a + column per label. `granularity` sets the step and `$__interval` in the same + `" "` format PromQL tiles use. 4. `clickstack_save_dashboard` with a `configType: "promql"` tile keeps the - chart; `clickstack_query_tile` returns the same rows for the same - expression and granularity. `PROMETHEUS_LABEL` filters give the dashboard - a label dropdown that tiles reference as `{job=~"$job"}`. + chart; `clickstack_query_tile` returns the same rows for the same expression + and granularity. `PROMETHEUS_LABEL` filters give the dashboard a label + dropdown that tiles reference as `{job=~"$job"}`. ```jsonc { "sourceId": "", "expression": "sum by (job) (rate(http_requests_total[$__rate_interval]))", "startTime": "2026-01-01T00:00:00Z", - "endTime": "2026-01-01T01:00:00Z" + "endTime": "2026-01-01T01:00:00Z", } ``` -The `$__interval`, `$__rate_interval` and `$__range` macros expand as they do -in a PromQL tile. Dashboard variables do not resolve in `clickstack_promql`; -write the value inline. +The `$__interval`, `$__rate_interval` and `$__range` macros expand as they do in +a PromQL tile. Dashboard variables do not resolve in `clickstack_promql`; write +the value inline. diff --git a/packages/api/src/mcp/__tests__/trace.int.test.ts b/packages/api/src/mcp/__tests__/trace.int.test.ts index 722af8b2bd..3c72c04393 100644 --- a/packages/api/src/mcp/__tests__/trace.int.test.ts +++ b/packages/api/src/mcp/__tests__/trace.int.test.ts @@ -159,6 +159,13 @@ describe('MCP Trace Tools', () => { // ─── Schema serialization ────────────────────────────────────────────────── describe('schema serialization', () => { + // Some MCP clients cap tool name length, often after prefixing the server name. + it('should keep every tool name within 40 characters', async () => { + const { tools } = await client.listTools(); + const tooLong = tools.map(t => t.name).filter(name => name.length > 40); + expect(tooLong).toEqual([]); + }); + it('should expose clickstack_trace_waterfall with expected properties', async () => { const { tools } = await client.listTools(); const tool = tools.find(t => t.name === 'clickstack_trace_waterfall'); @@ -174,10 +181,10 @@ describe('MCP Trace Tools', () => { expect(tool!.inputSchema.required).toContain('sourceId'); }); - it('should expose clickstack_trace_top_time_consuming_operations with expected properties', async () => { + it('should expose clickstack_trace_top_time_consuming_ops with expected properties', async () => { const { tools } = await client.listTools(); const tool = tools.find( - t => t.name === 'clickstack_trace_top_time_consuming_operations', + t => t.name === 'clickstack_trace_top_time_consuming_ops', ); expect(tool).toBeDefined(); @@ -1050,13 +1057,13 @@ describe('MCP Trace Tools', () => { }); }); - // ─── clickstack_trace_top_time_consuming_operations ─────────────────────────── + // ─── clickstack_trace_top_time_consuming_ops ─────────────────────────── - describe('clickstack_trace_top_time_consuming_operations', () => { + describe('clickstack_trace_top_time_consuming_ops', () => { it('should return error for non-existent source', async () => { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: '000000000000000000000000', parentFilter: "ServiceName = 'api-gateway'", @@ -1071,7 +1078,7 @@ describe('MCP Trace Tools', () => { it('should return error for non-trace source', async () => { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: logSource._id.toString(), parentFilter: "ServiceName = 'api-gateway'", @@ -1086,7 +1093,7 @@ describe('MCP Trace Tools', () => { it('should return error for invalid time range', async () => { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: traceSource._id.toString(), parentFilter: "ServiceName = 'api-gateway'", @@ -1101,7 +1108,7 @@ describe('MCP Trace Tools', () => { it('should return empty operations when no traces match', async () => { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: traceSource._id.toString(), parentFilter: "ServiceName = 'nonexistent-service'", @@ -1208,7 +1215,7 @@ describe('MCP Trace Tools', () => { it('should break down child operations ranked by total time', async () => { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: traceSource._id.toString(), parentFilter: `ServiceName = '${PARENT_SVC}' AND SpanName = '${PARENT_OP}'`, @@ -1245,7 +1252,7 @@ describe('MCP Trace Tools', () => { // Only trace 2 has a parent >= 850ms (900ms) const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: traceSource._id.toString(), parentFilter: `ServiceName = '${PARENT_SVC}' AND SpanName = '${PARENT_OP}'`, @@ -1270,7 +1277,7 @@ describe('MCP Trace Tools', () => { it('should respect topN parameter', async () => { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: traceSource._id.toString(), parentFilter: `ServiceName = '${PARENT_SVC}' AND SpanName = '${PARENT_OP}'`, @@ -1295,7 +1302,7 @@ describe('MCP Trace Tools', () => { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: traceSource._id.toString(), parentFilter: `ServiceName = '${PARENT_SVC}' AND SpanName = '${PARENT_OP}'`, @@ -1320,7 +1327,7 @@ describe('MCP Trace Tools', () => { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: traceSource._id.toString(), parentFilter: `ServiceName = '${PARENT_SVC}' AND SpanName = '${PARENT_OP}'`, @@ -1340,7 +1347,7 @@ describe('MCP Trace Tools', () => { it('should return error for invalid parentFilter SQL', async () => { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: traceSource._id.toString(), parentFilter: 'INVALID SQL @@@ SYNTAX', @@ -1370,7 +1377,7 @@ describe('MCP Trace Tools', () => { try { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: traceSource._id.toString(), parentFilter: `ServiceName = '${PARENT_SVC}' AND SpanName = '${PARENT_OP}'`, @@ -1438,7 +1445,7 @@ describe('MCP Trace Tools', () => { try { const result = await callTool( client, - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { sourceId: traceSource._id.toString(), parentFilter: `ServiceName = '${PARENT_SVC}' AND SpanName = '${PARENT_OP}'`, diff --git a/packages/api/src/mcp/tools/query/builderCatalog.ts b/packages/api/src/mcp/tools/query/builderCatalog.ts index ec195b744f..ff79e655d8 100644 --- a/packages/api/src/mcp/tools/query/builderCatalog.ts +++ b/packages/api/src/mcp/tools/query/builderCatalog.ts @@ -14,7 +14,7 @@ export const BUILDER_TOOLS_LIST = [ ' • clickstack_event_deltas — attributes that differ between two row groups', ' • clickstack_emerging_signals — patterns new or gone vs a baseline window', ' • clickstack_trace_waterfall — one trace as a parent/child span tree', - ' • clickstack_trace_top_time_consuming_operations — slowest child operations in a trace', + ' • clickstack_trace_top_time_consuming_ops — slowest child operations in a trace', ].join('\n'); /** When raw SQL is actually warranted. */ diff --git a/packages/api/src/mcp/tools/query/serviceHealth/index.ts b/packages/api/src/mcp/tools/query/serviceHealth/index.ts index d45d08258d..85cd563429 100644 --- a/packages/api/src/mcp/tools/query/serviceHealth/index.ts +++ b/packages/api/src/mcp/tools/query/serviceHealth/index.ts @@ -51,7 +51,7 @@ const DESCRIPTION = 'For a flagged service, check its own runtime metrics (memory, GC, CPU, ' + 'restarts by pod) on the metric source before blaming dependencies, then ' + 'use clickstack_event_deltas and ' + - 'clickstack_trace_top_time_consuming_operations.\n\n' + + 'clickstack_trace_top_time_consuming_ops.\n\n' + 'CALIBRATION: flags fire only past fixed thresholds (see `usage` in the ' + 'response); smaller swings are usually normal variance, and no flags is ' + 'a valid result for a routine check. Thresholds apply to service-wide ' + diff --git a/packages/api/src/mcp/tools/trace/breakdown.ts b/packages/api/src/mcp/tools/trace/breakdown.ts index e480c2a566..ea4e0c5a6f 100644 --- a/packages/api/src/mcp/tools/trace/breakdown.ts +++ b/packages/api/src/mcp/tools/trace/breakdown.ts @@ -1,5 +1,5 @@ /** - * clickstack_trace_top_time_consuming_operations + * clickstack_trace_top_time_consuming_ops * * Aggregate counterpart to clickstack_trace_waterfall. Given a parent-span * filter (a service + operation, optionally constrained to slow durations), @@ -62,7 +62,7 @@ export function registerTraceBreakdown({ const { teamId } = context; registerTool( - 'clickstack_trace_top_time_consuming_operations', + 'clickstack_trace_top_time_consuming_ops', { title: 'Top Time-Consuming Operations Across Matching Traces', annotations: READ_ONLY_TOOL, @@ -86,7 +86,7 @@ export function registerTraceBreakdown({ } if (source.kind !== SourceKind.Trace) { return mcpUserError( - `Source ${input.sourceId} is kind="${source.kind}". clickstack_trace_top_time_consuming_operations requires a source of kind="trace".`, + `Source ${input.sourceId} is kind="${source.kind}". clickstack_trace_top_time_consuming_ops requires a source of kind="trace".`, ); } diff --git a/packages/api/src/mcp/tools/trace/waterfall.ts b/packages/api/src/mcp/tools/trace/waterfall.ts index 46d9125a1c..e7760f6be2 100644 --- a/packages/api/src/mcp/tools/trace/waterfall.ts +++ b/packages/api/src/mcp/tools/trace/waterfall.ts @@ -318,7 +318,7 @@ export function registerTraceWaterfall({ "instead of writing TraceId self-JOINs in raw SQL; it uses the source's " + 'configured trace, span, and parent-span ID expressions.\n\n' + 'NOT FOR AGGREGATE QUESTIONS. "Where does the time go across many slow traces ' + - 'of operation X" is clickstack_trace_top_time_consuming_operations, called ' + + 'of operation X" is clickstack_trace_top_time_consuming_ops, called ' + 'once per (service, operation) with minParentDurationMs. Use this tool for a ' + 'single concrete example, typically after that breakdown has pointed at a ' + 'suspicious operation.\n\n' + From 3c8794f2ca6e1a986c0c6176f2f914ef4c2c6e94 Mon Sep 17 00:00:00 2001 From: Mike Shi Date: Tue, 17 Nov 2026 14:56:08 -0800 Subject: [PATCH 31/55] fix(app): dedupe Y-axis tick labels on stacked time charts (#3699) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Stacked bar and stacked line charts could show the same Y-axis label twice. With a "Number" format at 0 decimals and a stack that reaches 2000, the axis rendered `0, 500, 1k, 2k, 2k`, because 1500 rounds to "2k". Line charts already avoid this: `computeYAxisBounds` picks nice ticks and escalates precision when two labels collide. Stacked charts returned early from it and left ticks to Recharts, because the function only scanned per-series values, not stack heights. The label formatter then rounded Recharts' ticks with nothing checking for collisions. This PR: - Adds `scanStackedYAxisValueRange`, which computes the axis extent from each row's running sums. This matches how Recharts stacks with its default `stackOffset="none"` (each series sits on the previous one's top, null counts as 0, zero baseline included). - Sends stacked charts through the same zero-pinned tick path the default line chart uses, so they get the same distinct-label handling. Stacked charts stay pinned at zero whatever the fit-to-data setting, which is documented as line-only. - Leaves stacked charts with a reference line on Recharts' auto ticks, as line charts already do in that branch. That path can still collide, and this PR doesn't change it. ### Screenshots or video Same dashboard tile (raw SQL, stacked bar, 1200 + 800 per bucket, Number format, 0 decimals). | Before | After | | :----- | :---- | | ![Before: 0, 500, 1k, 2k, 2k](https://cursor.com/artifacts/c/art-7427da94-0a3f-48ef-83e9-bfd7b9f9d866) | ![After: 0, 500, 1k, 1.5k, 2k](https://cursor.com/artifacts/c/art-fab6090d-2ead-4d61-888c-1a2668dca68a) | ### How to reproduce **Starting point:** `yarn app:dev:local` connected to the demo server (onboarding → "Connect to Demo Server"). **On `main`:** 1. Go to Dashboards, create a dashboard, and add a tile. 2. Switch the tile to raw SQL (time series) and enter: `SELECT toStartOfInterval(now() - INTERVAL number MINUTE, INTERVAL {intervalSeconds:Int64} SECOND) AS ts, any(toFloat64(1200)) AS a, any(toFloat64(800)) AS b FROM numbers(60) GROUP BY ts ORDER BY ts` 3. Keep display type as stacked bar. In display settings, set the number format to "Number" with 0 decimals. 4. Set the time range to the last hour and save the tile. The Y axis reads `0, 500, 1k, 2k, 2k`. **On this branch:** 1. Same steps. The Y axis reads `0, 500, 1k, 1.5k, 2k`. ### How to test on Vercel preview **Preview routes:** /dashboards **Steps:** 1. Create a new dashboard and click "Add" to add a tile. 2. Switch the tile to raw SQL time series and enter the SQL from "How to reproduce" above. 3. Choose the stacked bar display type, open display settings, set number format to "Number" with 0 decimals, and save the tile with a "last 1 hour" range. 4. Verify the Y-axis labels are `0, 500, 1k, 1.5k, 2k`, with no label repeated. ### References - Related PRs: #3172, #3162 (earlier distinct-tick work for line charts)
Open in Web Open in Cursor 
Co-authored-by: Cursor Agent <199161495+cursoragent@users.noreply.github.com> --- .changeset/stacked-chart-distinct-y-ticks.md | 6 + packages/app/src/HDXMultiSeriesTimeChart.tsx | 43 ++++-- .../__tests__/HDXMultiSeriesTimeChart.test.ts | 135 +++++++++++++----- 3 files changed, 143 insertions(+), 41 deletions(-) create mode 100644 .changeset/stacked-chart-distinct-y-ticks.md diff --git a/.changeset/stacked-chart-distinct-y-ticks.md b/.changeset/stacked-chart-distinct-y-ticks.md new file mode 100644 index 0000000000..3a9437cdf0 --- /dev/null +++ b/.changeset/stacked-chart-distinct-y-ticks.md @@ -0,0 +1,6 @@ +--- +'@hyperdx/app': patch +--- + +fix: stacked bar and stacked line charts no longer show duplicate Y-axis labels +(e.g. "0, 500, 1k, 2k, 2k" when 1.5k rounds to 2k) diff --git a/packages/app/src/HDXMultiSeriesTimeChart.tsx b/packages/app/src/HDXMultiSeriesTimeChart.tsx index 3de997cf70..a2cfecd200 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart.tsx +++ b/packages/app/src/HDXMultiSeriesTimeChart.tsx @@ -1134,6 +1134,32 @@ export function scanYAxisValueRange( return { min, max }; } +// Mirrors Recharts' stackOffset="none": each series sits on the running sum +// of the ones before it, starting from a zero baseline, and the axis must +// cover every one of those running sums. +export function scanStackedYAxisValueRange( + graphResults: any[], + lineData: LineData[], +): { min: number; max: number } { + let min = Infinity; + let max = -Infinity; + graphResults.forEach(dataPoint => { + let sum = 0; + lineData.forEach(ld => { + const value = dataPoint[ld.dataKey]; + if (typeof value === 'number' && !isNaN(value)) { + sum += value; + min = Math.min(min, sum); + max = Math.max(max, sum); + } + }); + }); + if (max === -Infinity) { + return { min, max }; + } + return { min: Math.min(min, 0), max: Math.max(max, 0) }; +} + export interface YAxisBounds { domain: AxisDomain; ticks: number[] | undefined; @@ -1168,8 +1194,6 @@ export function getLineCurveType( ]; } -// A stacked bar's rendered height sums its series at each timestamp - leave -// that entirely to Recharts, regardless of selection/fit-to-data state. export function computeYAxisBounds( graphResults: any[], visibleLineData: LineData[], @@ -1179,21 +1203,22 @@ export function computeYAxisBounds( referenceLineValues: number[], axisNumberFormat?: NumberFormat, ): YAxisBounds { - if ( + const isStacked = displayType === DisplayType.StackedBar || - displayType === DisplayType.StackedLine - ) { - return DEFAULT_Y_AXIS_BOUNDS; - } + displayType === DisplayType.StackedLine; const shouldFitYAxis = fitYAxisToData; - if (!hasSelection && !shouldFitYAxis) { + // Stacked charts always stay zero-pinned: fit-to-data is line-only, and a + // selection already narrows visibleLineData, so it changes the stack sums. + if (isStacked || (!hasSelection && !shouldFitYAxis)) { // A fully numeric domain skips Recharts' own nice rounding, and a // reference line can extend it further - defer to Recharts entirely. if (referenceLineValues.length > 0) { return DEFAULT_Y_AXIS_BOUNDS; } - const { min, max } = scanYAxisValueRange(graphResults, visibleLineData); + const { min, max } = isStacked + ? scanStackedYAxisValueRange(graphResults, visibleLineData) + : scanYAxisValueRange(graphResults, visibleLineData); if (max === -Infinity) { return DEFAULT_Y_AXIS_BOUNDS; } diff --git a/packages/app/src/__tests__/HDXMultiSeriesTimeChart.test.ts b/packages/app/src/__tests__/HDXMultiSeriesTimeChart.test.ts index 9a53c84384..f2dd15690c 100644 --- a/packages/app/src/__tests__/HDXMultiSeriesTimeChart.test.ts +++ b/packages/app/src/__tests__/HDXMultiSeriesTimeChart.test.ts @@ -24,6 +24,7 @@ import { getYAxisTicks, HARD_LINES_LIMIT, sameActiveClickSeries, + scanStackedYAxisValueRange, scanYAxisValueRange, } from '@/HDXMultiSeriesTimeChart'; import { COLORS } from '@/utils'; @@ -421,6 +422,39 @@ describe('scanYAxisValueRange', () => { }); }); +describe('scanStackedYAxisValueRange', () => { + const series = (dataKey: string): LineData => ({ + dataKey, + currentPeriodKey: dataKey, + previousPeriodKey: `${dataKey}.prev`, + displayName: dataKey, + valueColumnName: dataKey, + groupValues: [], + color: '#a', + }); + + it('spans every running sum of the stack, as Recharts draws it', () => { + // Recharts stacks each series on the previous one's top (stackOffset + // "none"), so a negative series can dip a segment below its baseline. + const lineData = [series('a'), series('b'), series('c')]; + const graphResults = [ + { a: 10, b: 30, c: -50 }, + { a: 5, c: 20 }, + ]; + expect(scanStackedYAxisValueRange(graphResults, lineData)).toEqual({ + min: -10, + max: 40, + }); + }); + + it('returns an empty range when no series has a numeric value', () => { + expect(scanStackedYAxisValueRange([{ a: null }], [series('a')])).toEqual({ + min: Infinity, + max: -Infinity, + }); + }); +}); + describe('computeYAxisBounds', () => { const series = (dataKey: string): LineData => ({ dataKey, @@ -536,40 +570,77 @@ describe('computeYAxisBounds', () => { expect(bounds).toEqual({ domain: [0, 'auto'], ticks: undefined }); }); - it('leaves a stacked bar`s max to Recharts, selection or not', () => { - // Regression: 60 and 40 individually reach a stack height of 100, not - // 63 - the guard must apply regardless of hasSelection. - const lineData = [series('a'), series('b')]; - const graphResults = [{ a: 60, b: 40 }]; - for (const hasSelection of [false, true]) { - expect( - computeYAxisBounds( - graphResults, - lineData, - hasSelection, - false, - DisplayType.StackedBar, - [], - ), - ).toEqual({ domain: [0, 'auto'], ticks: undefined }); - } + it.each([DisplayType.StackedBar, DisplayType.StackedLine])( + 'sizes a %s axis to the stack height, not the tallest series', + displayType => { + // 60 and 40 individually reach a stack height of 100, not 63. + const lineData = [series('a'), series('b')]; + const graphResults = [{ a: 60, b: 40 }]; + for (const hasSelection of [false, true]) { + expect( + computeYAxisBounds( + graphResults, + lineData, + hasSelection, + false, + displayType, + [], + ), + ).toEqual({ + domain: [0, 105], + ticks: [0, 25, 50, 75, 100], + tickFormatter: expect.any(Function), + }); + } + }, + ); + + it.each([DisplayType.StackedBar, DisplayType.StackedLine])( + 'never shows duplicate %s tick labels when 1.5k rounds to 2k', + displayType => { + // Regression: stacked charts deferred to Recharts' ticks, which + // rendered 0/500/1k/2k/2k for a 2000-high stack at 0 decimals. + const bounds = computeYAxisBounds( + [ + { a: 1200, b: 800 }, + { a: 600, b: 300 }, + ], + [series('a'), series('b')], + false, + false, + displayType, + [], + { output: 'number', mantissa: 0 }, + ); + const labels = bounds.ticks!.map(t => bounds.tickFormatter!(t)); + expect(labels).toEqual(['0', '500', '1k', '1.5k', '2k']); + }, + ); + + it('keeps a stacked axis pinned at zero even when fit-to-data is on', () => { + // Fit-to-data only applies to line charts; a stacked bar cut off above + // zero would misrepresent each segment's height. + const bounds = computeYAxisBounds( + [{ a: 900, b: 100 }], + [series('a'), series('b')], + false, + true, + DisplayType.StackedBar, + [], + ); + expect(bounds.domain).toEqual([0, 1050]); }); - it('leaves a stacked line`s max to Recharts, selection or not', () => { - const lineData = [series('a'), series('b')]; - const graphResults = [{ a: 60, b: 40 }]; - for (const hasSelection of [false, true]) { - expect( - computeYAxisBounds( - graphResults, - lineData, - hasSelection, - false, - DisplayType.StackedLine, - [], - ), - ).toEqual({ domain: [0, 'auto'], ticks: undefined }); - } + it('leaves a stacked axis with a reference line to Recharts', () => { + const bounds = computeYAxisBounds( + [{ a: 60, b: 40 }], + [series('a'), series('b')], + false, + false, + DisplayType.StackedBar, + [150], + ); + expect(bounds).toEqual({ domain: [0, 'auto'], ticks: undefined }); }); it('falls back to auto when there is no numeric data', () => { From a7744e82abf448d76a3d396a9ec27211efcd95d3 Mon Sep 17 00:00:00 2001 From: Drew Davis Date: Tue, 17 Nov 2026 20:11:39 -0500 Subject: [PATCH 32/55] feat: add data source and connection variable types to dashboards (#3651) --- .changeset/source-vars-1.md | 7 + .changeset/source-vars-2.md | 5 + .changeset/source-vars-3.md | 5 + .changeset/source-vars-4.md | 5 + .changeset/source-vars-5.md | 8 + packages/api/openapi.json | 214 ++++- packages/api/src/controllers/alerts.ts | 6 + .../dashboards/patchDashboard.int.test.ts | 82 ++ .../dashboards/queryTile.int.test.ts | 82 ++ .../dashboards/queryTiles.int.test.ts | 55 ++ .../dashboards/queryTilesHandler.test.ts | 9 + .../dashboards/saveDashboard.int.test.ts | 123 +++ .../__tests__/dashboards/validation.test.ts | 29 + .../__tests__/dashboards/variables.test.ts | 287 +++++- .../api/src/mcp/prompts/dashboards/content.ts | 2 + .../mcp/tools/dashboards/patchDashboard.ts | 1 + .../api/src/mcp/tools/dashboards/queryTile.ts | 23 +- .../src/mcp/tools/dashboards/queryTiles.ts | 31 +- .../api/src/mcp/tools/dashboards/schemas.ts | 147 ++- .../src/mcp/tools/dashboards/validation.ts | 16 +- .../api/src/mcp/tools/dashboards/variables.ts | 227 ++++- .../api/__tests__/dashboard.int.test.ts | 215 +++++ packages/api/src/routers/api/dashboards.ts | 40 +- .../__tests__/dashboards.int.test.ts | 404 +++++++++ .../src/routers/external-api/v2/dashboards.ts | 181 +++- .../v2/utils/__tests__/dashboards.test.ts | 25 + .../external-api/v2/utils/dashboards.ts | 127 ++- .../__tests__/provisionDashboards.int.test.ts | 35 + .../src/tasks/provisionDashboards/index.ts | 11 +- packages/api/src/utils/externalApi.ts | 18 + packages/api/src/utils/zod.ts | 72 +- packages/app/src/DBDashboardImportPage.tsx | 244 +++-- packages/app/src/DBDashboardPage.tsx | 203 +++-- packages/app/src/DashboardFilters.tsx | 95 +- .../__tests__/DBDashboardImportPage.test.tsx | 153 +++- .../AdhocDashboardFilter.tsx | 31 +- .../__tests__/AdhocDashboardFilter.test.tsx | 34 + .../ChartEditor/PromqlChartEditor.tsx | 4 +- .../ChartEditor/RawSqlChartEditor.tsx | 42 +- .../resolveConnectionSourceSync.test.ts | 24 + .../ChartEditor/__tests__/utils.test.ts | 84 ++ .../app/src/components/ChartEditor/utils.ts | 173 ++-- .../app/src/components/ConnectionSelect.tsx | 50 +- .../ChartEditorControls.tsx | 1 + .../DBEditTimeChartForm/ChartPreviewPanel.tsx | 27 +- .../DBEditTimeChartForm/EditTimeChartForm.tsx | 212 ++++- .../__tests__/ChartPreviewPanel.test.tsx | 47 +- .../__tests__/DBEditTimeChartForm.test.tsx | 224 +++++ .../__tests__/utils.test.ts | 104 +++ .../useDebouncedFormValues.ts | 25 + .../components/DBEditTimeChartForm/utils.ts | 116 ++- .../src/components/DashboardFilterLabel.tsx | 10 + .../AdhocFilterEditForm.tsx | 45 +- .../DashboardFilterEditForm.tsx | 59 +- .../DashboardFiltersList.tsx | 34 +- .../DataSourceFilterEditForm.tsx | 100 +++ .../PromqlLabelFilterEditForm.tsx | 4 +- .../QueryExpressionFilterEditForm.tsx | 9 +- .../__tests__/DashboardFiltersModal.test.tsx | 1 + .../DataSourceFilterEditForm.test.tsx | 84 ++ .../__tests__/filterFormState.test.ts | 110 ++- .../DashboardFiltersModal/filterFormState.ts | 32 +- .../ReferenceVariableDashboardFilter.tsx | 188 ++++ .../app/src/components/SelectControlled.tsx | 32 +- .../app/src/components/SourceMultiSelect.tsx | 14 +- packages/app/src/components/SourceSelect.tsx | 31 +- .../ReferenceVariableDashboardFilter.test.tsx | 149 ++++ .../__tests__/SourceSelect.test.tsx | 109 ++- .../app/src/components/sourceSelectUtils.tsx | 153 +++- .../__tests__/useDashboardFilters.test.tsx | 243 +++++ .../usePresetDashboardFilters.test.tsx | 4 + packages/app/src/hooks/useConnectionItems.ts | 17 + .../app/src/hooks/useDashboardFilters.tsx | 127 ++- .../e2e/components/ChartEditorComponent.ts | 13 + .../dashboard-required-filters.spec.ts | 2 +- .../dashboard-source-variables.spec.ts | 313 +++++++ .../dashboard-tile-editor-filters.spec.ts | 2 +- .../tests/e2e/page-objects/DashboardPage.ts | 73 +- .../common-utils/src/__tests__/guards.test.ts | 46 + .../src/__tests__/referenceVariables.test.ts | 843 ++++++++++++++++++ packages/common-utils/src/core/utils.ts | 70 +- .../common-utils/src/dashboardFilterValues.ts | 16 + .../common-utils/src/dashboardValidation.ts | 206 ++++- packages/common-utils/src/filters.ts | 55 +- packages/common-utils/src/guards.ts | 88 ++ .../common-utils/src/referenceVariables.ts | 376 ++++++++ packages/common-utils/src/types.ts | 67 +- 87 files changed, 7559 insertions(+), 551 deletions(-) create mode 100644 .changeset/source-vars-1.md create mode 100644 .changeset/source-vars-2.md create mode 100644 .changeset/source-vars-3.md create mode 100644 .changeset/source-vars-4.md create mode 100644 .changeset/source-vars-5.md create mode 100644 packages/app/src/components/DBEditTimeChartForm/useDebouncedFormValues.ts create mode 100644 packages/app/src/components/DashboardFiltersModal/DataSourceFilterEditForm.tsx create mode 100644 packages/app/src/components/DashboardFiltersModal/__tests__/DataSourceFilterEditForm.test.tsx create mode 100644 packages/app/src/components/ReferenceVariableDashboardFilter.tsx create mode 100644 packages/app/src/components/__tests__/ReferenceVariableDashboardFilter.test.tsx create mode 100644 packages/app/src/hooks/useConnectionItems.ts create mode 100644 packages/app/tests/e2e/features/dashboard-source-variables.spec.ts create mode 100644 packages/common-utils/src/__tests__/referenceVariables.test.ts create mode 100644 packages/common-utils/src/referenceVariables.ts diff --git a/.changeset/source-vars-1.md b/.changeset/source-vars-1.md new file mode 100644 index 0000000000..eeacef4d13 --- /dev/null +++ b/.changeset/source-vars-1.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/common-utils': minor +'@hyperdx/api': minor +'@hyperdx/app': patch +--- + +feat: add data source and connection variable types to dashboards diff --git a/.changeset/source-vars-2.md b/.changeset/source-vars-2.md new file mode 100644 index 0000000000..32fd79c38c --- /dev/null +++ b/.changeset/source-vars-2.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/api': minor +--- + +feat: support data source and connection variables in the external API and MCP diff --git a/.changeset/source-vars-3.md b/.changeset/source-vars-3.md new file mode 100644 index 0000000000..743757dbd6 --- /dev/null +++ b/.changeset/source-vars-3.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': minor +--- + +feat: add data source variables to dashboard filters and tiles diff --git a/.changeset/source-vars-4.md b/.changeset/source-vars-4.md new file mode 100644 index 0000000000..312539ba46 --- /dev/null +++ b/.changeset/source-vars-4.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': minor +--- + +feat: let tiles and filters use a data source variable as their source diff --git a/.changeset/source-vars-5.md b/.changeset/source-vars-5.md new file mode 100644 index 0000000000..49079c5482 --- /dev/null +++ b/.changeset/source-vars-5.md @@ -0,0 +1,8 @@ +--- +'@hyperdx/app': minor +'@hyperdx/api': minor +'@hyperdx/common-utils': minor +--- + +feat: add connection variables for raw SQL tiles, SQL query filters, and +connection-scoped data source variables diff --git a/packages/api/openapi.json b/packages/api/openapi.json index 65ea9dff2b..d3d0e8dc9b 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -1883,7 +1883,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -1980,7 +1980,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2057,7 +2057,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2144,7 +2144,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2227,7 +2227,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2288,7 +2288,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2343,7 +2343,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2437,7 +2437,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2495,7 +2495,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2559,7 +2559,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2599,7 +2599,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to mine patterns from.", + "description": "ID of the data source to mine patterns from, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2664,7 +2664,7 @@ }, "connectionId": { "type": "string", - "description": "ID of the ClickHouse connection to execute the query against.", + "description": "ID of the ClickHouse connection to execute the query against, or\n`$connectionVariable` of a CONNECTION filter on the dashboard.\n", "example": "65f5e4a3b9e77c001a567890" }, "sqlTemplate": { @@ -2675,7 +2675,7 @@ }, "sourceId": { "type": "string", - "description": "Optional ID of the data source associated with this Raw SQL chart. Used for applying dashboard filters.", + "description": "Optional ID of the data source associated with this Raw SQL chart, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. Used for applying dashboard filters.", "example": "65f5e4a3b9e77c001a567890" }, "numberFormat": { @@ -4031,6 +4031,12 @@ }, { "$ref": "#/components/schemas/AdhocFilterInput" + }, + { + "$ref": "#/components/schemas/DataSourceFilterInput" + }, + { + "$ref": "#/components/schemas/ConnectionFilterInput" } ], "discriminator": { @@ -4040,7 +4046,179 @@ "STATIC_LIST": "#/components/schemas/StaticListFilterInput", "PROMETHEUS_LABEL": "#/components/schemas/PrometheusLabelFilterInput", "SQL_QUERY": "#/components/schemas/SqlQueryFilterInput", - "ADHOC": "#/components/schemas/AdhocFilterInput" + "ADHOC": "#/components/schemas/AdhocFilterInput", + "DATA_SOURCE": "#/components/schemas/DataSourceFilterInput", + "CONNECTION": "#/components/schemas/ConnectionFilterInput" + } + } + }, + "DataSourceFilterInput": { + "type": "object", + "description": "A variable whose single, required value is a source. Tiles reference it\nas `$variableName` in their sourceId, and other filters in sourceId or\nappliesToSourceIds, so viewers can switch the source those read. Tiles\nthat use it do not load until a source is selected, and cannot have\nalerts.\n", + "required": [ + "type", + "name", + "allowedSourceKinds" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "DATA_SOURCE" + ], + "description": "Filter type discriminator. Must be \"DATA_SOURCE\".", + "example": "DATA_SOURCE" + }, + "name": { + "type": "string", + "minLength": 1, + "description": "Display name of the variable's dropdown", + "example": "Logs source" + }, + "variableName": { + "type": "string", + "maxLength": 64, + "pattern": "^[a-zA-Z][a-zA-Z0-9_]*$", + "description": "Token tiles and filters reference the selected source by, as `$variableName`.", + "example": "logs" + }, + "isGlobalRequirement": { + "type": "boolean", + "default": false, + "description": "Blocks every tile on the dashboard until a value is selected. False\n(the default) blocks only the tiles that reference the variable.\n", + "example": true + }, + "minSelections": { + "type": "integer", + "enum": [ + 1 + ], + "default": 1, + "description": "Must be 1 if provided. The variable always requires a selection.", + "example": 1 + }, + "maxSelections": { + "type": "integer", + "enum": [ + 1 + ], + "default": 1, + "description": "Must be 1 if provided. The variable is always single-select.", + "example": 1 + }, + "isBroadcastEnabled": { + "type": "boolean", + "enum": [ + false + ], + "default": false, + "description": "Must be false or omitted.", + "example": false + }, + "isVariableEnabled": { + "type": "boolean", + "enum": [ + true + ], + "default": true, + "description": "Must be true if provided, and is true when omitted.", + "example": true + }, + "allowedSourceKinds": { + "type": "array", + "minItems": 1, + "items": { + "type": "string", + "enum": [ + "log", + "trace", + "session", + "metric", + "promql" + ] + }, + "description": "Kinds of sources offered. A field can reference the variable if it\naccepts at least one listed kind. A tile whose selected source is a\nkind it cannot use shows an error instead of running.\n", + "example": [ + "log" + ] + }, + "connectionId": { + "type": "string", + "description": "Optional connection the offered sources are limited to: a\nconnection ID, or `$name` of a CONNECTION filter on the dashboard.\n", + "example": "$conn" + } + } + }, + "ConnectionFilterInput": { + "type": "object", + "description": "A variable whose single, required value is a connection. Raw SQL tiles\nreference it as `$variableName` in their connectionId, and data source\nvariables and SQL query filters in theirs. Tiles that use it do not load\nuntil a connection is selected, and cannot have alerts.\n", + "required": [ + "type", + "name" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "CONNECTION" + ], + "description": "Filter type discriminator. Must be \"CONNECTION\".", + "example": "CONNECTION" + }, + "name": { + "type": "string", + "minLength": 1, + "description": "Display name of the variable's dropdown", + "example": "Connection" + }, + "variableName": { + "type": "string", + "maxLength": 64, + "pattern": "^[a-zA-Z][a-zA-Z0-9_]*$", + "description": "Token raw SQL tiles reference the selected connection by, as `$variableName`.", + "example": "conn" + }, + "isGlobalRequirement": { + "type": "boolean", + "default": false, + "description": "Blocks every tile on the dashboard until a value is selected. False\n(the default) blocks only the tiles that reference the variable.\n", + "example": true + }, + "minSelections": { + "type": "integer", + "enum": [ + 1 + ], + "default": 1, + "description": "Must be 1 if provided. The variable always requires a selection.", + "example": 1 + }, + "maxSelections": { + "type": "integer", + "enum": [ + 1 + ], + "default": 1, + "description": "Must be 1 if provided. The variable is always single-select.", + "example": 1 + }, + "isBroadcastEnabled": { + "type": "boolean", + "enum": [ + false + ], + "default": false, + "description": "Must be false or omitted.", + "example": false + }, + "isVariableEnabled": { + "type": "boolean", + "enum": [ + true + ], + "default": true, + "description": "Must be true if provided, and is true when omitted.", + "example": true } } }, @@ -4076,7 +4254,7 @@ }, "sourceId": { "type": "string", - "description": "Source ID this dashboard filter key applies to", + "description": "Source ID this dashboard filter key applies to, or `$name` of a DATA_SOURCE filter on the dashboard", "example": "65f5e4a3b9e77c001a111111" }, "sourceMetricType": { @@ -4370,7 +4548,7 @@ }, "connectionId": { "type": "string", - "description": "ID of the ClickHouse connection the query runs on.", + "description": "ClickHouse connection the query runs on: a connection ID, or\n`$name` of a CONNECTION filter on the dashboard.\n", "example": "65f5e4a3b9e77c001a567890" }, "sqlTemplate": { @@ -4469,7 +4647,7 @@ "items": { "type": "string" }, - "description": "IDs of the sources whose keys and values the filter suggests, all of sourceType.", + "description": "IDs of the sources whose keys and values the filter suggests, all of sourceType, or `$name` of data source variables.", "example": [ "65f5e4a3b9e77c001a111111" ] @@ -4493,7 +4671,7 @@ "items": { "type": "string" }, - "description": "IDs of the sources whose tiles the conditions apply to, all of\nsourceType. Omit or send an empty array to apply to the tiles of\nthe filter's sources.\n", + "description": "IDs of the sources whose tiles the conditions apply to, all of\nsourceType, or `$name` of data source variables. Omit or send an\nempty array to apply to the tiles of the filter's sources.\n", "example": [ "65f5e4a3b9e77c001a111111" ] diff --git a/packages/api/src/controllers/alerts.ts b/packages/api/src/controllers/alerts.ts index f1c69d0ee5..f49cf85a6f 100644 --- a/packages/api/src/controllers/alerts.ts +++ b/packages/api/src/controllers/alerts.ts @@ -9,6 +9,7 @@ import { isPromqlSavedChartConfig, isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; +import { configUsesReferenceVariable } from '@hyperdx/common-utils/dist/referenceVariables'; import { isRangeThresholdType } from '@hyperdx/common-utils/dist/types'; import { groupBy } from 'lodash'; import { type FilterQuery, Types } from 'mongoose'; @@ -97,6 +98,11 @@ export const validateAlertInput = async ( // The alert checker cannot evaluate these tiles, so the alert would never run. if (tile.config != null && !savedChartConfigSupportsAlerts(tile.config)) { + if (configUsesReferenceVariable(tile.config)) { + throw new Api400Error( + 'Alerts are not supported on tiles that use a data source or connection variable', + ); + } if (isPromqlSavedChartConfig(tile.config)) { throw new Api400Error('Alerts are not supported on PromQL tiles'); } diff --git a/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts index eef1d08387..1285ec729f 100644 --- a/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts @@ -1400,4 +1400,86 @@ describe('MCP Dashboard Tools - clickstack_patch_dashboard', () => { expect(tile.config.showOperandSeries).toBe(false); }); }); + + describe('reference variables', () => { + const createDashboard = () => + new Dashboard({ + name: 'Variable dashboard', + tiles: [ + { + id: 'tile', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + name: 'Tile', + source: ctx.traceSource._id.toString(), + displayType: 'line', + select: [{ aggFn: 'count', valueExpression: '' }], + where: '', + }, + }, + ], + filters: [ + { + id: 'ds-filter', + type: 'DATA_SOURCE', + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ], + team: ctx.team._id, + }).save(); + + const patchSource = (dashboardId: string, sourceId: string) => + callTool(ctx.client!, 'clickstack_patch_dashboard', { + dashboardId, + tileId: 'tile', + tile: { + name: 'Tile', + config: { + displayType: 'line', + sourceId, + select: [{ aggFn: 'count' }], + }, + }, + }); + + it('patches a tile to read from a declared data source variable', async () => { + const dashboard = await createDashboard(); + + const result = await patchSource(dashboard._id.toString(), '$traces'); + + expect(result.isError).toBeFalsy(); + const stored = await Dashboard.findById(dashboard._id).lean(); + expect(stored?.tiles[0].config).toMatchObject({ source: '$traces' }); + }); + + it('rejects a patch referencing an undeclared variable', async () => { + const dashboard = await createDashboard(); + + const result = await patchSource(dashboard._id.toString(), '$nope'); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain( + 'does not name a data source variable', + ); + }); + + it('accepts a patch that keeps a reference the dashboard no longer satisfies', async () => { + const dashboard = await createDashboard(); + await patchSource(dashboard._id.toString(), '$traces'); + await Dashboard.updateOne({ _id: dashboard._id }, { filters: [] }); + + const result = await patchSource(dashboard._id.toString(), '$traces'); + + expect(result.isError).toBeFalsy(); + }); + }); }); 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 48de1b8f67..5042fc502c 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts @@ -11,6 +11,7 @@ import { seedExponentialHistogramMetric, } from '@/fixtures'; import { callTool, getFirstText } from '@/mcp/__tests__/mcpTestUtils'; +import Dashboard from '@/models/dashboard'; import { Source } from '@/models/source'; import { setupDashboardTests } from './setup'; @@ -1373,4 +1374,85 @@ describe('MCP Dashboard Tools - clickstack_query_tile', () => { expect(rows.map(r => r.ServiceName)).toEqual(['svc-e', 'svc-d', 'svc-c']); }); }); + + describe('reference variables', () => { + const createVariableDashboard = (savedFilterValues: unknown[] = []) => + new Dashboard({ + name: 'Variable dashboard', + tiles: [ + { + id: 'variable-tile', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + name: 'Count', + source: '$traces', + displayType: 'number', + select: [{ aggFn: 'count', valueExpression: '' }], + where: '', + }, + }, + ], + filters: [ + { + id: 'ds-filter', + type: 'DATA_SOURCE', + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ], + savedFilterValues, + team: ctx.team._id, + }).save(); + + it("runs a tile on its data source variable's saved selection", async () => { + const dashboard = await createVariableDashboard([ + { + type: 'variable', + name: 'traces', + values: [ctx.traceSource._id.toString()], + }, + ]); + + const result = await callTool(ctx.client!, 'clickstack_query_tile', { + dashboardId: dashboard._id.toString(), + tileId: 'variable-tile', + }); + + expect(result.isError).toBeFalsy(); + }); + + it('runs a tile on a selection passed in variableValues', async () => { + const dashboard = await createVariableDashboard(); + + const result = await callTool(ctx.client!, 'clickstack_query_tile', { + dashboardId: dashboard._id.toString(), + tileId: 'variable-tile', + variableValues: [ + { name: 'traces', values: [ctx.traceSource._id.toString()] }, + ], + }); + + expect(result.isError).toBeFalsy(); + }); + + it('reports a data source variable with no selection', async () => { + const dashboard = await createVariableDashboard(); + + const result = await callTool(ctx.client!, 'clickstack_query_tile', { + dashboardId: dashboard._id.toString(), + tileId: 'variable-tile', + }); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain('$traces variable'); + }); + }); }); diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts index afaeff9786..6b154c40e5 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts @@ -594,4 +594,59 @@ describe('MCP Dashboard Tools - clickstack_query_tiles', () => { expect(text).toContain('prod, staging'); }); }); + + it('reports a tile whose data source variable has no selection without failing the batch', async () => { + const sourceId = ctx.traceSource._id.toString(); + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + name: 'Batch reference variable test', + tiles: [ + { + name: 'Fixed', + config: { + displayType: 'number', + sourceId, + select: [{ aggFn: 'count' }], + }, + }, + { + name: 'Variable', + config: { + displayType: 'number', + sourceId: '$traces', + select: [{ aggFn: 'count' }], + }, + }, + ], + filters: [ + { + type: 'DATA_SOURCE', + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + }, + ], + }, + ); + expect(createResult.isError).toBeFalsy(); + const dashboard = JSON.parse(getFirstText(createResult)); + + const result = await callTool(ctx.client!, 'clickstack_query_tiles', { + dashboardId: dashboard.id, + ...wideRange(), + }); + + expect(result.isError).toBeFalsy(); + const { tiles } = JSON.parse(getFirstText(result)); + expect(tiles).toEqual([ + expect.objectContaining({ name: 'Fixed', status: 'ok' }), + expect.objectContaining({ + name: 'Variable', + status: 'error', + error: expect.stringContaining('$traces variable'), + }), + ]); + }); }); diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts index 3b270d960e..597ef883cf 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts @@ -17,6 +17,15 @@ jest.mock('@/mcp/tools/query/helpers', () => { }; }); +jest.mock('@/mcp/tools/dashboards/variables', () => { + const actual = jest.requireActual('@/mcp/tools/dashboards/variables'); + return { + ...actual, + getReferenceTargets: () => + Promise.resolve({ sources: [], connectionIds: new Set() }), + }; +}); + jest.mock('@/models/dashboard', () => ({ __esModule: true, default: { findOne: (...args: unknown[]) => mockFindOne(...args) }, diff --git a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts index 9624eca73e..b750454e5f 100644 --- a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts @@ -4132,4 +4132,127 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { ]); }); }); + + describe('reference variables', () => { + const filters = [ + { + type: 'CONNECTION', + name: 'Connection', + variableName: 'conn', + isGlobalRequirement: true, + }, + { + type: 'DATA_SOURCE', + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + connectionId: '$conn', + }, + ]; + + it('saves and returns variables and tiles that reference them', async () => { + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Variable dashboard', + tiles: [ + { + name: 'Builder', + config: { + displayType: 'line', + sourceId: '$traces', + select: [{ aggFn: 'count' }], + }, + }, + { + name: 'Raw SQL', + config: { + configType: 'sql', + displayType: 'table', + connectionId: '$conn', + sqlTemplate: 'SELECT 1', + }, + }, + ], + filters, + }); + + expect(result.isError).toBeFalsy(); + const output = JSON.parse(getFirstText(result)); + expect(output.filters).toEqual([ + expect.objectContaining(filters[0]), + expect.objectContaining(filters[1]), + ]); + expect( + output.tiles.map((t: ExternalDashboardTileWithId) => t.config), + ).toEqual([ + expect.objectContaining({ sourceId: '$traces' }), + expect.objectContaining({ connectionId: '$conn' }), + ]); + }); + + it('saves a SQL query filter that runs on a connection variable', async () => { + const sqlFilter = { + type: 'SQL_QUERY', + name: 'Environment', + variableName: 'env', + connectionId: '$conn', + sqlTemplate: 'SELECT DISTINCT env FROM envs', + }; + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Variable dashboard', + tiles: [], + filters: [filters[0], sqlFilter], + }); + + expect(result.isError).toBeFalsy(); + expect(JSON.parse(getFirstText(result)).filters[1]).toMatchObject( + sqlFilter, + ); + }); + + it('rejects a tile referencing an undeclared variable', async () => { + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Variable dashboard', + tiles: [ + { + name: 'Builder', + config: { + displayType: 'line', + sourceId: '$traces', + select: [{ aggFn: 'count' }], + }, + }, + ], + }); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain( + 'does not name a data source variable', + ); + }); + + it('checks an update without filters against the stored variables', async () => { + const builderTile = (sourceId: string) => ({ + name: 'Builder', + config: { + displayType: 'line', + sourceId, + select: [{ aggFn: 'count' }], + }, + }); + const created = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Variable dashboard', + tiles: [builderTile(ctx.traceSource._id.toString())], + filters, + }); + expect(created.isError).toBeFalsy(); + + const updated = await callTool(ctx.client!, 'clickstack_save_dashboard', { + id: JSON.parse(getFirstText(created)).id, + name: 'Variable dashboard', + tiles: [builderTile('$traces')], + }); + + expect(updated.isError).toBeFalsy(); + }); + }); }); diff --git a/packages/api/src/mcp/__tests__/dashboards/validation.test.ts b/packages/api/src/mcp/__tests__/dashboards/validation.test.ts index bd6ffe6a63..0e9034c096 100644 --- a/packages/api/src/mcp/__tests__/dashboards/validation.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/validation.test.ts @@ -11,6 +11,7 @@ import { getRawSqlMissingSourceError, getRawSqlTileMacroWarnings, getRawSqlTilesMissingRequiredSource, + getSavedFilterValueWarnings, getTileVariableWarnings, } from '@/mcp/tools/dashboards/validation'; import type { @@ -982,3 +983,31 @@ describe('getFilterVariableWarnings', () => { }); }); }); + +describe('getSavedFilterValueWarnings', () => { + const filters = [ + { type: 'DATA_SOURCE' as const, name: 'Traces', variableName: 'traces' }, + { type: 'CONNECTION' as const, name: 'Cluster', variableName: 'conn' }, + ]; + + it('accepts saved values for data source and connection variables', () => { + expect( + getSavedFilterValueWarnings( + [ + { type: 'variable', name: 'traces', values: ['s1'] }, + { type: 'variable', name: 'conn', values: ['c1'] }, + ], + filters, + ), + ).toEqual([]); + }); + + it('warns about a saved value no filter declares', () => { + expect( + getSavedFilterValueWarnings( + [{ type: 'variable', name: 'nope', values: ['x'] }], + filters, + ), + ).toHaveLength(1); + }); +}); diff --git a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts index 6d3bcc42bf..9d5e0e45a2 100644 --- a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts @@ -1,10 +1,16 @@ +import { SourceKind } from '@hyperdx/common-utils/dist/types'; import mongoose from 'mongoose'; import { + type ReferenceTargets, resolveDashboardVariables, + resolveTileVariableReferences, withResolvedFilterVariableNames, } from '@/mcp/tools/dashboards/variables'; -import type { ExternalDashboardFilterWithId } from '@/utils/zod'; +import type { + ExternalDashboardFilterWithId, + ExternalDashboardTileWithId, +} from '@/utils/zod'; const sourceId = new mongoose.Types.ObjectId().toString(); @@ -322,3 +328,282 @@ describe('withResolvedFilterVariableNames', () => { ]); }); }); + +describe('resolveTileVariableReferences', () => { + const objectId = () => new mongoose.Types.ObjectId().toString(); + const connectionId = objectId(); + const otherConnectionId = objectId(); + const traceSourceId = objectId(); + const logSourceId = objectId(); + const metricSourceId = objectId(); + const promqlSourceId = objectId(); + const otherConnectionLogSourceId = objectId(); + const targets: ReferenceTargets = { + sources: [ + { id: traceSourceId, kind: SourceKind.Trace, connection: connectionId }, + { id: logSourceId, kind: SourceKind.Log, connection: connectionId }, + { id: metricSourceId, kind: SourceKind.Metric, connection: connectionId }, + { id: promqlSourceId, kind: SourceKind.Promql, connection: connectionId }, + { + id: otherConnectionLogSourceId, + kind: SourceKind.Log, + connection: otherConnectionId, + }, + ], + connectionIds: new Set([connectionId, otherConnectionId]), + }; + + const referenceVariableFields = { + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + } as const; + const connectionVariable: ExternalDashboardFilterWithId = { + ...referenceVariableFields, + id: objectId(), + type: 'CONNECTION', + name: 'Connection', + variableName: 'conn', + }; + const tracesVariable = ( + connection?: string, + ): ExternalDashboardFilterWithId => ({ + ...referenceVariableFields, + id: objectId(), + type: 'DATA_SOURCE', + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + connectionId: connection, + }); + + const sourceVariable = ( + allowedSourceKinds: SourceKind[], + ): ExternalDashboardFilterWithId => ({ + ...referenceVariableFields, + id: objectId(), + type: 'DATA_SOURCE', + name: 'Source', + variableName: 'src', + allowedSourceKinds, + }); + + const builderTile: ExternalDashboardTileWithId = { + id: 'builder', + name: 'Builder', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + displayType: 'number', + sourceId: '$traces', + select: [{ aggFn: 'count', where: '' }], + }, + }; + const rawSqlTile: ExternalDashboardTileWithId = { + id: 'raw-sql', + name: 'Raw SQL', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + configType: 'sql', + displayType: 'table', + connectionId: '$conn', + sqlTemplate: 'SELECT 1', + }, + }; + + const promqlTile: ExternalDashboardTileWithId = { + id: 'promql', + name: 'PromQL', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + configType: 'promql', + displayType: 'line', + sourceId: '$src', + expressions: [{ expression: 'up' }], + }, + } as ExternalDashboardTileWithId; + const searchTile: ExternalDashboardTileWithId = { + id: 'search', + name: 'Search', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + displayType: 'search', + sourceId: '$src', + select: '', + where: '', + whereLanguage: 'sql', + }, + }; + const rawSqlSourceTile: ExternalDashboardTileWithId = { + ...rawSqlTile, + id: 'raw-sql-source', + config: { + configType: 'sql', + displayType: 'table', + connectionId: '$conn', + sourceId: '$src', + sqlTemplate: 'SELECT 1', + }, + }; + + const resolve = ( + tile: ExternalDashboardTileWithId, + filters: ExternalDashboardFilterWithId[], + selections: Record, + ) => + resolveTileVariableReferences( + tile, + filters, + Object.entries(selections).map(([name, values]) => ({ name, values })), + [], + targets, + ); + + it("resolves a connection reference to the variable's selection", () => { + const result = resolve(rawSqlTile, [connectionVariable], { + conn: [connectionId], + }); + + expect(result).toEqual({ + tile: { + ...rawSqlTile, + config: { ...rawSqlTile.config, connectionId }, + }, + }); + }); + + it('resolves a source on the connection its connection variable selects', () => { + const result = resolve( + builderTile, + [connectionVariable, tracesVariable('$conn')], + { conn: [connectionId], traces: [traceSourceId] }, + ); + + expect(result).toEqual({ + tile: { + ...builderTile, + config: { ...builderTile.config, sourceId: traceSourceId }, + }, + }); + }); + + it('resolves a source of a kind the tile accepts', () => { + const result = resolve( + promqlTile, + [sourceVariable([SourceKind.Log, SourceKind.Promql])], + { src: [promqlSourceId] }, + ); + + expect(result).toEqual({ + tile: { + ...promqlTile, + config: { ...promqlTile.config, sourceId: promqlSourceId }, + }, + }); + }); + + it.each<{ + case: string; + tile: ExternalDashboardTileWithId; + selection: string; + kinds: SourceKind[]; + }>([ + { + case: 'a log source on a PromQL tile', + tile: promqlTile, + selection: logSourceId, + kinds: [SourceKind.Log, SourceKind.Promql], + }, + { + case: 'a metric source on a search tile', + tile: searchTile, + selection: metricSourceId, + kinds: [SourceKind.Log, SourceKind.Metric], + }, + ])('rejects $case', ({ tile, selection, kinds }) => { + expect( + resolve(tile, [sourceVariable(kinds)], { src: [selection] }), + ).toEqual({ + error: expect.stringContaining('this tile only accepts'), + }); + }); + + it('resolves a raw SQL source on the connection the query runs on', () => { + const result = resolve( + rawSqlSourceTile, + [connectionVariable, sourceVariable([SourceKind.Log])], + { conn: [connectionId], src: [logSourceId] }, + ); + + expect(result).toEqual({ + tile: { + ...rawSqlSourceTile, + config: { + ...rawSqlSourceTile.config, + connectionId, + sourceId: logSourceId, + }, + }, + }); + }); + + it('rejects a raw SQL source on another connection than the query', () => { + const result = resolve( + rawSqlSourceTile, + [connectionVariable, sourceVariable([SourceKind.Log])], + { conn: [connectionId], src: [otherConnectionLogSourceId] }, + ); + + expect(result).toEqual({ + error: expect.stringContaining( + `the source is on connection "${otherConnectionId}"`, + ), + }); + }); + + it.each<{ + case: string; + tile: ExternalDashboardTileWithId; + filters: ExternalDashboardFilterWithId[]; + selections: Record; + variable: string; + }>([ + { + case: 'a source selection that is not a source', + tile: builderTile, + filters: [tracesVariable()], + selections: { traces: [connectionId] }, + variable: '$traces', + }, + { + case: 'a source variable whose connection variable has no selection', + tile: builderTile, + filters: [connectionVariable, tracesVariable('$conn')], + selections: { traces: [traceSourceId] }, + variable: '$conn', + }, + { + case: 'a connection selection that is not a connection', + tile: rawSqlTile, + filters: [connectionVariable], + selections: { conn: [traceSourceId] }, + variable: '$conn', + }, + ])('rejects $case', ({ tile, filters, selections, variable }) => { + expect(resolve(tile, filters, selections)).toEqual({ + error: expect.stringContaining(`${variable} variable`), + }); + }); +}); diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index bbfb7167de..125b3c16e5 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -137,6 +137,8 @@ Apply these before calling clickstack_save_dashboard. Each rule is enforced by t 9h. USE AN ADHOC FILTER TO LET THE USER BUILD FREE-FORM CONDITIONS. filters: [{ type: "ADHOC", name, sourceType: "sql", sources: [""], variableName? }] adds an input where the user picks any column or map key, an operator, and a value; clicking a value in a tile adds a condition too. Every condition is ANDed onto the tiles of its sources (or of appliesToSourceIds) with no per-tile wiring. It is never a variable: its variableName only names the entry its conditions are saved under. Seed conditions with savedFilterValues: [{ type: "adhoc", name: "", conditions: [{ key: "ServiceName", operator: "IN", value: "api" }] }]; IN conditions on the same key are ORed. Declare at most one ad hoc filter per source, since a click updates every ad hoc filter on the clicked tile's source. +9i. TO LET VIEWERS SWITCH THE SOURCE OR CONNECTION, USE A DATA_SOURCE OR CONNECTION FILTER. filters: [{ type: "DATA_SOURCE", name: "Logs source", variableName: "logs", allowedSourceKinds: ["log"] }] adds a required source picker; tiles then set sourceId: "$logs" (filters may use it in sourceId or appliesToSourceIds). A CONNECTION filter does the same for raw SQL tiles' and SQL_QUERY filters' connectionId, and a DATA_SOURCE filter's optional connectionId limits its sources to one connection. Keep allowedSourceKinds to kinds charts treat alike (log + trace, or one kind). Tiles that use either cannot have alerts, and clickstack_query_tile needs a selection for the variable (variableValues or the dashboard's saved value). + 10. UPDATE IS REPLACE, NOT MERGE. clickstack_save_dashboard with an id overwrites tiles, containers, and filters in their entirety. Call clickstack_get_dashboard first when you only want to add or rename one entry; do not send a partial set or you will silently drop everything you omitted. 11. GROUP RELATED TILES INTO CONTAINERS. REQUIRED at five or more tiles, no exceptions. An ungrouped wall of nine or ten tiles is a readability failure even when each tile is correct in isolation. Containers are the right way to introduce structure; markdown tiles for section labels are not. diff --git a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts index 36d5f43a21..c19c9d8715 100644 --- a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts @@ -201,6 +201,7 @@ export function registerPatchDashboard({ teamId, tiles: [mergedTile], existingTiles: existingDashboard.tiles ?? [], + existingFilters: existingDashboard.filters, containers: existingDashboard.containers ?? [], }); if (validationError) { diff --git a/packages/api/src/mcp/tools/dashboards/queryTile.ts b/packages/api/src/mcp/tools/dashboards/queryTile.ts index b6cd385b57..1e610b0cd3 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTile.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTile.ts @@ -13,7 +13,12 @@ import { getRawSqlTileMacroWarnings, getTileVariableWarnings, } from './validation'; -import { mcpVariableValuesParam, resolveDashboardVariables } from './variables'; +import { + getReferenceTargets, + mcpVariableValuesParam, + resolveDashboardVariables, + resolveTileVariableReferences, +} from './variables'; export function registerQueryTile({ context, @@ -79,8 +84,8 @@ export function registerQueryTile({ const externalDashboard = convertToExternalDashboard(dashboard, { hidePromql: !isPromqlEnabled(context), }); - const tile = externalDashboard.tiles.find(t => t.id === tileId); - if (!tile) { + const storedTile = externalDashboard.tiles.find(t => t.id === tileId); + if (!storedTile) { return mcpUserError( `Tile not found: ${tileId}. Available tile IDs: ${externalDashboard.tiles.map(t => t.id).join(', ')}`, ); @@ -94,6 +99,18 @@ export function registerQueryTile({ return mcpUserError(resolvedVariables.error); } + const resolvedTile = resolveTileVariableReferences( + storedTile, + externalDashboard.filters, + variableValues, + externalDashboard.savedFilterValues, + await getReferenceTargets(teamId.toString()), + ); + if ('error' in resolvedTile) { + return mcpUserError(resolvedTile.error); + } + const { tile } = resolvedTile; + const result = await runConfigTile( teamId.toString(), tile, diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index 44af35c950..a1716461f2 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -19,7 +19,12 @@ import { getRawSqlTileMacroWarnings, getTileVariableWarnings, } from './validation'; -import { mcpVariableValuesParam, resolveDashboardVariables } from './variables'; +import { + getReferenceTargets, + mcpVariableValuesParam, + resolveDashboardVariables, + resolveTileVariableReferences, +} from './variables'; /** * How many tiles to query against ClickHouse at once. Kept lowish so a batch @@ -230,6 +235,8 @@ export function registerQueryTiles({ .slice(MAX_TILES_PER_CALL) .map(t => t.id); + const referenceTargets = await getReferenceTargets(teamId.toString()); + // Fix one shared deadline for the whole batch that every tile races. const deadlineAt = Date.now() + BATCH_DEADLINE_MS; @@ -251,6 +258,17 @@ export function registerQueryTiles({ return { ...base, status: 'skipped' }; } + const resolvedTile = resolveTileVariableReferences( + tile, + externalDashboard.filters, + variableValues, + externalDashboard.savedFilterValues, + referenceTargets, + ); + if ('error' in resolvedTile) { + return { ...base, status: 'error', error: resolvedTile.error }; + } + // Run the query under the shared deadline. It's passed as a thunk // so withDeadline can skip issuing it entirely once the budget is // spent (see withDeadline). withDeadline hands the thunk an @@ -263,10 +281,13 @@ export function registerQueryTiles({ try { const result = await withDeadline( signal => - runConfigTile(teamId.toString(), tile, startDate, endDate, { - abortSignal: signal, - variables, - }), + runConfigTile( + teamId.toString(), + resolvedTile.tile, + startDate, + endDate, + { abortSignal: signal, variables }, + ), deadlineAt, ); diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index 090d00522b..0440330f1d 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -26,6 +26,7 @@ import { PromqlQueryTypeSchema, PromqlReducerSchema, SearchConditionTrimmedLanguageSchema, + SourceKind, SQLIntervalSchema, SqlQueryDashboardFilterSchema, StaticListDashboardFilterSchema, @@ -41,10 +42,18 @@ import { externalAdhocSavedFilterValueSchema, externalSqlSavedFilterValueSchema, externalVariableSavedFilterValueSchema, + objectIdOrVariableReferenceSchema, objectIdSchema, tagsSchema, } from '@/utils/zod'; +const SOURCE_VARIABLE_REFERENCE_NOTE = + 'May instead be `$name`, a reference to a DATA_SOURCE filter (variable) on this ' + + 'dashboard, so viewers can switch the source; the variable must offer at least ' + + 'one kind this field accepts.'; + +const SOURCE_ID_DESCRIPTION = `Source ID - call clickstack_list_sources. ${SOURCE_VARIABLE_REFERENCE_NOTE}`; + /** * Metric type values exposed on dashboard tile select items. Restricted to * the kinds the query renderer can translate today; summary is intentionally @@ -651,7 +660,7 @@ const mcpTimeChartDisplayFields = { }; const mcpRowListSourceFields = { - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), where: z .string() .optional() @@ -739,7 +748,7 @@ export const mcpLineTileSchema = mcpTileLayoutSchema.extend({ .object({ ...rejectedTileWhereFields, displayType: z.literal('line').describe('Line chart over time'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .min(1) @@ -776,7 +785,7 @@ export const mcpLineTileSchema = mcpTileLayoutSchema.extend({ }); const mcpStackedTimeChartConfigFields = { - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .min(1) @@ -828,7 +837,7 @@ const mcpTableTileSchema = mcpTileLayoutSchema.extend({ .object({ ...rejectedTileWhereFields, displayType: z.literal('table').describe('Tabular aggregated data'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .min(1) @@ -884,7 +893,7 @@ export const mcpNumberTileSchema = mcpTileLayoutSchema.extend({ displayType: z .literal('number') .describe('Single aggregate scalar value'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .min(1) @@ -925,7 +934,7 @@ const mcpPieTileSchema = mcpTileLayoutSchema.extend({ .object({ ...rejectedTileWhereFields, displayType: z.literal('pie').describe('Pie chart'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .length(1) @@ -973,7 +982,7 @@ const mcpCategoricalBarTileSchema = mcpTileLayoutSchema.extend({ displayType: z .literal('bar') .describe('Bar chart — one bar per group value (not a time series)'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .length(1) @@ -1061,7 +1070,8 @@ const mcpHeatmapTileSchema = mcpTileLayoutSchema.extend({ .string() .describe( 'Source ID. Must be a Trace source today; use clickstack_list_sources and ' + - 'pick one whose kind is "trace".', + 'pick one whose kind is "trace". ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), select: z .array(mcpHeatmapSelectItemSchema) @@ -1106,7 +1116,8 @@ const mcpHeatmapSeriesTileSchema = mcpTileLayoutSchema.extend({ sourceId: z .string() .describe( - 'Source ID of a Trace, Log, or Metric source - call clickstack_list_sources', + 'Source ID of a Trace, Log, or Metric source - call clickstack_list_sources. ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), select: z .array(mcpTileSelectItemSchema) @@ -1203,7 +1214,9 @@ export const mcpSqlTileSchema = mcpTileLayoutSchema.extend({ connectionId: z .string() .describe( - 'Connection ID (not sourceId) – call clickstack_list_sources to find available connections', + 'Connection ID (not sourceId) – call clickstack_list_sources to find available connections. ' + + 'May instead be `$name`, a reference to a CONNECTION filter (variable) on this ' + + 'dashboard, so viewers can switch the connection the query runs on.', ), sourceId: z .string() @@ -1213,7 +1226,8 @@ export const mcpSqlTileSchema = mcpTileLayoutSchema.extend({ 'ALWAYS set this for raw SQL tiles UNLESS the query reads from multiple tables ' + '(e.g. JOINs or sub-queries spanning several sources), in which case omit it. ' + 'sourceId is REQUIRED by two macros: $__filters and $__sourceTable. ' + - 'The sourceId must belong to the same connection as connectionId.', + 'The sourceId must belong to the same connection as connectionId. ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), sqlTemplate: z.string().describe(` Raw ClickHouse SQL query. SQL guidelines: @@ -1341,7 +1355,8 @@ const mcpPromqlTileSchema = mcpTileLayoutSchema.extend({ sourceId: z .string() .describe( - 'ID of a source whose kind is "promql" – call clickstack_list_sources', + 'ID of a source whose kind is "promql" – call clickstack_list_sources. ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), expressions: z .array(mcpPromqlExpressionSchema) @@ -1670,9 +1685,10 @@ const mcpQueryExpressionFilterSchema = z "not declared in any of this dashboard's filters is silently dropped at click time. " + 'Declare an expression here for every column you plan to drive via row-click.', ), - sourceId: objectIdSchema.describe( + sourceId: objectIdOrVariableReferenceSchema.describe( 'Source the filter values are pulled from (for the dropdown). ' + - 'Get IDs from clickstack_list_sources.', + 'Get IDs from clickstack_list_sources. ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), sourceMetricType: z .nativeEnum(MetricsDataType) @@ -1701,7 +1717,7 @@ const mcpQueryExpressionFilterSchema = z 'Query language of `where`. Set it explicitly.', ), appliesToSourceIds: z - .array(objectIdSchema) + .array(objectIdOrVariableReferenceSchema) .optional() .describe( 'Source IDs (from clickstack_list_sources) that this filter is applied to. ' + @@ -1778,8 +1794,9 @@ const mcpSqlQueryFilterSchema = z .describe( 'Filter type discriminator for a filter whose dropdown values come from a ClickHouse SQL query.', ), - connectionId: objectIdSchema.describe( - 'ClickHouse connection the query runs on. Get IDs from clickstack_list_sources.', + connectionId: objectIdOrVariableReferenceSchema.describe( + 'ClickHouse connection the query runs on: a connection ID from ' + + 'clickstack_list_sources, or `$name` of a CONNECTION filter on this dashboard.', ), sqlTemplate: SqlQueryDashboardFilterSchema.shape.sqlTemplate.describe( 'ClickHouse SELECT whose FIRST column becomes the dropdown values (cast to ' + @@ -1805,8 +1822,9 @@ const mcpPromqlLabelFilterSchema = z .describe( "Filter type discriminator for a filter whose dropdown lists a Prometheus label's values.", ), - sourceId: objectIdSchema.describe( - 'ID of a source whose kind is "promql". Get IDs from clickstack_list_sources.', + sourceId: objectIdOrVariableReferenceSchema.describe( + 'ID of a source whose kind is "promql". Get IDs from clickstack_list_sources. ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), label: PromqlLabelDashboardFilterSchema.shape.label.describe( 'Label whose values fill the dropdown, e.g. "job". ' + @@ -1846,11 +1864,11 @@ const mcpAdhocFilterSchema = z '"sql": keys are the columns and map keys of Log, Trace, or Session sources.', ), sources: z - .array(objectIdSchema) + .array(objectIdOrVariableReferenceSchema) .min(1) .describe( 'IDs of the Log, Trace, or Session sources (from clickstack_list_sources) ' + - 'whose keys and values the filter suggests.', + 'whose keys and values the filter suggests, or `$name` of DATA_SOURCE filters.', ), where: z .string() @@ -1863,7 +1881,7 @@ const mcpAdhocFilterSchema = z 'Query language of `where`.', ), appliesToSourceIds: z - .array(objectIdSchema) + .array(objectIdOrVariableReferenceSchema) .optional() .describe( 'IDs of the sources whose tiles the conditions apply to, of the same kind ' + @@ -1885,31 +1903,92 @@ const mcpPromqlAdhocFilterSchema = mcpAdhocFilterSchema.extend({ 'as label matchers to every selector in PromQL tiles.', ), sources: z - .array(objectIdSchema) + .array(objectIdOrVariableReferenceSchema) .min(1) .describe( 'IDs of the sources (from clickstack_list_sources) whose keys and values ' + - 'the filter suggests: Log, Trace, or Session sources for sourceType ' + - '"sql", promql sources for "promql".', + 'the filter suggests, or `$name` of DATA_SOURCE filters: Log, Trace, or ' + + 'Session sources for sourceType "sql", promql sources for "promql".', ), where: mcpAdhocFilterSchema.shape.where.describe( `${mcpAdhocFilterSchema.shape.where.description} sourceType "sql" only; rejected when sourceType is "promql".`, ), }); +// Reference variables are always single-select and required, so they take +// none of the selection-limit fields. +const mcpReferenceVariableBaseShape = { + id: mcpDashboardFilterBaseShape.id, + name: mcpDashboardFilterBaseShape.name, + variableName: mcpDashboardFilterBaseShape.variableName, + // Always required, so the base description's minSelections condition doesn't apply + isGlobalRequirement: mcpDashboardFilterBaseShape.isGlobalRequirement.describe( + 'Block EVERY tile on the dashboard until a value is selected, not just ' + + 'the ones that reference this variable.', + ), +}; + +const mcpDataSourceFilterSchema = z + .object({ + ...mcpReferenceVariableBaseShape, + type: z + .literal(DashboardFilterType.enum.DATA_SOURCE) + .describe( + 'Filter type discriminator for a variable whose value is a source.', + ), + allowedSourceKinds: z + .array(z.nativeEnum(SourceKind)) + .min(1) + .describe( + 'Kinds of sources offered in the dropdown. A tile or filter can reference the ' + + 'variable if it accepts at least one listed kind. A tile whose selected source ' + + 'is a kind it cannot use (e.g. a log source on a PromQL tile) errors instead of ' + + 'running, so prefer kinds that charts treat alike (log + trace, or a single kind).', + ), + connectionId: objectIdOrVariableReferenceSchema + .optional() + .describe( + 'Optional connection the offered sources are limited to: a connection ID, or ' + + '`$name` of a CONNECTION filter on this dashboard.', + ), + }) + .describe( + 'A variable whose single, required value is a source. Tiles and other filters ' + + 'reference it as `$variableName` in sourceId (or appliesToSourceIds) instead of a ' + + 'source ID; tiles stay blocked until a source is selected.', + ); + +const mcpConnectionFilterSchema = z + .object({ + ...mcpReferenceVariableBaseShape, + type: z + .literal(DashboardFilterType.enum.CONNECTION) + .describe( + 'Filter type discriminator for a variable whose value is a connection.', + ), + }) + .describe( + 'A variable whose single, required value is a connection. Raw SQL tiles reference ' + + 'it as `$variableName` in connectionId, and DATA_SOURCE and SQL_QUERY filters in ' + + 'connectionId.', + ); + const mcpDashboardFilterSchema = z .discriminatedUnion('type', [ mcpQueryExpressionFilterSchema, mcpStaticListFilterSchema, mcpSqlQueryFilterSchema, mcpAdhocFilterSchema, + mcpDataSourceFilterSchema, + mcpConnectionFilterSchema, ]) .describe( 'A dashboard-level filter the user can adjust in the dashboard filter bar. ' + 'QUERY_EXPRESSION queries its dropdown values from a source column; ' + 'STATIC_LIST declares them inline; SQL_QUERY reads them from a SQL query. ' + 'STATIC_LIST and SQL_QUERY are always variable-only. ADHOC holds free-form ' + - 'conditions and always broadcasts.', + 'conditions and always broadcasts. DATA_SOURCE and CONNECTION select the ' + + 'source or connection that tiles referencing them as `$variableName` use.', ); const mcpPromqlDashboardFilterSchema = z @@ -1919,6 +1998,8 @@ const mcpPromqlDashboardFilterSchema = z mcpSqlQueryFilterSchema, mcpPromqlLabelFilterSchema, mcpPromqlAdhocFilterSchema, + mcpDataSourceFilterSchema, + mcpConnectionFilterSchema, ]) .describe( 'A dashboard-level filter the user can adjust in the dashboard filter bar. ' + @@ -1926,7 +2007,8 @@ const mcpPromqlDashboardFilterSchema = z 'STATIC_LIST declares them inline; SQL_QUERY reads them from a SQL query; ' + 'PROMETHEUS_LABEL lists the values of a label on a promql source. Those three ' + 'are always variable-only. ADHOC holds free-form conditions on SQL or promql ' + - 'sources and always broadcasts.', + 'sources and always broadcasts. DATA_SOURCE and CONNECTION select the source ' + + 'or connection that tiles referencing them as `$variableName` use.', ); export type McpDashboardFilter = z.infer; @@ -2011,7 +2093,16 @@ const mcpFiltersParam = z ']\n' + 'with savedFilterValues: [{ "type": "adhoc", "name": "conditions", "conditions": ' + '[{ "key": "ServiceName", "operator": "IN", "value": "api" }, ' + - '{ "key": "ServiceName", "operator": "IN", "value": "web" }] }].', + '{ "key": "ServiceName", "operator": "IN", "value": "web" }] }].\n\n' + + 'Example (data source variable: viewers pick which logs source every tile reads):\n' + + '[\n' + + ' { "type": "DATA_SOURCE", "name": "Logs source", "variableName": "logs",\n' + + ' "allowedSourceKinds": ["log"] }\n' + + ']\n' + + 'Tiles then set "sourceId": "$logs". A CONNECTION filter works the same way for ' + + 'raw SQL tiles ("connectionId": "$conn"); a DATA_SOURCE filter may set ' + + '"connectionId" to limit its sources to one connection. Alerts are not supported ' + + 'on tiles that use either.', ); const PROMQL_FILTERS_EXAMPLE = diff --git a/packages/api/src/mcp/tools/dashboards/validation.ts b/packages/api/src/mcp/tools/dashboards/validation.ts index d678b37729..d323c86acc 100644 --- a/packages/api/src/mcp/tools/dashboards/validation.ts +++ b/packages/api/src/mcp/tools/dashboards/validation.ts @@ -6,6 +6,8 @@ import { getFilterVariableName, isAdhocConditionSupported, isFilterVariableEnabled, + isReferenceVariableFilterType, + pairWithVariableNames, validateSqlQueryFilterTemplate, } from '@hyperdx/common-utils/dist/filters'; import { @@ -264,7 +266,8 @@ export function getFilterVariableWarnings( * `name` matches no filter of its kind, or an ad hoc condition its filter's * source type can't express, is silently ignored when the dashboard loads, so * it looks like a saved default but never applies. Warn so the agent can fix - * it. + * it. Data source and connection variables count as variable-enabled filters, + * though they are not text variables. */ export function getSavedFilterValueWarnings( savedFilterValues: DashboardFilterValue[] | undefined, @@ -273,11 +276,16 @@ export function getSavedFilterValueWarnings( | undefined, ): string[] { if (!savedFilterValues?.length) return []; - const declaredNames = new Set( - getDashboardVariableDeclarations(filters).map( + const declaredNames = new Set([ + ...getDashboardVariableDeclarations(filters).map( declaration => declaration.name, ), - ); + ...pairWithVariableNames( + (filters ?? []).filter(filter => + isReferenceVariableFilterType(filter.type), + ), + ).map(({ name }) => name), + ]); const adhocSourceTypeByName = new Map( (filters ?? []).flatMap(filter => filter.type === 'ADHOC' && filter.sourceType diff --git a/packages/api/src/mcp/tools/dashboards/variables.ts b/packages/api/src/mcp/tools/dashboards/variables.ts index f1b98a6116..7f5e91cb9d 100644 --- a/packages/api/src/mcp/tools/dashboards/variables.ts +++ b/packages/api/src/mcp/tools/dashboards/variables.ts @@ -2,18 +2,48 @@ import { getDashboardVariableDeclarations, getDashboardVariableFilters, getFilterVariableName, + isDataSourceFilter, isFilterVariableEnabled, isStaticListFilter, } from '@hyperdx/common-utils/dist/filters'; -import type { ChartVariable } from '@hyperdx/common-utils/dist/types'; +import { getSavedConfigAllowedSourceKinds } from '@hyperdx/common-utils/dist/guards'; +import { + getReferenceVariableFilters, + getStringField, + isSourceOfferedByVariable, + parseVariableReference, +} from '@hyperdx/common-utils/dist/referenceVariables'; +import type { + ChartVariable, + SavedChartConfig, + SourceKind, +} from '@hyperdx/common-utils/dist/types'; import { isFilterSingleSelect } from '@hyperdx/common-utils/dist/variables'; import { z } from 'zod'; +import { getConnectionsByTeam } from '@/controllers/connection'; +import { getSources } from '@/controllers/sources'; +import { + convertToInternalTileConfig, + type ExternalDashboard, + isConfigTile, + isRawSqlExternalTileConfig, +} from '@/routers/external-api/v2/utils/dashboards'; import type { ExternalDashboardFilter, ExternalDashboardFilterWithId, + ExternalDashboardTileWithId, } from '@/utils/zod'; +type ExternalFilters = + | (ExternalDashboardFilter | ExternalDashboardFilterWithId)[] + | undefined; + +/** Names of the data source and connection variables a dashboard declares. */ +function getReferenceVariableNames(filters: ExternalFilters): Set { + return new Set(getReferenceVariableFilters(filters).map(({ name }) => name)); +} + /** Optional per-variable selection for a tile run. */ export const mcpVariableValuesParam = z .array( @@ -28,7 +58,9 @@ export const mcpVariableValuesParam = z .array(z.string()) .describe( 'Values to treat as selected. An empty array means nothing is selected for this variable. ' + - "For a STATIC_LIST filter's variable, every value must be one of the filter's declared options.", + "For a STATIC_LIST filter's variable, every value must be one of the filter's declared options. " + + 'For a DATA_SOURCE or CONNECTION variable, pass one source or connection ID; it ' + + "overrides the dashboard's saved selection.", ), }), ) @@ -65,9 +97,11 @@ export function resolveDashboardVariables( if (!variableValues?.length) return { variables }; const byName = new Map(variables.map(variable => [variable.name, variable])); + // Resolved separately, by resolveTileVariableReferences + const referenceVariableNames = getReferenceVariableNames(filters); const unknownVariableValues = variableValues .map(({ name }) => name) - .filter(name => !byName.has(name)); + .filter(name => !byName.has(name) && !referenceVariableNames.has(name)); if (unknownVariableValues.length > 0) { const available = variables.length > 0 @@ -121,12 +155,197 @@ export function resolveDashboardVariables( // Override the default empty selection with the given variableValues for (const { name, values } of variableValues) { - byName.get(name)!.values = values; + const variable = byName.get(name); + if (variable) variable.values = values; } return { variables }; } +/** The team's sources and connections that a reference variable may select. */ +export type ReferenceTargets = { + sources: { + id: string; + kind: SourceKind; + connection: string; + disabled?: boolean; + }[]; + connectionIds: ReadonlySet; +}; + +export async function getReferenceTargets( + teamId: string, +): Promise { + const [sources, connections] = await Promise.all([ + getSources(teamId), + getConnectionsByTeam(teamId), + ]); + return { + sources: sources.map(source => ({ + id: source._id.toString(), + kind: source.kind, + connection: source.connection.toString(), + disabled: source.disabled, + })), + connectionIds: new Set(connections.map(c => c._id.toString())), + }; +} + +/** + * Replace a tile's `$name` sourceId / connectionId with the source or + * connection its data source or connection variable selects: the caller's + * variableValues first, then the dashboard's saved selection. A tile with no + * selection cannot run, as on the dashboard, so that is an error naming the + * variable. So is a selection the dashboard's picker would not offer, such as + * a source of another kind or on another connection. + */ +export function resolveTileVariableReferences< + T extends ExternalDashboardTileWithId, +>( + tile: T, + filters: ExternalFilters, + variableValues: McpVariableValues | undefined, + savedFilterValues: ExternalDashboard['savedFilterValues'] | undefined, + 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 sourceVariables = new Map( + getReferenceVariableFilters(filters).flatMap(({ filter, name }) => + isDataSourceFilter(filter) ? [[name, filter] as const] : [], + ), + ); + + const isSourceOffered = (name: string, id: string) => { + const variable = sourceVariables.get(name); + const source = targets.sources.find(source => source.id === id); + if (variable == null || source == null) return false; + // An unselected connection variable stays a reference, which matches no source + const connectionName = parseVariableReference(variable.connectionId); + const connection = + connectionName == null + ? variable.connectionId + : (selections.get(connectionName)?.[0] ?? variable.connectionId); + return isSourceOfferedByVariable(source, { + allowedSourceKinds: variable.allowedSourceKinds, + connection, + }); + }; + + const describeOffer = (name: string) => { + const variable = sourceVariables.get(name); + if (variable == null) return 'no sources'; + const connectionName = parseVariableReference(variable.connectionId); + const connection = + connectionName != null + ? ` on the connection the $${connectionName} variable selects` + : variable.connectionId + ? ` on connection ${variable.connectionId}` + : ''; + return `enabled ${variable.allowedSourceKinds.join(', ')} sources${connection}`; + }; + + let config: object = tile.config; + for (const field of ['sourceId', 'connectionId'] as const) { + const name = parseVariableReference(getStringField(config, field)); + if (name == null) continue; + const subject = `Tile "${tile.id}" reads its ${field} from the $${name} variable`; + const values = selections.get(name) ?? []; + if (values.length !== 1) { + return { + error: + values.length === 0 + ? `${subject}, which has no selection. Pass one ID for it in variableValues, or save a selection on the dashboard.` + : `${subject}, which accepts exactly one value.`, + }; + } + const [id] = values; + const isOffered = + field === 'connectionId' + ? targets.connectionIds.has(id) + : isSourceOffered(name, id); + if (!isOffered) { + const offer = + field === 'connectionId' + ? 'connections on this team' + : describeOffer(name); + return { + error: `${subject}, which selects "${id}" but only offers ${offer}.`, + }; + } + config = { ...config, [field]: id }; + } + + const resolved = { ...tile, config }; + const tileError = getResolvedSourceError(resolved, tile.config, targets); + return tileError != null ? { error: tileError } : { tile: resolved }; +} + +/** + * Checks a resolved source the variable offers but the tile can't use, which + * the dashboard shows as an error in place of the tile: a kind the tile's + * chart type doesn't accept, or, for raw SQL, a source on another connection + * than the query runs on. + */ +function getResolvedSourceError( + tile: ExternalDashboardTileWithId, + storedConfig: object, + targets: ReferenceTargets, +): string | null { + if (!isConfigTile(tile)) return null; + const sourceId = getStringField(tile.config, 'sourceId'); + const source = targets.sources.find(s => s.id === sourceId); + if (source == null) return null; + const sourceName = parseVariableReference( + getStringField(storedConfig, 'sourceId'), + ); + const connectionName = parseVariableReference( + getStringField(storedConfig, 'connectionId'), + ); + + if (sourceName != null) { + let config: SavedChartConfig; + try { + config = convertToInternalTileConfig(tile).config; + } catch { + // A shape the converter refuses fails when the tile runs + return null; + } + const allowedKinds = getSavedConfigAllowedSourceKinds(config); + if (!allowedKinds.includes(source.kind)) { + return ( + `Tile "${tile.id}" reads its sourceId from the $${sourceName} variable, which ` + + `selects "${source.id}", a ${source.kind} source, but this tile only accepts ` + + `${allowedKinds.join(', ')} sources.` + ); + } + } + + if ( + (sourceName != null || connectionName != null) && + isRawSqlExternalTileConfig(tile.config) && + source.connection !== tile.config.connectionId + ) { + const from = [sourceName, connectionName] + .filter((name): name is string => name != null) + .map(name => `$${name}`) + .join(' and '); + return ( + `Tile "${tile.id}" resolves source "${source.id}" and connection ` + + `"${tile.config.connectionId}" from ${from}, but the source is on connection ` + + `"${source.connection}". Select a source on the connection the query runs on.` + ); + } + return null; +} + /** Options of each static filter, keyed by the variable name it answers to. */ function buildStaticOptionsByName( filters: ExternalDashboardFilter[] | undefined, diff --git a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts index 405e260fd9..d6065229ca 100644 --- a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts +++ b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts @@ -1519,6 +1519,185 @@ describe('dashboard router', () => { ); }); + describe('data source variables', () => { + const dataSourceFilter = { + id: new Types.ObjectId().toString(), + type: 'DATA_SOURCE' as const, + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + it('persists a tile and a filter that reference the variable', async () => { + const tile = makeTile({ sourceId: '$logs' }); + const queriedFilter = { + id: new Types.ObjectId().toString(), + type: 'QUERY_EXPRESSION' as const, + name: 'Service', + expression: 'ServiceName', + source: '$logs', + }; + + const created = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [tile], + filters: [dataSourceFilter, queriedFilter], + }) + .expect(200); + + expect(created.body.tiles[0].config.source).toBe('$logs'); + expect(created.body.filters).toEqual([dataSourceFilter, queriedFilter]); + }); + + it('rejects a reference to an unknown variable', async () => { + const res = await agent + .post('/dashboards') + .send({ ...MOCK_DASHBOARD, tiles: [makeTile({ sourceId: '$nope' })] }) + .expect(400); + + expect(JSON.stringify(res.body)).toMatch( + /does not name a data source variable/, + ); + }); + + it('rejects a variable offering no kind the reference can use', async () => { + const res = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [makeTile({ sourceId: '$logs' })], + filters: [ + { ...dataSourceFilter, allowedSourceKinds: [SourceKind.Promql] }, + ], + }) + .expect(400); + + expect(res.body.message).toMatch(/offers no kind of source/); + }); + + it('accepts a variable offering some kinds the reference cannot use', async () => { + await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [makeTile({ sourceId: '$logs' })], + filters: [ + { + ...dataSourceFilter, + allowedSourceKinds: [SourceKind.Log, SourceKind.Promql], + }, + ], + }) + .expect(200); + }); + + it('validates a PATCH of tiles against the stored filters', async () => { + const created = await agent + .post('/dashboards') + .send({ ...MOCK_DASHBOARD, filters: [dataSourceFilter] }) + .expect(200); + + await agent + .patch(`/dashboards/${created.body.id}`) + .send({ tiles: [makeTile({ sourceId: '$logs' })] }) + .expect(200); + const res = await agent + .patch(`/dashboards/${created.body.id}`) + .send({ + tiles: [ + makeTile({ sourceId: '$logs' }), + makeTile({ sourceId: '$nope' }), + ], + }) + .expect(400); + expect(res.body.message).toMatch(/does not name a data source variable/); + }); + + // Only references an update adds are checked, so editing a variable + // doesn't fail on the tiles and filters that already use it. + it('saves a filter edit that leaves stored references unsatisfied', async () => { + const adhocFilter = { + id: new Types.ObjectId().toString(), + type: 'ADHOC' as const, + name: 'Conditions', + sourceType: 'sql' as const, + sources: ['$logs'], + isBroadcastEnabled: true, + isVariableEnabled: true, + }; + const created = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [makeTile({ sourceId: '$logs' })], + filters: [dataSourceFilter, adhocFilter], + }) + .expect(200); + + await agent + .patch(`/dashboards/${created.body.id}`) + .send({ + filters: [ + { ...dataSourceFilter, allowedSourceKinds: [SourceKind.Promql] }, + adhocFilter, + ], + }) + .expect(200); + await agent + .patch(`/dashboards/${created.body.id}`) + .send({ filters: [adhocFilter] }) + .expect(200); + }); + + it('drops an alert on a tile that uses the variable', async () => { + await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [ + makeTile({ + sourceId: '$logs', + alert: makeMockAlert(webhook._id.toString()), + }), + ], + filters: [dataSourceFilter], + }) + .expect(200); + + expect(await Alert.countDocuments({ team: team._id })).toBe(0); + }); + + it('rejects a tile alert on a tile that uses the variable', async () => { + const created = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [makeTile({ sourceId: '$logs' })], + filters: [dataSourceFilter], + }) + .expect(200); + + const res = await agent + .post('/alerts') + .send( + makeAlertInput({ + dashboardId: created.body.id, + tileId: created.body.tiles[0].id, + webhookId: webhook._id.toString(), + }), + ) + .expect(400); + + expect(res.body.message).toMatch(/data source or connection variable/); + }); + }); + describe('promql-label filters', () => { const createPromqlSource = () => Source.create({ @@ -1966,6 +2145,42 @@ describe('dashboard router', () => { expect(updated.body.filters).toEqual([moved]); }); + + const connectionFilter = { + id: new Types.ObjectId().toString(), + type: 'CONNECTION' as const, + name: 'Connection', + variableName: 'conn', + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + it('accepts a connection variable as the connection', async () => { + const filter = makeSqlFilter({ connection: '$conn' }); + + const created = await agent + .post('/dashboards') + .send({ ...MOCK_DASHBOARD, filters: [connectionFilter, filter] }) + .expect(200); + + expect(created.body.filters).toEqual([connectionFilter, filter]); + }); + + it('rejects a reference that names no connection variable', async () => { + const response = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + filters: [makeSqlFilter({ connection: '$conn' })], + }) + .expect(400); + + expect(response.body.message).toMatch( + /does not name a connection variable/, + ); + }); }); describe('ad hoc filters', () => { diff --git a/packages/api/src/routers/api/dashboards.ts b/packages/api/src/routers/api/dashboards.ts index e88f39e324..ac54d3e74a 100644 --- a/packages/api/src/routers/api/dashboards.ts +++ b/packages/api/src/routers/api/dashboards.ts @@ -1,9 +1,11 @@ import { + getVariableReferenceError, validateDashboardFilterModes, validateDashboardFilterOptionUniqueness, validateDashboardFilterVariableNames, } from '@hyperdx/common-utils/dist/dashboardValidation'; import { isSqlQueryFilter } from '@hyperdx/common-utils/dist/filters'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; import { DashboardFilter, DashboardSchema, @@ -77,7 +79,10 @@ async function validateFilterSources( filters: DashboardFilter[] = [], existingFilters: DashboardFilter[] = [], ): Promise { - const refs = getChangedFilterSourceRefs(filters, existingFilters); + const refs = getChangedFilterSourceRefs(filters, existingFilters).filter( + // Variable references are checked by validateDashboardVariableReferences + ref => parseVariableReference(ref.id) == null, + ); if (refs.length === 0) return null; return getFilterSourceRefError(refs, await getSources(teamId.toString())); } @@ -85,7 +90,8 @@ async function validateFilterSources( /** * Rejects SQL_QUERY filters whose connection doesn't belong to the team. As in * `validateFilterSources`, a connection the stored filter with the same ID - * already used is skipped. Returns an error message, or null. + * already used is skipped, and so is a variable reference. Returns an error + * message, or null. */ async function validateFilterConnections( teamId: ObjectId, @@ -101,7 +107,10 @@ async function validateFilterConnections( filters .filter(isSqlQueryFilter) .filter( - filter => existingConnectionById.get(filter.id) !== filter.connection, + filter => + // Variable references are checked by validateDashboardVariableReferences + parseVariableReference(filter.connection) == null && + existingConnectionById.get(filter.id) !== filter.connection, ) .map(filter => filter.connection), ); @@ -181,10 +190,9 @@ router.post( // dashboard to the provisioner. const dashboard = _.omit(req.body, 'provisioned'); - const filterError = await validateFilterReferences( - teamId, - req.body.filters, - ); + const filterError = + getVariableReferenceError(req.body.tiles, req.body.filters) ?? + (await validateFilterReferences(teamId, req.body.filters)); if (filterError != null) { return res.status(400).json({ message: filterError }); } @@ -229,11 +237,19 @@ router.patch( // null still signals field removal downstream. const updates = DashboardWithoutIdSchema.partial().parse(req.body); - const filterError = await validateFilterReferences( - teamId, - req.body.filters, - dashboard.filters, - ); + const filterError = + // Only references this update adds are checked, so a filter edit + // can't fail on tiles and filters it didn't touch + getVariableReferenceError( + req.body.tiles ?? dashboard.tiles, + req.body.filters ?? dashboard.filters, + dashboard, + ) ?? + (await validateFilterReferences( + teamId, + req.body.filters, + dashboard.filters, + )); if (filterError != null) { return res.status(400).json({ message: filterError }); } 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 92a72d9767..88faec017f 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 @@ -6329,6 +6329,35 @@ describe('External API v2 Dashboards - new format', () => { expect(response.body.message).toContain(connectionId); }); + it('accepts a connection variable as the connection', async () => { + const response = await sendFilters([ + { + id: new ObjectId().toString(), + type: 'CONNECTION', + name: 'Connection', + variableName: 'conn', + }, + sqlFilterInput({ connectionId: '$conn' }), + ]); + + expect(response.status).toBe(200); + expect(response.body.data.filters[1]).toMatchObject({ + type: 'SQL_QUERY', + connectionId: '$conn', + }); + }); + + it('rejects a reference that names no connection variable', async () => { + const response = await sendFilters([ + sqlFilterInput({ connectionId: '$conn' }), + ]); + + expect(response.status).toBe(400); + expect(response.body.message).toMatch( + /does not name a connection variable/, + ); + }); + it.each([ ['broadcast enabled', { isBroadcastEnabled: true }], ['not variable-enabled', { isVariableEnabled: false }], @@ -8511,6 +8540,381 @@ describe('External API v2 Dashboards - new format', () => { }); }); + describe('reference variables', () => { + const connectionFilter = { + type: 'CONNECTION' as const, + name: 'Connection', + variableName: 'conn', + }; + const dataSourceFilter = { + type: 'DATA_SOURCE' as const, + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + connectionId: '$conn', + }; + const rawSqlTile = { + name: 'Raw SQL', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + configType: 'sql', + displayType: 'table', + connectionId: '$conn', + sqlTemplate: 'SELECT 1', + }, + }; + + it('round-trips the variables, their values and the tiles that use them', async () => { + const globalConnectionFilter = { + ...connectionFilter, + isGlobalRequirement: true, + }; + const savedFilterValues = [ + { type: 'variable', name: 'conn', values: [connection._id.toString()] }, + { + type: 'variable', + name: 'traces', + values: [traceSource._id.toString()], + }, + ]; + const created = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [makeExternalTile({ sourceId: '$traces' }), rawSqlTile], + tags: [], + filters: [globalConnectionFilter, dataSourceFilter], + savedFilterValues, + }) + .expect(200); + + const fetched = await authRequest( + 'get', + `${BASE_URL}/${created.body.data.id}`, + ).expect(200); + expect(fetched.body.data.filters).toEqual([ + expect.objectContaining(globalConnectionFilter), + expect.objectContaining(dataSourceFilter), + ]); + expect(fetched.body.data.tiles.map(t => t.config)).toEqual([ + expect.objectContaining({ sourceId: '$traces' }), + expect.objectContaining({ connectionId: '$conn' }), + ]); + expect(fetched.body.data.savedFilterValues).toEqual(savedFilterValues); + + const echoed = await authRequest( + 'put', + `${BASE_URL}/${created.body.data.id}`, + ) + .send(fetched.body.data) + .expect(200); + expect(echoed.body.data.filters).toEqual(fetched.body.data.filters); + expect(echoed.body.data.tiles.map(t => t.config)).toEqual( + fetched.body.data.tiles.map(t => t.config), + ); + }); + + it('rejects a tile referencing an undeclared variable', async () => { + const res = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [makeExternalTile({ sourceId: '$traces' })], + tags: [], + }) + .expect(400); + expect(res.body.message).toMatch(/does not name a data source variable/); + }); + + it('rejects a connection reference to an undeclared connection variable', async () => { + const res = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [rawSqlTile], + tags: [], + filters: [{ ...dataSourceFilter, connectionId: undefined }], + }) + .expect(400); + expect(res.body.message).toMatch(/does not name a connection variable/); + }); + + it('accepts a PromQL tile and PROMETHEUS_LABEL filter on a PromQL data source variable', async () => { + await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [ + { + name: 'PromQL', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + configType: 'promql', + displayType: 'line', + sourceId: '$prom', + expressions: [{ expression: 'up' }], + }, + }, + ], + tags: [], + filters: [ + { + type: 'DATA_SOURCE', + name: 'PromQL source', + variableName: 'prom', + allowedSourceKinds: [SourceKind.Promql], + }, + { + type: 'PROMETHEUS_LABEL', + name: 'Job', + sourceId: '$prom', + label: 'job', + }, + ], + }) + .expect(200); + }); + + it('accepts an ADHOC filter whose sources reference a data source variable', async () => { + const adhocFilter = { + type: 'ADHOC', + name: 'Conditions', + sourceType: 'sql', + sources: ['$traces'], + appliesToSourceIds: ['$traces'], + }; + await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [], + tags: [], + filters: [omit(dataSourceFilter, 'connectionId'), adhocFilter], + }) + .expect(200); + + const res = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [], + tags: [], + filters: [adhocFilter], + }) + .expect(400); + expect(res.body.message).toMatch(/does not name a data source variable/); + }); + + it('accepts a raw SQL tile with a fixed source on a connection variable', async () => { + await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [ + { + ...rawSqlTile, + config: { + ...rawSqlTile.config, + sourceId: traceSource._id.toString(), + }, + }, + ], + tags: [], + filters: [connectionFilter], + }) + .expect(200); + }); + + it("rejects a raw SQL tile whose data source variable is limited to another connection than the tile's", async () => { + const otherConnection = await Connection.create({ + team: team._id, + name: 'Other Connection', + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + + const res = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [ + { + ...rawSqlTile, + config: { + ...rawSqlTile.config, + connectionId: connection._id.toString(), + sourceId: '$traces', + }, + }, + ], + tags: [], + filters: [ + { + ...dataSourceFilter, + connectionId: otherConnection._id.toString(), + }, + ], + }) + .expect(400); + expect(res.body.message).toBe( + 'The following source IDs do not match the specified connections: $traces', + ); + }); + + it('checks a PUT without filters against the stored variables', async () => { + const dashboard = await createTestDashboard({ + filters: [ + { id: new ObjectId().toString(), ...connectionFilter }, + { + id: new ObjectId().toString(), + ...omit(dataSourceFilter, 'connectionId'), + connection: '$conn', + }, + ], + }); + + await authRequest('put', `${BASE_URL}/${dashboard._id}`) + .send({ + name: 'Variable Dashboard', + tiles: [makeExternalTile({ sourceId: '$traces' })], + tags: [], + }) + .expect(200); + }); + + // Only references an update adds are checked, so editing a variable + // doesn't fail on the tiles that already use it. + it('accepts a PUT whose filter change leaves stored references unsatisfied', async () => { + const variable = { ...dataSourceFilter, connectionId: undefined }; + const created = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [makeExternalTile({ sourceId: '$traces' })], + tags: [], + filters: [variable], + }) + .expect(200); + const fetched = await authRequest( + 'get', + `${BASE_URL}/${created.body.data.id}`, + ).expect(200); + const url = `${BASE_URL}/${created.body.data.id}`; + const [storedVariable] = fetched.body.data.filters; + + await authRequest('put', url) + .send({ + ...fetched.body.data, + filters: [ + { ...storedVariable, allowedSourceKinds: [SourceKind.Promql] }, + ], + }) + .expect(200); + await authRequest('put', url) + .send({ ...fetched.body.data, filters: [] }) + .expect(200); + + const res = await authRequest('put', url) + .send({ + ...fetched.body.data, + filters: [], + tiles: [ + ...fetched.body.data.tiles, + makeExternalTile({ sourceId: '$nope' }), + ], + }) + .expect(400); + expect(res.body.message).toMatch(/does not name a data source variable/); + }); + + it("accepts a PUT that moves a raw SQL tile's data source variable to another connection", async () => { + const otherConnection = await Connection.create({ + team: team._id, + name: 'Other Connection', + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + const created = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [ + { + ...rawSqlTile, + config: { + ...rawSqlTile.config, + connectionId: connection._id.toString(), + sourceId: '$traces', + }, + }, + ], + tags: [], + filters: [ + { ...dataSourceFilter, connectionId: connection._id.toString() }, + ], + }) + .expect(200); + const fetched = await authRequest( + 'get', + `${BASE_URL}/${created.body.data.id}`, + ).expect(200); + const [storedVariable] = fetched.body.data.filters; + + await authRequest('put', `${BASE_URL}/${created.body.data.id}`) + .send({ + ...fetched.body.data, + filters: [ + { + ...storedVariable, + connectionId: otherConnection._id.toString(), + }, + ], + }) + .expect(200); + }); + + it('deletes the alert of a tile that moves to a data source variable', async () => { + const tile = makeExternalTile({ sourceId: traceSource._id.toString() }); + const created = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [tile], + tags: [], + filters: [connectionFilter, dataSourceFilter], + }) + .expect(200); + const { id: dashboardId, tiles } = created.body.data; + const webhook = await Webhook.create({ + name: 'Test Webhook', + service: WebhookService.Slack, + url: 'https://hooks.slack.com/test', + team: team._id, + }); + const alert = await Alert.create({ + team: team._id, + dashboard: dashboardId, + tileId: tiles[0].id, + source: AlertSource.TILE, + threshold: 100, + interval: '1h', + thresholdType: AlertThresholdType.ABOVE, + channel: { type: 'webhook', webhookId: webhook._id.toString() }, + }); + + await authRequest('put', `${BASE_URL}/${dashboardId}`) + .send({ + ...created.body.data, + tiles: [ + { + ...tiles[0], + config: { ...tiles[0].config, sourceId: '$traces' }, + }, + ], + }) + .expect(200); + + expect(await Alert.findById(alert._id)).toBeNull(); + }); + }); + describe('ad hoc filters', () => { const adhocFilter = () => ({ id: new ObjectId().toString(), diff --git a/packages/api/src/routers/external-api/v2/dashboards.ts b/packages/api/src/routers/external-api/v2/dashboards.ts index 0b6bacea09..511775a035 100644 --- a/packages/api/src/routers/external-api/v2/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/dashboards.ts @@ -705,7 +705,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "line" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -792,7 +792,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "stacked_bar" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -862,7 +862,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "stacked_line" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -938,7 +938,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "table" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1012,7 +1012,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "number" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1071,7 +1071,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "pie" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1124,7 +1124,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "bar" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1217,7 +1217,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "distribution" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1265,7 +1265,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "series" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1314,7 +1314,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "search" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: string @@ -1345,7 +1345,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "event_patterns" * sourceId: * type: string - * description: ID of the data source to mine patterns from. + * description: ID of the data source to mine patterns from, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: string @@ -1395,7 +1395,9 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "sql" * connectionId: * type: string - * description: ID of the ClickHouse connection to execute the query against. + * description: | + * ID of the ClickHouse connection to execute the query against, or + * `$connectionVariable` of a CONNECTION filter on the dashboard. * example: "65f5e4a3b9e77c001a567890" * sqlTemplate: * type: string @@ -1404,7 +1406,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "SELECT count() FROM otel_logs WHERE timestamp > now() - INTERVAL 1 HOUR" * sourceId: * type: string - * description: Optional ID of the data source associated with this Raw SQL chart. Used for applying dashboard filters. + * description: Optional ID of the data source associated with this Raw SQL chart, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. Used for applying dashboard filters. * example: "65f5e4a3b9e77c001a567890" * numberFormat: * $ref: '#/components/schemas/NumberFormat' @@ -2420,6 +2422,8 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * - $ref: '#/components/schemas/PrometheusLabelFilterInput' * - $ref: '#/components/schemas/SqlQueryFilterInput' * - $ref: '#/components/schemas/AdhocFilterInput' + * - $ref: '#/components/schemas/DataSourceFilterInput' + * - $ref: '#/components/schemas/ConnectionFilterInput' * discriminator: * propertyName: type * mapping: @@ -2428,6 +2432,145 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * PROMETHEUS_LABEL: '#/components/schemas/PrometheusLabelFilterInput' * SQL_QUERY: '#/components/schemas/SqlQueryFilterInput' * ADHOC: '#/components/schemas/AdhocFilterInput' + * DATA_SOURCE: '#/components/schemas/DataSourceFilterInput' + * CONNECTION: '#/components/schemas/ConnectionFilterInput' + * + * DataSourceFilterInput: + * type: object + * description: | + * A variable whose single, required value is a source. Tiles reference it + * as `$variableName` in their sourceId, and other filters in sourceId or + * appliesToSourceIds, so viewers can switch the source those read. Tiles + * that use it do not load until a source is selected, and cannot have + * alerts. + * required: + * - type + * - name + * - allowedSourceKinds + * properties: + * type: + * type: string + * enum: [DATA_SOURCE] + * description: Filter type discriminator. Must be "DATA_SOURCE". + * example: "DATA_SOURCE" + * name: + * type: string + * minLength: 1 + * description: Display name of the variable's dropdown + * example: "Logs source" + * variableName: + * type: string + * maxLength: 64 + * pattern: '^[a-zA-Z][a-zA-Z0-9_]*$' + * description: Token tiles and filters reference the selected source by, as `$variableName`. + * example: "logs" + * isGlobalRequirement: + * type: boolean + * default: false + * description: | + * Blocks every tile on the dashboard until a value is selected. False + * (the default) blocks only the tiles that reference the variable. + * example: true + * minSelections: + * type: integer + * enum: [1] + * default: 1 + * description: Must be 1 if provided. The variable always requires a selection. + * example: 1 + * maxSelections: + * type: integer + * enum: [1] + * default: 1 + * description: Must be 1 if provided. The variable is always single-select. + * example: 1 + * isBroadcastEnabled: + * type: boolean + * enum: [false] + * default: false + * description: Must be false or omitted. + * example: false + * isVariableEnabled: + * type: boolean + * enum: [true] + * default: true + * description: Must be true if provided, and is true when omitted. + * example: true + * allowedSourceKinds: + * type: array + * minItems: 1 + * items: + * type: string + * enum: [log, trace, session, metric, promql] + * description: | + * Kinds of sources offered. A field can reference the variable if it + * accepts at least one listed kind. A tile whose selected source is a + * kind it cannot use shows an error instead of running. + * example: ["log"] + * connectionId: + * type: string + * description: | + * Optional connection the offered sources are limited to: a + * connection ID, or `$name` of a CONNECTION filter on the dashboard. + * example: "$conn" + * + * ConnectionFilterInput: + * type: object + * description: | + * A variable whose single, required value is a connection. Raw SQL tiles + * reference it as `$variableName` in their connectionId, and data source + * variables and SQL query filters in theirs. Tiles that use it do not load + * until a connection is selected, and cannot have alerts. + * required: + * - type + * - name + * properties: + * type: + * type: string + * enum: [CONNECTION] + * description: Filter type discriminator. Must be "CONNECTION". + * example: "CONNECTION" + * name: + * type: string + * minLength: 1 + * description: Display name of the variable's dropdown + * example: "Connection" + * variableName: + * type: string + * maxLength: 64 + * pattern: '^[a-zA-Z][a-zA-Z0-9_]*$' + * description: Token raw SQL tiles reference the selected connection by, as `$variableName`. + * example: "conn" + * isGlobalRequirement: + * type: boolean + * default: false + * description: | + * Blocks every tile on the dashboard until a value is selected. False + * (the default) blocks only the tiles that reference the variable. + * example: true + * minSelections: + * type: integer + * enum: [1] + * default: 1 + * description: Must be 1 if provided. The variable always requires a selection. + * example: 1 + * maxSelections: + * type: integer + * enum: [1] + * default: 1 + * description: Must be 1 if provided. The variable is always single-select. + * example: 1 + * isBroadcastEnabled: + * type: boolean + * enum: [false] + * default: false + * description: Must be false or omitted. + * example: false + * isVariableEnabled: + * type: boolean + * enum: [true] + * default: true + * description: Must be true if provided, and is true when omitted. + * example: true * * QueryExpressionFilterInput: * type: object @@ -2458,7 +2601,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "environment" * sourceId: * type: string - * description: Source ID this dashboard filter key applies to + * description: Source ID this dashboard filter key applies to, or `$name` of a DATA_SOURCE filter on the dashboard * example: "65f5e4a3b9e77c001a111111" * sourceMetricType: * type: string @@ -2762,7 +2905,9 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "Environment" * connectionId: * type: string - * description: ID of the ClickHouse connection the query runs on. + * description: | + * ClickHouse connection the query runs on: a connection ID, or + * `$name` of a CONNECTION filter on the dashboard. * example: "65f5e4a3b9e77c001a567890" * sqlTemplate: * type: string @@ -2854,7 +2999,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * minItems: 1 * items: * type: string - * description: IDs of the sources whose keys and values the filter suggests, all of sourceType. + * description: IDs of the sources whose keys and values the filter suggests, all of sourceType, or `$name` of data source variables. * example: ["65f5e4a3b9e77c001a111111"] * where: * type: string @@ -2874,8 +3019,8 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * type: string * description: | * IDs of the sources whose tiles the conditions apply to, all of - * sourceType. Omit or send an empty array to apply to the tiles of - * the filter's sources. + * sourceType, or `$name` of data source variables. Omit or send an + * empty array to apply to the tiles of the filter's sources. * example: ["65f5e4a3b9e77c001a111111"] * isBroadcastEnabled: * type: boolean diff --git a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts index 9ab3802983..200f6f26bb 100644 --- a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts +++ b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts @@ -8,6 +8,7 @@ import { MetricsDataType, PromqlReducer, PromqlSavedChartConfig, + SourceKind, } from '@hyperdx/common-utils/dist/types'; import mongoose from 'mongoose'; import { z } from 'zod'; @@ -539,6 +540,30 @@ describe('convertToExternalDashboard orphan-ref heal', () => { expect(hidden.savedFilterValues).toEqual([adhocValue]); }); + it('keeps data source variables that offer promql sources with hidePromql', () => { + const doc = makeDoc({ + filters: [ + { + id: 'mixed', + type: 'DATA_SOURCE', + name: 'mixed', + variableName: 'mixed', + allowedSourceKinds: [SourceKind.Metric, SourceKind.Promql], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ], + }); + + expect( + convertToExternalDashboard(doc, { hidePromql: true }).filters?.map( + f => f.id, + ), + ).toEqual(['mixed']); + }); + // seriesLimit is three-state (matching the internal schema): omitted = // default cap, 0 = unlimited, positive N = top-N. All three must survive a // GET->PUT round-trip: 0 and N pass through, null maps to absent (the diff --git a/packages/api/src/routers/external-api/v2/utils/dashboards.ts b/packages/api/src/routers/external-api/v2/utils/dashboards.ts index 0590b30fc3..fbde606d52 100644 --- a/packages/api/src/routers/external-api/v2/utils/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/utils/dashboards.ts @@ -6,6 +6,8 @@ import { TIME_SERIES_DISPLAY_TYPE_BY_NAME, } from '@hyperdx/common-utils/dist/core/utils'; import { + collectRefinementIssues, + getVariableReferenceError, validateDashboardContainersStructure, validateDashboardFilterFieldGating, validateDashboardFilterModes, @@ -24,6 +26,10 @@ import { isPromqlSavedChartConfig, isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; +import { + getSourceVariableDeclarations, + parseVariableReference, +} from '@hyperdx/common-utils/dist/referenceVariables'; import { AggregateFunctionSchema, BuilderSavedChartConfig, @@ -1327,7 +1333,12 @@ function getMissingSources( const existingSourceIds = new Set( sources.map(source => source._id.toString()), ); - return [...sourceIds].filter(sourceId => !existingSourceIds.has(sourceId)); + // Variable references are checked by validateDashboardVariableReferences + return [...sourceIds].filter( + sourceId => + parseVariableReference(sourceId) == null && + !existingSourceIds.has(sourceId), + ); } /** @@ -1585,16 +1596,18 @@ async function getMissingConnections( filters: (ExternalDashboardFilter | ExternalDashboardFilterWithId)[] = [], ): Promise { const connectionIds = new Set(); + // Variable references are checked by validateDashboardVariableReferences + const addConnectionId = (id: string | undefined) => { + if (id && parseVariableReference(id) == null) connectionIds.add(id); + }; for (const tile of tiles) { if (isConfigTile(tile) && isRawSqlExternalTileConfig(tile.config)) { - connectionIds.add(tile.config.connectionId); + addConnectionId(tile.config.connectionId); } } for (const filter of filters) { - if ('connectionId' in filter) { - connectionIds.add(filter.connectionId); - } + if ('connectionId' in filter) addConnectionId(filter.connectionId); } if (connectionIds.size === 0) return []; @@ -1697,8 +1710,26 @@ export function convertExternalFiltersToInternal( function getSourceConnectionMismatches( sources: SourceForValidation[], tiles: ExternalDashboardTileWithId[], + filters: DashboardFilter[], + existingTiles: DashboardDocument['tiles'] = [], ): string[] { + const existingConfigById = new Map( + existingTiles.map(tile => [tile.id, tile.config]), + ); const sourceById = new Map(sources.map(s => [s._id.toString(), s])); + const variableConnectionByName = new Map( + getSourceVariableDeclarations(filters).map(({ name, connection }) => [ + name, + connection, + ]), + ); + // A source variable's sources are on its declared connection, if any + const getSourceConnection = (sourceId: string) => { + const name = parseVariableReference(sourceId); + return name == null + ? sourceById.get(sourceId)?.connection.toString() + : variableConnectionByName.get(name); + }; const mismatched: string[] = []; for (const tile of tiles) { @@ -1707,9 +1738,30 @@ function getSourceConnectionMismatches( isRawSqlExternalTileConfig(tile.config) && tile.config.sourceId ) { - const source = sourceById.get(tile.config.sourceId); - if (source && source.connection.toString() !== tile.config.connectionId) { - mismatched.push(tile.config.sourceId); + const { connectionId, sourceId } = tile.config; + // Like other variable references, one the update leaves as it was + // isn't checked again; the dashboard shows the mismatch instead + const existingConfig = tile.id + ? existingConfigById.get(tile.id) + : undefined; + if ( + parseVariableReference(sourceId) != null && + existingConfig != null && + Reflect.get(existingConfig, 'source') === sourceId && + Reflect.get(existingConfig, 'connection') === connectionId + ) { + continue; + } + const sourceConnection = getSourceConnection(sourceId); + // A connection reference is only known once selected, so compare two + // IDs, or two references, but not one of each + if ( + sourceConnection != null && + (parseVariableReference(sourceConnection) == null) === + (parseVariableReference(connectionId) == null) && + sourceConnection !== connectionId + ) { + mismatched.push(sourceId); } } } @@ -1724,9 +1776,16 @@ export type TileValidationContext = { tiles: ExternalDashboardTileWithId[]; /** Filters to check for missing source IDs (create/full-update paths). */ filters?: (ExternalDashboardFilter | ExternalDashboardFilterWithId)[]; - /** Existing internal tiles for scoping heatmap change detection (update paths). */ + /** + * Existing internal tiles for scoping heatmap change detection and the + * variable reference check (update paths). + */ existingTiles?: DashboardDocument['tiles']; - /** Existing filters, whose source references aren't re-checked (update paths). */ + /** + * Existing internal filters (update paths). Their source references aren't + * re-checked, and tile variable references are checked against them when + * the request carries no `filters`. + */ existingFilters?: DashboardFilter[]; /** Container set to validate tile containerId/tabId refs against. */ containers: DashboardContainer[]; @@ -1753,6 +1812,26 @@ export async function validateDashboardTiles( return tileRefIssues.join('; '); } + // Stored IDs are kept so that the references an update leaves as they were + // can be told apart from the ones it adds, which are the only ones checked + const referenceFilters = filters + ? convertExternalFiltersToInternal( + filters, + new Set(existingFilters?.map(filter => filter.id)), + ) + : (existingFilters ?? []); + const variableReferenceError = getVariableReferenceError( + convertExternalTilesToInternal( + tiles, + new Set(existingTiles?.map(tile => tile.id)), + ), + referenceFilters, + existingTiles && { tiles: existingTiles, filters: existingFilters }, + ); + if (variableReferenceError) { + return variableReferenceError; + } + // Fetch sources/connections/onClick targets in parallel. const [ sources, @@ -1777,6 +1856,8 @@ export async function validateDashboardTiles( const sourceConnectionMismatches = getSourceConnectionMismatches( sources, tiles, + referenceFilters, + existingTiles, ); if (sourceConnectionMismatches.length > 0) { return `The following source IDs do not match the specified connections: ${sourceConnectionMismatches.join(', ')}`; @@ -1816,10 +1897,10 @@ export async function validateDashboardTiles( // PromQL tiles query through their source's connection and TimeSeries // table, which only a PromQL source carries. const nonPromqlTileSourceIds = getInvalidSourceIds( - getChangedPromqlTileSourceIds(tiles, existingTiles).map(id => ({ - id, - kinds: [SourceKind.Promql], - })), + getChangedPromqlTileSourceIds(tiles, existingTiles) + // A reference's kinds are checked by validateDashboardVariableReferences + .filter(id => parseVariableReference(id) == null) + .map(id => ({ id, kinds: [SourceKind.Promql] })), sources, ); if (nonPromqlTileSourceIds.length > 0) { @@ -1836,7 +1917,7 @@ export async function validateDashboardTiles( translateExternalFilterToFilter({ id: '', ...filter }), ), existingFilters, - ), + ).filter(ref => parseVariableReference(ref.id) == null), sources, ); if (filterSourceError != null) return filterSourceError; @@ -1951,15 +2032,13 @@ export function collectTileContainerRefIssues( containers: DashboardContainer[], tiles: ExternalDashboardTileWithId[], ): string[] { - const schema = z.object({}).superRefine((_, ctx) => { - const containerById = new Map( - containers.map(c => [c.id, c]), - ); - validateDashboardTileContainerRefs(containerById, tiles, ctx); - }); - const result = schema.safeParse({}); - if (result.success) return []; - return result.error.issues.map(issue => { + const containerById = new Map( + containers.map(c => [c.id, c]), + ); + const issues = collectRefinementIssues(ctx => + validateDashboardTileContainerRefs(containerById, tiles, ctx), + ); + return issues.map(issue => { const path = issue.path.length > 0 ? `${issue.path.join('.')}: ` : ''; return `${path}${issue.message}`; }); diff --git a/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts b/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts index 3e17594813..c91e79b5b2 100644 --- a/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts +++ b/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts @@ -143,6 +143,41 @@ describe('provisionDashboards', () => { // rejects the legacy enum and `readDashboardFiles` skips the file // outright, so a provisioned dashboard authored against #2265 // wouldn't ship at all. + it('parses a tile that references a declared data source variable', () => { + fs.writeFileSync( + path.join(tmpDir, 'source-variable.json'), + JSON.stringify({ + name: 'Source Variable', + tiles: [makeTile({ sourceId: '$logs' })], + filters: [ + { + id: 'ds', + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: ['log'], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ], + }), + ); + expect(readDashboardFiles(tmpDir)).toHaveLength(1); + }); + + it('skips a tile that references an undeclared data source variable', () => { + fs.writeFileSync( + path.join(tmpDir, 'unknown-variable.json'), + JSON.stringify({ + name: 'Unknown Variable', + tiles: [makeTile({ sourceId: '$logs' })], + }), + ); + expect(readDashboardFiles(tmpDir)).toEqual([]); + }); + it('migrates legacy chart-N tile colors before schema validation', () => { const tile = makeTile(); (tile.config as any).color = 'chart-1'; diff --git a/packages/api/src/tasks/provisionDashboards/index.ts b/packages/api/src/tasks/provisionDashboards/index.ts index cf10427c72..4199d96182 100644 --- a/packages/api/src/tasks/provisionDashboards/index.ts +++ b/packages/api/src/tasks/provisionDashboards/index.ts @@ -1,4 +1,7 @@ -import { validateDashboardFilterOptionUniqueness } from '@hyperdx/common-utils/dist/dashboardValidation'; +import { + validateDashboardFilterOptionUniqueness, + validateDashboardVariableReferences, +} from '@hyperdx/common-utils/dist/dashboardValidation'; import { DashboardWithoutId, DashboardWithoutIdSchema, @@ -30,8 +33,10 @@ function migrateLegacyDashboardTileColorsRaw(raw: unknown): unknown { } const provisionedDashboardSchema = DashboardWithoutIdSchema.superRefine( - (data, ctx) => - validateDashboardFilterOptionUniqueness(data.filters ?? [], ctx), + (data, ctx) => { + validateDashboardFilterOptionUniqueness(data.filters ?? [], ctx); + validateDashboardVariableReferences(data.tiles, data.filters ?? [], ctx); + }, ); export function readDashboardFiles(dir: string): DashboardWithoutId[] { diff --git a/packages/api/src/utils/externalApi.ts b/packages/api/src/utils/externalApi.ts index a626c5e49f..164e59d7f3 100644 --- a/packages/api/src/utils/externalApi.ts +++ b/packages/api/src/utils/externalApi.ts @@ -269,6 +269,15 @@ export function translateFilterToExternalFilter( connectionId: filter.connection.toString(), }; + case 'DATA_SOURCE': + return { + ...omit(filter, 'connection'), + ...(filter.connection ? { connectionId: filter.connection } : {}), + }; + + case 'CONNECTION': + return filter; + case 'QUERY_EXPRESSION': { // Ignore variableName and appliesToSourceIds if the filter is not in a mode that uses them const ignoredKeys = [ @@ -310,6 +319,15 @@ export function translateExternalFilterToFilter( case 'QUERY_EXPRESSION': return { ...omit(filter, 'sourceId'), source: filter.sourceId }; + case 'DATA_SOURCE': + return { + ...omit(filter, 'connectionId'), + ...(filter.connectionId ? { connection: filter.connectionId } : {}), + }; + + case 'CONNECTION': + return filter; + default: filter satisfies never; return filter; diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index 05cd5c23d8..87df22e508 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -1,4 +1,5 @@ import { validateChartConfigFormulas } from '@hyperdx/common-utils/dist/dashboardValidation'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; import { addDuplicateTileIdIssues, AdhocDashboardFilterSchema, @@ -12,8 +13,10 @@ import { AlertThresholdType, BackgroundChartSchema, ChartPaletteTokenSchema, + ConnectionDashboardFilterSchema, DASHBOARD_CONTAINER_ID_MAX, DASHBOARD_MAX_TILES, + DataSourceDashboardFilterSchema, HeatmapScaleTypeSchema, LineInterpolationSchema, MAX_LEGEND_TEMPLATE_LENGTH, @@ -54,6 +57,17 @@ export const objectIdSchema = z.string().refine(val => { return Types.ObjectId.isValid(val); }, 'Invalid ObjectId'); +/** + * A source or connection field: an ObjectId, or a `$name` reference to the + * dashboard's data source or connection variable of that name. + */ +export const objectIdOrVariableReferenceSchema = z + .string() + .refine( + val => Types.ObjectId.isValid(val) || parseVariableReference(val) != null, + 'Invalid ObjectId or $variable reference', + ); + /** * A repeatable query param. Express's parser yields a bare string for a single * occurrence and an array for several, and `?p[]=x` lands on the same key as @@ -175,7 +189,7 @@ export { tagsSchema }; const externalQueryExpressionFilterShape = QueryExpressionDashboardFilterSchema.omit({ source: true }).extend({ - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, }); // A static filter's mode flags each accept exactly one value, so callers may @@ -188,7 +202,7 @@ const externalStaticListFilterShape = StaticListDashboardFilterSchema.extend({ const externalPromqlLabelFilterShape = PromqlLabelDashboardFilterSchema.omit({ source: true, }).extend({ - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, isBroadcastEnabled: z.literal(false).default(false), isVariableEnabled: z.literal(true).default(true), }); @@ -197,19 +211,39 @@ const externalPromqlLabelFilterShape = PromqlLabelDashboardFilterSchema.omit({ const externalSqlQueryFilterShape = SqlQueryDashboardFilterSchema.omit({ connection: true, }).extend({ - connectionId: objectIdSchema, + connectionId: objectIdOrVariableReferenceSchema, isBroadcastEnabled: z.literal(false).default(false), isVariableEnabled: z.literal(true).default(true), }); // Field names match the stored filter, so it needs no translation. const externalAdhocFilterShape = AdhocDashboardFilterSchema.extend({ - sources: z.array(objectIdSchema).min(1), - appliesToSourceIds: z.array(objectIdSchema).optional(), + sources: z.array(objectIdOrVariableReferenceSchema).min(1), + appliesToSourceIds: z.array(objectIdOrVariableReferenceSchema).optional(), isBroadcastEnabled: z.literal(true).default(true), isVariableEnabled: z.literal(true).default(true), }); +// Reference variables are always single-select and required, so these +// fields, like the mode flags, accept one value each and may be omitted. +const referenceVariableFixedFields = { + minSelections: z.literal(1).default(1), + maxSelections: z.literal(1).default(1), + isBroadcastEnabled: z.literal(false).default(false), + isVariableEnabled: z.literal(true).default(true), +}; + +const externalDataSourceFilterShape = DataSourceDashboardFilterSchema.omit({ + connection: true, +}).extend({ + connectionId: objectIdOrVariableReferenceSchema.optional(), + ...referenceVariableFixedFields, +}); + +const externalConnectionFilterShape = ConnectionDashboardFilterSchema.extend( + referenceVariableFixedFields, +); + export const externalDashboardFilterSchemaWithId = z.discriminatedUnion( 'type', [ @@ -218,6 +252,8 @@ export const externalDashboardFilterSchemaWithId = z.discriminatedUnion( externalPromqlLabelFilterShape.strict(), externalSqlQueryFilterShape.strict(), externalAdhocFilterShape.strict(), + externalDataSourceFilterShape.strict(), + externalConnectionFilterShape.strict(), ], ); @@ -236,6 +272,8 @@ export const externalDashboardFilterSchema = z.discriminatedUnion('type', [ externalPromqlLabelFilterShape.omit({ id: true }).strict(), externalSqlQueryFilterShape.omit({ id: true }).strict(), externalAdhocFilterShape.omit({ id: true }).strict(), + externalDataSourceFilterShape.omit({ id: true }).strict(), + externalConnectionFilterShape.omit({ id: true }).strict(), ]); export type ExternalDashboardFilter = z.infer< @@ -356,9 +394,9 @@ export type ExternalDashboardSelectItem = z.infer< const externalDashboardRawSqlChartConfigBaseSchema = z.object({ configType: z.literal('sql'), - connectionId: objectIdSchema, + connectionId: objectIdOrVariableReferenceSchema, sqlTemplate: z.string().max(100000), - sourceId: objectIdSchema.optional(), + sourceId: objectIdOrVariableReferenceSchema.optional(), numberFormat: NumberFormatSchema.optional(), }); @@ -381,7 +419,7 @@ const externalFormulasSchema = z.array(MetricFormulaSchema).max(10).optional(); const externalShowOperandSeriesSchema = z.boolean().optional(); const externalDashboardTimeChartConfigSchema = z.object({ - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardSelectItemSchema).min(1).max(20), groupBy: z.string().max(10000).optional(), asRatio: z.boolean().optional(), @@ -452,7 +490,7 @@ const externalDashboardStackedLineRawSqlChartConfigSchema = const externalDashboardTableChartConfigSchema = z.object({ displayType: z.literal('table'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardSelectItemSchema).min(1).max(20), groupBy: z.string().max(10000).optional(), having: z.string().max(10000).optional(), @@ -492,7 +530,7 @@ const externalDashboardCategoricalBarRawSqlChartConfigSchema = const externalDashboardNumberChartConfigSchema = z.object({ displayType: z.literal('number'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, // Exactly one select item unless `formulas` is set: a formula number tile // displays the (single) formula value and its select entries are the // formula's operands (e.g. A / (A + B)). The one-item rule for @@ -532,7 +570,7 @@ const externalDashboardNumberChartConfigSchema = z.object({ const externalDashboardPieChartConfigSchema = z.object({ displayType: z.literal('pie'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardSelectItemSchema).length(1), groupBy: z.string().max(10000).optional(), orderBy: z.string().max(10000).optional(), @@ -543,7 +581,7 @@ const externalDashboardPieChartConfigSchema = z.object({ const externalDashboardCategoricalBarChartConfigSchema = z.object({ displayType: z.literal('bar'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardSelectItemSchema).length(1), groupBy: z.string().max(10000).optional(), orderBy: z.string().max(10000).optional(), @@ -580,7 +618,7 @@ export type ExternalDashboardHeatmapSelectItem = z.infer< const externalDashboardHeatmapChartConfigSchema = z.object({ displayType: z.literal('heatmap'), heatmapMode: z.literal('distribution').optional(), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardHeatmapSelectItemSchema).length(1), where: z.string().max(10000).optional().default(''), // `whereLanguageSchema` (an alias for `SearchConditionLanguageSchema`) @@ -594,7 +632,7 @@ const externalDashboardHeatmapChartConfigSchema = z.object({ const externalDashboardHeatmapSeriesChartConfigSchema = z.object({ displayType: z.literal('heatmap'), heatmapMode: z.literal('series'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardSelectItemSchema).length(1), groupBy: z.string().max(10000).optional(), numberFormat: NumberFormatSchema.optional(), @@ -602,7 +640,7 @@ const externalDashboardHeatmapSeriesChartConfigSchema = z.object({ const externalDashboardSearchChartConfigSchema = z.object({ displayType: z.literal('search'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.string().max(10000), where: z.string().max(10000).optional().default(''), whereLanguage: whereLanguageSchema, @@ -626,7 +664,7 @@ const externalDashboardMarkdownChartConfigSchema = z.object({ const externalDashboardEventPatternsChartConfigSchema = z.object({ displayType: z.literal('event_patterns'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.string().max(10000).optional().default(''), where: z.string().max(10000).optional().default(''), whereLanguage: whereLanguageSchema, @@ -720,7 +758,7 @@ const externalPromqlLegendTemplateSchema = z const externalPromqlChartConfigBaseSchema = z.object({ configType: z.literal('promql'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, // Sets the Prometheus step and `$__interval` of range queries. granularity: z.union([SQLIntervalSchema, z.literal('auto')]).optional(), numberFormat: NumberFormatSchema.optional(), diff --git a/packages/app/src/DBDashboardImportPage.tsx b/packages/app/src/DBDashboardImportPage.tsx index 21c5936fd1..749908f984 100644 --- a/packages/app/src/DBDashboardImportPage.tsx +++ b/packages/app/src/DBDashboardImportPage.tsx @@ -16,10 +16,15 @@ import { Controller, useForm, useWatch } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { convertToDashboardDocument } from '@hyperdx/common-utils/dist/core/utils'; +import { + collectRefinementIssues, + validateDashboardVariableReferences, +} from '@hyperdx/common-utils/dist/dashboardValidation'; import { type DashboardFilterQueryIssue, getAdhocFilterSourceKinds, isAdhocFilter, + isDataSourceFilter, isPrometheusLabelFilter, isQueryExpressionFilter, isSqlQueryFilter, @@ -34,6 +39,7 @@ import { displayTypeRequiresSource, isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; import { type DashboardFilter, type DashboardTemplate, @@ -75,6 +81,7 @@ import { import SelectControlled from './components/SelectControlled'; import { SourceMultiSelectControlled } from './components/SourceMultiSelect'; +import { useConnectionItems } from './hooks/useConnectionItems'; import api from './api'; import { usePageTitle } from './brand'; import { useConnections } from './connection'; @@ -130,6 +137,32 @@ function CollapsibleMessage({ ); } +/** + * A `$name` that names no variable of the right type in the template. The API + * rejects these too, but only once the mappings are filled in, and local mode + * doesn't check at all. + */ +export function getTemplateVariableReferenceIssues( + template: DashboardTemplate, +): string[] { + return collectRefinementIssues(ctx => + validateDashboardVariableReferences( + template.tiles, + template.filters ?? [], + ctx, + ), + ).map(({ path, message }) => { + const [collection, index] = path; + const owner = + collection === 'tiles' && typeof index === 'number' + ? `Tile "${template.tiles[index]?.config.name ?? index}"` + : collection === 'filters' && typeof index === 'number' + ? `Filter "${template.filters?.[index]?.name ?? index}"` + : path.join('.'); + return `${owner}: ${message}`; + }); +} + function FileSelection({ onComplete, }: { @@ -203,6 +236,24 @@ function FileSelection({ return; } + const referenceIssues = getTemplateVariableReferenceIssues(result.data); + if (referenceIssues.length > 0) { + onComplete(null); + setError({ + message: 'Failed to Import Dashboard', + details: ( + + {referenceIssues.map(issue => ( + + {issue} + + ))} + + ), + }); + return; + } + // The schema only guarantees saved filter values are well-shaped, not that // their condition strings parse. Surface a non-blocking warning so users // who hand-edited or generated the file know a value won't actually filter, @@ -398,11 +449,37 @@ function resolveAppliesToSources( return { ids: slots.filter(Boolean), slots }; } +/** + * A data source or connection variable reference (`$name`) is portable as + * written, so import neither maps it nor asks the user to. + */ +const isVariableRef = (name: string | undefined) => + parseVariableReference(name) != null; + +const sourceVariableRefs = (names: string[] | undefined) => + names?.filter(isVariableRef) ?? []; + +const mappableSourceNames = (names: string[] | undefined) => + names?.filter(name => !isVariableRef(name)); + /** Whether the filter names a single source that import must map. */ const isSourceBackedTemplateFilter = ( filter: DashboardFilter, ): filter is QueryExpressionDashboardFilter | PromqlLabelDashboardFilter => - isQueryExpressionFilter(filter) || isPrometheusLabelFilter(filter); + (isQueryExpressionFilter(filter) || isPrometheusLabelFilter(filter)) && + !isVariableRef(filter.source); + +/** + * Returns the filter if it names a connection import must map: a SQL query + * filter, or a data source variable limited to a connection. + */ +const connectionBackedTemplateFilter = (filter: DashboardFilter | undefined) => + filter && + (isSqlQueryFilter(filter) || isDataSourceFilter(filter)) && + filter.connection && + !isVariableRef(filter.connection) + ? filter + : undefined; /** Returns the filter if it names a source, or `undefined` if it doesn't. */ const sourceBackedTemplateFilter = (filter: DashboardFilter | undefined) => @@ -466,7 +543,7 @@ export function buildMappingFormSchema( connectionMappings: z.array(MappingValueSchema), /** A list of filter source mappings, ordered by input filter index */ filterSourceMappings: z.array(MappingValueSchema).optional(), - /** A list of filter connection mappings, ordered by input filter index. Only applicable for SQL query filters */ + /** Connection mappings of SQL query filters and data source variables, ordered by input filter index */ filterConnectionMappings: z.array(MappingValueSchema).optional(), /** * Per-filter applies-to source mappings. Each entry is an array of mapped @@ -497,6 +574,7 @@ export function buildMappingFormSchema( // meaningful source even when the template names one. if ( config.source && + !isVariableRef(config.source) && displayTypeRequiresSource(config.displayType) && !data.tileSourceMappings[idx] ) { @@ -508,7 +586,11 @@ export function buildMappingFormSchema( } // A raw SQL tile always gets a connection row, and its connection is // not optional — leaving it unpicked used to throw on `connection!.id`. - if (isRawSqlSavedChartConfig(config) && !data.connectionMappings[idx]) { + if ( + isRawSqlSavedChartConfig(config) && + !isVariableRef(config.connection) && + !data.connectionMappings[idx] + ) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['connectionMappings', idx], @@ -524,6 +606,16 @@ export function buildMappingFormSchema( }); input.filters?.forEach((filter, idx) => { + if ( + connectionBackedTemplateFilter(filter) && + !data.filterConnectionMappings?.[idx] + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['filterConnectionMappings', idx], + message: 'Select a connection for this filter', + }); + } if (isAdhocFilter(filter)) { const kinds = getAdhocFilterSourceKinds(filter.sourceType); const kindMessage = @@ -533,7 +625,10 @@ export function buildMappingFormSchema( const mappedSourceIds = data.filterAdhocSourceMappings?.[idx]?.filter( id => !!id, ); - if (!mappedSourceIds?.length) { + if ( + !mappedSourceIds?.length && + sourceVariableRefs(filter.sources).length === 0 + ) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['filterAdhocSourceMappings', idx], @@ -556,17 +651,6 @@ export function buildMappingFormSchema( return; } - if (isSqlQueryFilter(filter)) { - if (!data.filterConnectionMappings?.[idx]) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['filterConnectionMappings', idx], - message: 'Select a connection for this filter', - }); - } - return; - } - if (!isSourceBackedTemplateFilter(filter)) return; const mappedSourceId = data.filterSourceMappings?.[idx]; if (!mappedSourceId) { @@ -603,6 +687,7 @@ export function Mapping({ input }: { input: DashboardTemplate }) { const router = useRouter(); const { data: sources } = useSources(); const { data: connections } = useConnections(); + const connectionItems = useConnectionItems(); const { data: dashboards } = useDashboards(); const { data: existingTags } = api.useTags(); const [dashboardId] = useQueryState('dashboardId', parseAsString); @@ -646,7 +731,7 @@ export function Mapping({ input }: { input: DashboardTemplate }) { const tileSourceMappings = input.tiles.map(tile => { const config = tile.config as SavedChartConfig; - if (!config.source) return ''; + if (!config.source || isVariableRef(config.source)) return ''; const match = sources.find( source => source.name.toLowerCase() === config.source!.toLowerCase(), ); @@ -655,17 +740,19 @@ export function Mapping({ input }: { input: DashboardTemplate }) { const findConnectionIdByName = (name: string) => connections.find(conn => conn.name.toLowerCase() === name.toLowerCase()) - ?.id || ''; + ?.id ?? ''; const connectionMappings = input.tiles.map(tile => { const config = tile.config as SavedChartConfig; - if (!isRawSqlSavedChartConfig(config)) return ''; + if (!isRawSqlSavedChartConfig(config) || isVariableRef(config.connection)) + return ''; return findConnectionIdByName(config.connection); }); - const filterConnectionMappings = input.filters?.map(filter => - isSqlQueryFilter(filter) ? findConnectionIdByName(filter.connection) : '', - ); + const filterConnectionMappings = input.filters?.map(filter => { + const connection = connectionBackedTemplateFilter(filter)?.connection; + return connection ? findConnectionIdByName(connection) : ''; + }); const filterSourceMappings = input.filters?.map(filter => { const sourceName = sourceBackedTemplateFilter(filter)?.source; @@ -724,8 +811,8 @@ export function Mapping({ input }: { input: DashboardTemplate }) { setValue('tileSourceMappings', tileSourceMappings); setValue('connectionMappings', connectionMappings); - setValue('filterSourceMappings', filterSourceMappings); setValue('filterConnectionMappings', filterConnectionMappings); + setValue('filterSourceMappings', filterSourceMappings); multiMappingSlotsRef.current.clear(); filterAppliesToSourceMappings?.forEach((mapping, idx) => { setValue(`filterAppliesToSourceMappings.${idx}`, mapping); @@ -916,8 +1003,8 @@ export function Mapping({ input }: { input: DashboardTemplate }) { sources, ]); - // Propagate connection mapping changes to other RawSQL tiles and SQL query - // filters with the same input connection + // Propagate connection mapping changes to other RawSQL tiles and filters + // with the same input connection useEffect(() => { if (isUpdatingRef.current) return; if (!input.tiles) return; @@ -950,9 +1037,11 @@ export function Mapping({ input }: { input: DashboardTemplate }) { ); if (filterIdx !== -1) { prevFilterConnectionMappingsRef.current = filterConnectionMappings; - const filter = input.filters?.[filterIdx]; - if (filter && isSqlQueryFilter(filter)) { - inputConnectionName = filter.connection; + const connection = connectionBackedTemplateFilter( + input.filters?.[filterIdx], + )?.connection; + if (connection) { + inputConnectionName = connection; connectionId = filterConnectionMappings[filterIdx] ?? ''; } } @@ -977,8 +1066,8 @@ export function Mapping({ input }: { input: DashboardTemplate }) { ?.map((filter, index) => ({ filter, index })) .filter( ({ filter }) => - isSqlQueryFilter(filter) && - filter.connection === inputConnectionName, + connectionBackedTemplateFilter(filter)?.connection === + inputConnectionName, ) .map(({ index }) => `filterConnectionMappings.${index}` as const) ?? []; @@ -1092,12 +1181,14 @@ export function Mapping({ input }: { input: DashboardTemplate }) { }; if (isRawSqlSavedChartConfig(tile.config)) { - const connection = findConnection(data.connectionMappings[idx]); + const connection = isVariableRef(tile.config.connection) + ? tile.config.connection + : findConnection(data.connectionMappings[idx])!.id; return { ...tile, config: applyOnClick({ ...tile.config, - connection: connection!.id, + connection, ...(source ? { source: source.id } : {}), }), }; @@ -1118,23 +1209,34 @@ export function Mapping({ input }: { input: DashboardTemplate }) { // Zip the source mappings with the input filters const zippedFilters = input.filters?.map((filter, idx) => { - const appliesTo = data.filterAppliesToSourceMappings?.[idx]?.filter( - id => !!id?.length, - ); - const appliesToSourceIds = appliesTo?.length ? appliesTo : undefined; + // Data source variable references carry over unmapped + const appliesTo = [ + ...sourceVariableRefs( + appliesToTemplateFilter(filter)?.appliesToSourceIds, + ), + ...(data.filterAppliesToSourceMappings?.[idx]?.filter( + id => !!id?.length, + ) ?? []), + ]; + const appliesToSourceIds = appliesTo.length ? appliesTo : undefined; if (isAdhocFilter(filter)) { return { ...filter, - sources: - data.filterAdhocSourceMappings?.[idx]?.filter(id => !!id) ?? [], + sources: [ + ...sourceVariableRefs(filter.sources), + ...(data.filterAdhocSourceMappings?.[idx]?.filter(id => !!id) ?? + []), + ], appliesToSourceIds, }; } - if (isSqlQueryFilter(filter)) { - const connection = findConnection( - data.filterConnectionMappings?.[idx], - ); - return { ...filter, connection: connection!.id }; + if (connectionBackedTemplateFilter(filter)) { + return { + ...filter, + // The form schema requires this mapping + connection: findConnection(data.filterConnectionMappings?.[idx])! + .id, + }; } const source = findSource(data.filterSourceMappings?.[idx]); return { @@ -1227,7 +1329,7 @@ export function Mapping({ input }: { input: DashboardTemplate }) { return ( {/** Mapping for the tile's source, if one exists (they're optional for raw sql tiles) */} - {tile.config.source && ( + {tile.config.source && !isVariableRef(tile.config.source) && ( {tile.config.name} Data source @@ -1246,7 +1348,7 @@ export function Mapping({ input }: { input: DashboardTemplate }) { )} {/** Mapping for the tile's connection, if it's a raw sql tile */} - {isRawSql && ( + {isRawSql && !isVariableRef(config.connection) && ( {tile.config.name} Data connection @@ -1255,10 +1357,7 @@ export function Mapping({ input }: { input: DashboardTemplate }) { ({ - value: conn.id, - label: conn.name, - }))} + data={connectionItems} placeholder="Select a connection" /> @@ -1310,10 +1409,33 @@ export function Mapping({ input }: { input: DashboardTemplate }) { {/** Map filter sources */} {input.filters?.map((filter, i) => { - const appliesToSourceIds = - appliesToTemplateFilter(filter)?.appliesToSourceIds; + const appliesToSourceIds = mappableSourceNames( + appliesToTemplateFilter(filter)?.appliesToSourceIds, + ); + const adhocSourceNames = isAdhocFilter(filter) + ? mappableSourceNames(filter.sources) + : undefined; return ( + {connectionBackedTemplateFilter(filter) && ( + + {filter.name} (Filter) + Data connection + + {connectionBackedTemplateFilter(filter)?.connection} + + + + + + + + )} {isSourceBackedTemplateFilter(filter) && ( {filter.name} (Filter) @@ -1338,29 +1460,11 @@ export function Mapping({ input }: { input: DashboardTemplate }) { )} - {isSqlQueryFilter(filter) && ( - - {filter.name} (Filter) - Data connection - {filter.connection} - - ({ - value: conn.id, - label: conn.name, - }))} - placeholder="Select a connection" - /> - - - )} - {isAdhocFilter(filter) && ( + {isAdhocFilter(filter) && !!adhocSourceNames?.length && ( {filter.name} (Filter) Data sources - {filter.sources.join(', ')} + {adhocSourceNames.join(', ')} ( () => JSON.parse(serializedMissingRequiredFilterNames), @@ -929,16 +962,13 @@ const Tile = ({ return url && addTimeZone(url); }, [dateRange, queriedConfig, source, addTimeZone]); + // An alert must query one fixed source and connection + const supportsAlerts = + !usesReferenceVariable && savedChartConfigSupportsAlerts(chart.config); + const hoverToolbar = useMemo(() => { if (readOnly) return null; - const isRawSql = isRawSqlSavedChartConfig(chart.config); - const isPromQL = isPromqlSavedChartConfig(chart.config); - const displayTypeSupportsAlerts = isRawSql - ? displayTypeSupportsRawSqlAlerts(chart.config.displayType) - : isPromQL - ? displayTypeSupportsPromQLAlerts(chart.config.displayType) - : displayTypeSupportsBuilderAlerts(chart.config.displayType); const canMoveToGroup = onMoveToGroup && moveTargets && moveTargets.length > 0; return ( @@ -968,7 +998,7 @@ const Tile = ({ )} - {displayTypeSupportsAlerts && + {supportsAlerts && (alert ? ( // Existing alert: bell with a colored status dot indicator. { if (readOnly) return null; - const isRawSql = isRawSqlSavedChartConfig(chart.config); - const isPromQL = isPromqlSavedChartConfig(chart.config); - const showAlerts = isRawSql - ? displayTypeSupportsRawSqlAlerts(chart.config.displayType) - : isPromQL - ? displayTypeSupportsPromQLAlerts(chart.config.displayType) - : displayTypeSupportsBuilderAlerts(chart.config.displayType); const canMoveToGroup = onMoveToGroup && moveTargets && moveTargets.length > 0; return ( @@ -1113,7 +1136,7 @@ const Tile = ({ Replay search )} - {showAlerts && ( + {supportsAlerts && ( <> - {`Missing required filters: ${missingRequiredFilterNames.join( + {`Missing required filters or variables: ${missingRequiredFilterNames.join( ', ', )}. Select a value for each to load this tile.`} @@ -1269,6 +1292,20 @@ const Tile = ({ The data source for this tile is not set. Edit the tile to select a data source. + ) : isSourceOnOtherConnection ? ( + + The selected data source is on a different connection than this + tile's query. Select a source on the same connection. + + ) : isSourceKindUnsupported ? ( + + The selected data source can't be used with this chart type. + Select a different source. + ) : ( <> {effectiveQueriedConfig && @@ -1501,6 +1538,8 @@ const Tile = ({ filterWarning, isSourceMissing, isSourceUnset, + isSourceOnOtherConnection, + isSourceKindUnsupported, isBlockedByRequiredFilters, missingRequiredFilterNames, hasBeenVisible, @@ -1900,28 +1939,6 @@ function DBDashboardPage({ const { data: allDashboards } = useDashboards(); const [highlightedTileId] = useQueryState('highlightedTileId'); - const tableConnections = useMemo(() => { - if (!dashboard) return []; - const tc: TableConnection[] = []; - - for (const { config } of dashboard.tiles) { - if (!isBuilderSavedChartConfig(config)) continue; - const source = sources?.find(v => v.id === config.source); - if (!source || source.disabled) continue; - // TODO: will need to update this when we allow for multiple metrics per chart - const firstSelect = config.select[0]; - const metricType = - typeof firstSelect !== 'string' ? firstSelect?.metricType : undefined; - const tableName = getMetricTableName(source, metricType); - if (!tableName) continue; - tc.push({ - ...tcFromSource(source), - tableName, - }); - } - - return tc; - }, [dashboard, sources]); const [granularity, setGranularity] = useQueryState( 'granularity', @@ -1966,8 +1983,61 @@ function DBDashboardPage({ ignoredVariableNames, getFilterQueriesForSource, variables, + referenceVariableValues, + resolvedFilters, + unresolvedReferenceVariablesByFilterId, + incompatibleReferenceVariablesByFilterId, unsatisfiedRequiredFilters, - } = useDashboardFilters(filters); + } = useDashboardFilters(filters, { sources }); + // Tiles as they query, by ID: source and connection variable references + // replaced by the selections. Edits and saves read `dashboard.tiles`, so the + // stored references survive. + const resolvedTiles = useMemo( + () => + new Map( + (dashboard?.tiles ?? []).map(tile => { + const config = resolveConfigReferences( + tile.config, + referenceVariableValues, + ); + return [tile.id, config === tile.config ? tile : { ...tile, config }]; + }), + ), + [dashboard?.tiles, referenceVariableValues], + ); + // Kept apart from `resolvedTiles` so a tile's list only changes with its config + const referenceVariableNamesByTileId = useMemo( + () => + new Map( + (dashboard?.tiles ?? []).map(tile => [ + tile.id, + getConfigReferenceVariables(tile.config), + ]), + ), + [dashboard?.tiles], + ); + + const tableConnections = useMemo(() => { + const tc: TableConnection[] = []; + + for (const { config } of resolvedTiles.values()) { + if (!isBuilderSavedChartConfig(config)) continue; + const source = sources?.find(v => v.id === config.source); + if (!source || source.disabled) continue; + // TODO: will need to update this when we allow for multiple metrics per chart + const firstSelect = config.select[0]; + const metricType = + typeof firstSelect !== 'string' ? firstSelect?.metricType : undefined; + const tableName = getMetricTableName(source, metricType); + if (!tableName) continue; + tc.push({ + ...tcFromSource(source), + tableName, + }); + } + + return tc; + }, [resolvedTiles, sources]); const dashboardReady = !!dashboard?.id && @@ -2406,10 +2476,10 @@ function DBDashboardPage({ // The filter bar is hidden in kiosk mode, so a click would add conditions // the viewer can't see or remove. if (isKioskMode) return handlers; - for (const tile of dashboard?.tiles ?? []) { + for (const tile of resolvedTiles.values()) { const sourceId = 'source' in tile.config ? tile.config.source : undefined; const targetIds = getAdhocFilterTargetsForTile( - filters, + resolvedFilters, tile.config, sourceId, ).map(filter => filter.id); @@ -2420,19 +2490,23 @@ function DBDashboardPage({ } } return handlers; - }, [isKioskMode, dashboard?.tiles, filters, applyAdhocAction]); + }, [isKioskMode, resolvedTiles, resolvedFilters, applyAdhocAction]); const renderTileComponent = useCallback( (chart: Tile) => { + const resolvedChart = resolvedTiles.get(chart.id) ?? chart; // Resolve the tile's source ID so per-source-scoped filters can be // narrowed to only the tiles they target. Builder and RawSQL configs // both carry a `source` field; markdown / other configs don't. const tileSourceId = - 'source' in chart.config ? chart.config.source : undefined; + 'source' in resolvedChart.config + ? resolvedChart.config.source + : undefined; return ( setEditedTile(chart)} readOnly={isKioskMode} @@ -2459,7 +2533,14 @@ function DBDashboardPage({ c => c.id === chart.id, ); if (chartIndex === -1) return; - draft.tiles[chartIndex] = newChart; + // Keep the source as stored, not as resolved for display + draft.tiles[chartIndex] = { + ...newChart, + config: restoreConfigReferences( + newChart.config, + chart.config, + ), + }; }), ); } @@ -2532,6 +2613,8 @@ function DBDashboardPage({ ); }, [ + resolvedTiles, + referenceVariableNamesByTileId, dashboard, searchedTimeRange, isRefreshEnabled, @@ -3224,7 +3307,10 @@ function DBDashboardPage({ // `` return shallow and prevents the tile-grid tree below // from being wrapped in an extra indentation level. const dashboardBody = ( - <> + {title} @@ -3324,7 +3410,7 @@ function DBDashboardPage({ )} {!isKioskMode && ( )} {/* Selection indicator */} @@ -3512,7 +3605,7 @@ function DBDashboardPage({ variables={variables} /> )} - + ); return ( diff --git a/packages/app/src/DashboardFilters.tsx b/packages/app/src/DashboardFilters.tsx index eb78462468..ff17338cfb 100644 --- a/packages/app/src/DashboardFilters.tsx +++ b/packages/app/src/DashboardFilters.tsx @@ -5,12 +5,15 @@ import { getFilterVariableName, getPendingFilterValuesVariables, isAdhocFilter, + isDataSourceFilter, isFilterGlobalRequirement, isFilterReferenceableVariable, isFilterRequired, isQueryExpressionFilter, + isReferenceVariableFilter, isStaticListFilter, } from '@hyperdx/common-utils/dist/filters'; +import { ReferenceVariableValues } from '@hyperdx/common-utils/dist/referenceVariables'; import { AdhocFilterCondition, ChartVariable, @@ -25,9 +28,14 @@ import { DashboardFilterLabel, FilterCaution, FilterEffect, + getIncompatibleVariablesTooltip, getPendingVariablesTooltip, } from './components/DashboardFilterLabel'; import { FilterLinkToggle } from './components/FilterLinkToggle'; +import { + ConnectionDashboardFilter, + DataSourceDashboardFilter, +} from './components/ReferenceVariableDashboardFilter'; import { VirtualMultiSelect } from './components/VirtualMultiSelect/VirtualMultiSelect'; import { useDashboardFilterValues } from './hooks/useDashboardFilterValues'; @@ -173,6 +181,16 @@ interface DashboardFilterProps { variables?: ChartVariable[]; /** Required filters with nothing selected, which can block ad hoc filters. */ unsatisfiedRequiredFilters?: DashboardFilter[]; + /** The selected ID of each data source and connection variable, by name. */ + referenceVariableValues?: ReferenceVariableValues; + /** + * The reference variables each filter's fields reference that leave it + * nothing to query, by filter ID. `filters` are otherwise expected with + * their references resolved. + */ + unresolvedReferenceVariablesByFilterId?: ReadonlyMap; + /** The subset of those selecting a source the filter can't use. */ + incompatibleReferenceVariablesByFilterId?: ReadonlyMap; } const DashboardFilters = ({ @@ -184,6 +202,9 @@ const DashboardFilters = ({ onSetAdhocConditions, variables, unsatisfiedRequiredFilters, + referenceVariableValues, + unresolvedReferenceVariablesByFilterId, + incompatibleReferenceVariablesByFilterId, }: DashboardFilterProps) => { // "Link" mode (opt-in, off by default): each dropdown's values are narrowed by // the others' selections. Off by default because contingent value lookups @@ -191,13 +212,22 @@ const DashboardFilters = ({ // on, all of a source's facets are computed in a single groupUniqArrayIf scan. const [linked, setLinked] = useState(false); + // A filter whose data source variable has no selection has nothing to query yet + const queryableFilters = useMemo( + () => + filters.filter( + filter => !unresolvedReferenceVariablesByFilterId?.has(filter.id), + ), + [filters, unresolvedReferenceVariablesByFilterId], + ); + const { data: filterValuesById, erroredFilterIds, filterErrorMessages, isFetching, } = useDashboardFilterValues({ - filters, + filters: queryableFilters, dateRange, variables, // Only narrow by sibling selections when linked. @@ -214,6 +244,39 @@ const DashboardFilters = ({ return ( {filters.map(filter => { + const incompatibleVariables = + incompatibleReferenceVariablesByFilterId?.get(filter.id) ?? []; + const unresolvedVariables = + unresolvedReferenceVariablesByFilterId?.get(filter.id) ?? []; + // Variables with no selection yet, as opposed to an unusable one + const unselectedVariables = unresolvedVariables.filter( + name => !incompatibleVariables.includes(name), + ); + if (isReferenceVariableFilter(filter)) { + const referenceProps = { + value: referenceVariableValues?.get( + getFilterVariableName(filter) ?? '', + ), + onChange: (value: string | undefined) => + onSetFilterValue(filter.id, value ? [value] : []), + effect: getFilterEffect(filter), + requiredTooltip: getRequiredFilterTooltip(filter), + }; + return isDataSourceFilter(filter) ? ( + + ) : ( + + ); + } if (isAdhocFilter(filter)) { return ( ); } @@ -238,21 +303,31 @@ const DashboardFilters = ({ // Fall back to the hook-level fetching state only until this filter's // query has produced an entry; once it has (even with empty values), // honor its own loading flag. - const isLoadingValues = queriedFilterValues - ? queriedFilterValues.isLoading - : isFetching; + const isLoadingValues = + unresolvedVariables.length === 0 && + (queriedFilterValues ? queriedFilterValues.isLoading : isFetching); // Only a queried dropdown has a values query that can await a - // variable's selection. - const pendingVariables = isQueryExpressionFilter(filter) - ? getPendingFilterValuesVariables(filter, variables) - : undefined; + // variable's selection, besides any data source variable it reads from. + const pendingVariables = [ + ...unselectedVariables, + ...(isQueryExpressionFilter(filter) + ? getPendingFilterValuesVariables(filter, variables) + : []), + ]; return ( 0 || + (erroredFilterIds?.has(filter.id) ?? false) + } + errorMessage={ + incompatibleVariables.length > 0 + ? getIncompatibleVariablesTooltip(incompatibleVariables) + : filterErrorMessages?.get(filter.id) + } pendingVariables={pendingVariables} onChange={values => onSetFilterValue(filter.id, values)} values={queriedFilterValues?.values} diff --git a/packages/app/src/__tests__/DBDashboardImportPage.test.tsx b/packages/app/src/__tests__/DBDashboardImportPage.test.tsx index 2bfec3b197..81502709f0 100644 --- a/packages/app/src/__tests__/DBDashboardImportPage.test.tsx +++ b/packages/app/src/__tests__/DBDashboardImportPage.test.tsx @@ -6,7 +6,11 @@ import { } from '@hyperdx/common-utils/dist/types'; import { act, fireEvent, screen, waitFor } from '@testing-library/react'; -import { buildMappingFormSchema, Mapping } from '@/DBDashboardImportPage'; +import { + buildMappingFormSchema, + getTemplateVariableReferenceIssues, + Mapping, +} from '@/DBDashboardImportPage'; // Sources/connections the import maps the template's source *names* onto. The // auto-mapping effect in `Mapping` matches by name (case-insensitive), so a @@ -724,3 +728,150 @@ describe('Dashboard import - ad hoc filter sources', () => { expect(issuesFor(['src-logs'])).toBeUndefined(); }); }); + +describe('Dashboard import - data source variables', () => { + const sourceVariableTemplate = DashboardTemplateSchema.parse({ + version: '0.1.0', + name: 'Source Variables', + tiles: [builderTile('tile-line', 'line', '$logs', 0)], + filters: [ + { + id: 'ds', + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + { + id: 'svc', + type: 'QUERY_EXPRESSION', + name: 'Service', + expression: 'ServiceName', + source: '$logs', + }, + { + id: 'adhoc', + type: 'ADHOC', + name: 'Conditions', + sourceType: 'sql', + sources: ['$logs', 'Traces'], + isBroadcastEnabled: true, + isVariableEnabled: true, + }, + ], + }); + + it('keeps references as written without asking for a mapping', async () => { + renderWithMantine(); + + const finish = await screen.findByRole('button', { + name: /finish import/i, + }); + expect(screen.queryByText('$logs')).not.toBeInTheDocument(); + await act(async () => { + fireEvent.click(finish); + }); + + await waitFor(() => expect(mockMutateAsync).toHaveBeenCalledTimes(1)); + const payload = mockMutateAsync.mock.calls[0][0]; + expect(payload.tiles[0].config.source).toBe('$logs'); + expect(payload.filters[1].source).toBe('$logs'); + expect(payload.filters[2].sources).toEqual(['$logs', 'src-traces']); + }); + + it('accepts references to the variables the template declares', () => { + expect(getTemplateVariableReferenceIssues(sourceVariableTemplate)).toEqual( + [], + ); + }); + + it('reports references to variables the template does not declare', () => { + const template = DashboardTemplateSchema.parse({ + version: '0.1.0', + name: 'Undeclared', + tiles: [builderTile('tile-line', 'line', '$traces', 0)], + filters: [ + { + id: 'svc', + type: 'QUERY_EXPRESSION', + name: 'Service', + expression: 'ServiceName', + source: '$traces', + }, + ], + }); + + expect(getTemplateVariableReferenceIssues(template)).toEqual([ + 'Tile "tile-line": "$traces" does not name a data source variable on this dashboard', + 'Filter "Service": "$traces" does not name a data source variable on this dashboard', + ]); + }); +}); + +describe('Dashboard import - connection variables', () => { + const connectionVariableTemplate = DashboardTemplateSchema.parse({ + version: '0.1.0', + name: 'Connection Variables', + tiles: [ + { + id: 'tile-rawsql', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + name: 'tile-rawsql', + displayType: 'table', + configType: 'sql', + connection: '$conn', + sqlTemplate: 'SELECT 1', + }, + }, + ], + filters: [ + { + id: 'conn', + type: 'CONNECTION', + name: 'Cluster', + variableName: 'conn', + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + { + id: 'ds', + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + connection: 'Default', + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ], + }); + + it('keeps connection references and maps a data source variable connection', async () => { + renderWithMantine(); + + const finish = await screen.findByRole('button', { + name: /finish import/i, + }); + expect(screen.queryByText('$conn')).not.toBeInTheDocument(); + await act(async () => { + fireEvent.click(finish); + }); + + await waitFor(() => expect(mockMutateAsync).toHaveBeenCalledTimes(1)); + const payload = mockMutateAsync.mock.calls[0][0]; + expect(payload.tiles[0].config.connection).toBe('$conn'); + expect(payload.filters[1].connection).toBe('conn-default'); + }); +}); diff --git a/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx b/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx index 008860ab93..f89d1a71f2 100644 --- a/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx +++ b/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx @@ -30,6 +30,7 @@ import { DashboardFilterLabel, FilterCaution, FilterEffect, + getIncompatibleVariablesTooltip, getPendingVariablesTooltip, } from '@/components/DashboardFilterLabel'; import { FilterPill, getFilterOperatorDisplay } from '@/components/FilterPill'; @@ -53,8 +54,17 @@ type AdhocDashboardFilterProps = { variables?: ChartVariable[]; /** Required filters with nothing selected. */ unsatisfiedRequiredFilters?: DashboardFilter[]; + /** + * Unselected data source variables the filter's sources reference. Until + * they have a selection the filter has no sources to suggest keys from. + */ + unresolvedVariables?: string[]; + /** Those of `unresolvedVariables` selecting a source the filter can't use. */ + incompatibleVariables?: string[]; }; +const NO_VARIABLES: string[] = []; + /** A dashboard filter bar control holding one ad hoc filter's conditions. */ export function AdhocDashboardFilter({ filter, @@ -64,6 +74,8 @@ export function AdhocDashboardFilter({ effect, variables, unsatisfiedRequiredFilters, + unresolvedVariables = NO_VARIABLES, + incompatibleVariables = NO_VARIABLES, }: AdhocDashboardFilterProps) { const [isAdding, setIsAdding] = useState(false); const [isExpanded, setIsExpanded] = useState(false); @@ -103,7 +115,13 @@ export function AdhocDashboardFilter({ ? `This filter depends on: ${blockingFilterNames.join(', ')}` : undefined; const disabledReason = dependsOn ?? suggestionsWhere.error; - const isDisabled = !!disabledReason; + const isDisabled = !!disabledReason || unresolvedVariables.length > 0; + const allPendingVariables = [ + ...unresolvedVariables.filter( + name => !incompatibleVariables.includes(name), + ), + ...pendingVariables, + ]; const toggleAdding = () => { if (isDisabled) return; @@ -136,15 +154,18 @@ export function AdhocDashboardFilter({ testId={`dashboard-filter-blocked-${filter.name}`} /> )} - {!isDisabled && pendingVariables.length > 0 && ( + {!disabledReason && allPendingVariables.length > 0 && ( )} - {suggestionsWhere.error && ( + {(suggestionsWhere.error || incompatibleVariables.length > 0) && ( diff --git a/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx b/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx index 3f767a0e3e..467830eebb 100644 --- a/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx +++ b/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx @@ -151,6 +151,40 @@ describe('AdhocDashboardFilter', () => { ); }); + it('waits for an unselected data source variable its sources reference', async () => { + const onChange = renderFilter([existing], filter, { + unresolvedVariables: ['ds'], + }); + + expect( + screen.getByTestId('dashboard-filter-pending-variable-Conditions'), + ).toBeInTheDocument(); + expect(addButton()).toHaveAttribute('aria-disabled', 'true'); + await userEvent.click(addButton()); + await userEvent.click(screen.getByTestId('adhoc-condition-pill')); + expect(screen.queryByTestId(`${editorId}-key`)).not.toBeInTheDocument(); + + await userEvent.click( + screen.getByRole('button', { name: 'Remove filter' }), + ); + expect(onChange).toHaveBeenCalledWith([]); + }); + + it("reports a data source variable selecting a source it can't use", () => { + renderFilter([existing], filter, { + unresolvedVariables: ['ds'], + incompatibleVariables: ['ds'], + }); + + expect( + screen.getByTestId('dashboard-filter-error-Conditions'), + ).toBeInTheDocument(); + expect( + screen.queryByTestId('dashboard-filter-pending-variable-Conditions'), + ).not.toBeInTheDocument(); + expect(addButton()).toHaveAttribute('aria-disabled', 'true'); + }); + it('edits a condition from its pill', async () => { const onChange = renderFilter([ existing, diff --git a/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx b/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx index 838e3ec737..9a7942579e 100644 --- a/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx +++ b/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx @@ -21,6 +21,7 @@ import { IconCirclePlus } from '@tabler/icons-react'; import { HeatmapModeControl } from '@/components/DBEditTimeChartForm/HeatmapModeControl'; import { SourceSelectControlled } from '@/components/SourceSelect'; +import { useResolvedReference } from '@/components/sourceSelectUtils'; import { usePromqlMetricNames } from '@/hooks/usePromqlMetadata'; import { useSource } from '@/source'; @@ -80,7 +81,7 @@ export default function PromqlChartEditor({ ); }, []); - const sourceId = useWatch({ control, name: 'source' }); + const sourceId = useResolvedReference(useWatch({ control, name: 'source' })); const displayType = useWatch({ control, name: 'displayType' }); const { data: source } = useSource({ id: sourceId }); // The form can still hold a non-PromQL source right after switching a tile @@ -107,6 +108,7 @@ export default function PromqlChartEditor({ name="source" data-testid="source-selector" allowedSourceKinds={allowedSourceKinds} + allowSourceVariables /> {displayType === DisplayType.Heatmap && ( diff --git a/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx b/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx index ea2304d038..895c1685be 100644 --- a/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx +++ b/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx @@ -9,6 +9,7 @@ import { validateRawSqlChartConfig, validateRawSqlForAlert, } from '@hyperdx/common-utils/dist/core/utils'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; import { ChartVariable, RawSqlChartConfig, @@ -41,6 +42,7 @@ import SourceSchemaPreview, { isSourceSchemaPreviewEnabled, } from '@/components/SourceSchemaPreview'; import { SourceSelectControlled } from '@/components/SourceSelect'; +import { useResolvedReference } from '@/components/sourceSelectUtils'; import { SQLEditorControlled } from '@/components/SQLEditor/SQLEditor'; import { type SQLCompletion } from '@/components/SQLEditor/utils'; import { IS_LOCAL_MODE } from '@/config'; @@ -80,9 +82,14 @@ export function resolveConnectionSourceSync({ sources: { id: string; connection: string }[] | undefined; }): ConnectionSourceSyncResult { if (!sources) return null; + // A data source variable reference isn't bound to a connection here: the + // filter bar decides what it selects, so it neither moves the connection + // nor is cleared by a connection change. + const isSourceReference = parseVariableReference(source) != null; // When the source changes, sync the connection to match. if (source !== prevSource) { + if (isSourceReference) return null; const sourceConnection = sources.find(s => s.id === source)?.connection; if (sourceConnection && sourceConnection !== connection) { return { field: 'connection', value: sourceConnection }; @@ -105,7 +112,7 @@ export function resolveConnectionSourceSync({ // connection change above was itself triggered by the source. if (connection !== prevConnection && prevConnection !== undefined) { const sourceConnection = sources.find(s => s.id === source)?.connection; - if (source && sourceConnection !== connection) { + if (source && !isSourceReference && sourceConnection !== connection) { return { field: 'source', value: '' }; } } @@ -147,8 +154,12 @@ export default function RawSqlChartEditor({ const { data: sources } = useSources(); const displayType = useWatch({ control, name: 'displayType' }); - const connection = useWatch({ control, name: 'connection' }); - const source = useWatch({ control, name: 'source' }); + // Source and connection variable references autocomplete and expand macros + // as the source and connection they currently select. + const storedConnection = useWatch({ control, name: 'connection' }); + const connection = useResolvedReference(storedConnection); + const storedSource = useWatch({ control, name: 'source' }); + const source = useResolvedReference(storedSource); const sqlTemplate = useWatch({ control, name: 'sqlTemplate' }); const chartName = useWatch({ control, name: 'name' }); const sourceObject = sources?.find(s => s.id === source); @@ -196,23 +207,36 @@ export default function RawSqlChartEditor({ }; }, [debouncedRawSqlConfig, isDashboardForm]); - const prevSource = usePrevious(source); + const prevSource = usePrevious(storedSource); const prevConnection = usePrevious(connection); useEffect(() => { const update = resolveConnectionSourceSync({ - source, + source: storedSource, connection, prevSource, prevConnection, sources, }); - if (update?.field === 'connection') { + // A connection variable stays as picked; the tile shows a mismatch + // instead of having its reference replaced + if ( + update?.field === 'connection' && + parseVariableReference(storedConnection) == null + ) { setValue('connection', update.value); } else if (update?.field === 'source') { setValue('source', update.value); } - }, [connection, prevConnection, prevSource, setValue, source, sources]); + }, [ + connection, + storedConnection, + prevConnection, + prevSource, + setValue, + storedSource, + sources, + ]); const placeholderSQl = SQL_PLACEHOLDERS[displayType ?? DisplayType.Table]; @@ -274,6 +298,8 @@ export default function RawSqlChartEditor({ control={control} name="connection" size="xs" + allowConnectionVariables + data-testid="connection-selector" /> @@ -293,7 +319,9 @@ export default function RawSqlChartEditor({ name="source" data-testid="source-selector" allowedSourceKinds={allowedSourceKinds} + allowSourceVariables connectionId={connection} + variableConnection={storedConnection} size="xs" clearable placeholder="None" diff --git a/packages/app/src/components/ChartEditor/__tests__/resolveConnectionSourceSync.test.ts b/packages/app/src/components/ChartEditor/__tests__/resolveConnectionSourceSync.test.ts index 7e979f0a18..57efcda348 100644 --- a/packages/app/src/components/ChartEditor/__tests__/resolveConnectionSourceSync.test.ts +++ b/packages/app/src/components/ChartEditor/__tests__/resolveConnectionSourceSync.test.ts @@ -107,4 +107,28 @@ describe('resolveConnectionSourceSync', () => { }), ).toBeNull(); }); + + it('leaves the connection alone when a data source variable is selected', () => { + expect( + resolveConnectionSourceSync({ + source: '$logs', + connection: 'conn-2', + prevSource: 'src-b', + prevConnection: 'conn-2', + sources, + }), + ).toBeNull(); + }); + + it('keeps a data source variable when the connection changes', () => { + expect( + resolveConnectionSourceSync({ + source: '$logs', + connection: 'conn-2', + prevSource: '$logs', + prevConnection: 'conn-1', + sources, + }), + ).toBeNull(); + }); }); diff --git a/packages/app/src/components/ChartEditor/__tests__/utils.test.ts b/packages/app/src/components/ChartEditor/__tests__/utils.test.ts index 63f4e2ded3..24f910d616 100644 --- a/packages/app/src/components/ChartEditor/__tests__/utils.test.ts +++ b/packages/app/src/components/ChartEditor/__tests__/utils.test.ts @@ -19,6 +19,7 @@ import { convertFormStateToSavedChartConfig, convertSavedChartConfigToFormState, getAllowedSourceKinds, + getInterchangeableSourceKind, promqlExpressionPlaceholder, validateChartForm, } from '@/components/ChartEditor/utils'; @@ -2705,3 +2706,86 @@ describe('promqlExpressionPlaceholder', () => { ); }); }); + +describe('data source variable references', () => { + it('saves the reference rather than the source it resolves to', () => { + const form: ChartEditorFormState = { + displayType: DisplayType.Line, + source: '$logs', + series: [seriesItem], + }; + expect(convertFormStateToSavedChartConfig(form, logSource)).toMatchObject({ + source: '$logs', + }); + }); + + it('queries the resolved source for a raw SQL chart', () => { + const form: ChartEditorFormState = { + configType: 'sql', + displayType: DisplayType.Table, + source: '$logs', + connection: 'conn-1', + sqlTemplate: 'SELECT 1', + series: [], + }; + expect(convertFormStateToSavedChartConfig(form, logSource)).toMatchObject({ + source: '$logs', + }); + expect( + convertFormStateToChartConfig(form, dateRange, logSource), + ).toMatchObject({ source: logSource.id }); + }); + + it('saves a reference with no selected source when its kind is known', () => { + const form: ChartEditorFormState = { + displayType: DisplayType.Line, + source: '$logs', + series: [ + { ...seriesItem, metricName: 'cpu', metricType: MetricsDataType.Gauge }, + ], + }; + const saved = convertFormStateToSavedChartConfig( + form, + undefined, + SourceKind.Log, + ); + expect(saved).toMatchObject({ source: '$logs' }); + expect(saved).toMatchObject({ + select: [expect.not.objectContaining({ metricName: 'cpu' })], + }); + }); + + it('validates a reference with no selected source by its kind', () => { + const form: ChartEditorFormState = { + displayType: DisplayType.Line, + source: '$logs', + series: [seriesItem], + }; + expect( + validateChartForm(form, undefined, jest.fn(), { + sourceKind: SourceKind.Log, + }), + ).toEqual([]); + expect( + validateChartForm(form, undefined, jest.fn(), { + missingSourceMessage: 'Select a source for $logs', + }), + ).toEqual([{ path: 'source', message: 'Select a source for $logs' }]); + }); +}); + +describe('getInterchangeableSourceKind', () => { + it.each<[SourceKind[], SourceKind | undefined]>([ + [[SourceKind.Log], SourceKind.Log], + [[SourceKind.Log, SourceKind.Trace], SourceKind.Log], + [[SourceKind.Log, SourceKind.Metric], undefined], + [[SourceKind.Log, SourceKind.Session], undefined], + [[SourceKind.Session, SourceKind.Promql], undefined], + [[], undefined], + ])( + 'returns a stand-in for %p only when charts treat them alike', + (kinds, expected) => { + expect(getInterchangeableSourceKind(kinds)).toBe(expected); + }, + ); +}); diff --git a/packages/app/src/components/ChartEditor/utils.ts b/packages/app/src/components/ChartEditor/utils.ts index 5607dcdaac..3d6babc24e 100644 --- a/packages/app/src/components/ChartEditor/utils.ts +++ b/packages/app/src/components/ChartEditor/utils.ts @@ -13,20 +13,23 @@ import { validateRawSqlForAlert, } from '@hyperdx/common-utils/dist/core/utils'; import { - getHeatmapSourceKinds, + getAllowedSourceKinds, isBuilderSavedChartConfig, + isPromqlDisplayType, isPromqlSavedChartConfig, isRawSqlSavedChartConfig, + isStringSelectDisplayType, + toBuilderHeatmapMode, } from '@hyperdx/common-utils/dist/guards'; import { MACRO_SUGGESTIONS } from '@hyperdx/common-utils/dist/macros'; import { QUERY_PARAMS_BY_DISPLAY_TYPE } from '@hyperdx/common-utils/dist/rawSqlParams'; +import { getConfigReferenceVariables } from '@hyperdx/common-utils/dist/referenceVariables'; import { BuilderSavedChartConfig, ChartConfigWithDateRange, ChartVariable, DisplayType, getSampleWeightExpression, - HeatmapMode, isLogSource, isMetricSource, isRangeThresholdType, @@ -83,6 +86,32 @@ export function buildRawSqlCompletions({ ]; } +/** + * Groups kinds that charts treat alike: validation and normalization only ask + * whether a source is a metric source and whether it supports formulas, and + * PromQL sources only serve PromQL charts. + */ +function chartSourceKindClass(kind: SourceKind): string { + if (kind === SourceKind.Promql) return 'promql'; + if (kind === SourceKind.Metric) return 'metric'; + return isFormulaSourceKind(kind) ? 'events' : 'session'; +} + +/** + * A kind that stands for all of `kinds` when charts treat them alike, so a + * chart built for one is valid on the others. Undefined when they differ. + */ +export function getInterchangeableSourceKind( + kinds: readonly SourceKind[], +): SourceKind | undefined { + const [first] = kinds; + if (first == null) return undefined; + const firstClass = chartSourceKindClass(first); + return kinds.every(kind => chartSourceKindClass(kind) === firstClass) + ? first + : undefined; +} + function normalizeChartConfig< C extends Pick< BuilderSavedChartConfig, @@ -98,15 +127,15 @@ function normalizeChartConfig< | 'heatmap' | 'where' >, ->(config: C, source: TSource): C { - const isMetricSource = source.kind === SourceKind.Metric; +>(config: C, sourceKind: SourceKind): C { + const isMetricSource = sourceKind === SourceKind.Metric; // Formulas (HDX-5080) render on metric and event (log/trace) sources, and // only on the display types the formula query paths support (time series / // table / number). Strip them elsewhere so a source or display-type switch // can't persist a config the renderer would reject. The form state keeps // them, so switching back restores the formula rows. const keepFormulas = - isFormulaSourceKind(source.kind) && + isFormulaSourceKind(sourceKind) && (config.formulas?.length ?? 0) > 0 && isFormulaDisplayType(config.displayType); return { @@ -177,70 +206,20 @@ export const isRawSqlDisplayType = ( displayType === DisplayType.Bar || displayType === DisplayType.Number; -/** - * Display types that store `select` as a plain string (column expression) - * rather than a structured `DerivedColumn[]` series array. These types - * don't use the builder series editor and skip series-level validation. - */ -export const isStringSelectDisplayType = ( - displayType: DisplayType | undefined, -): displayType is DisplayType.Search | DisplayType.EventPatterns => - displayType === DisplayType.Search || - displayType === DisplayType.EventPatterns; - -export const isPromqlDisplayType = ( - displayType: DisplayType | undefined, -): displayType is - | DisplayType.Table - | DisplayType.Line - | DisplayType.StackedBar - | DisplayType.StackedLine - | DisplayType.Pie - | DisplayType.Bar - | DisplayType.Number - | DisplayType.Heatmap => - displayType === DisplayType.Table || - displayType === DisplayType.Line || - displayType === DisplayType.StackedBar || - displayType === DisplayType.StackedLine || - displayType === DisplayType.Pie || - displayType === DisplayType.Bar || - displayType === DisplayType.Number || - displayType === DisplayType.Heatmap; - -const NON_PROMQL_SOURCE_KINDS = Object.values(SourceKind).filter( - kind => kind !== SourceKind.Promql, -); - -/** - * Search and event patterns list raw rows out of the source's `from` table. A - * metric source keeps its rows in `metricTables` and leaves `from.tableName` - * empty, so there is nothing for them to read. - */ -const ROW_LISTING_SOURCE_KINDS = NON_PROMQL_SOURCE_KINDS.filter( - kind => kind !== SourceKind.Metric, -); - -/** Source kinds the Data Source picker offers, given the editor mode and the display type. */ -export function getAllowedSourceKinds({ - configType, - displayType, - heatmapMode, -}: { - configType: ChartEditorFormState['configType']; - displayType: DisplayType | undefined; - heatmapMode?: PromqlHeatmapMode; -}): SourceKind[] { - if (configType === 'promql' && isPromqlDisplayType(displayType)) { - return [SourceKind.Promql]; - } - if (displayType === DisplayType.Heatmap) { - return [...getHeatmapSourceKinds(toBuilderHeatmapMode(heatmapMode))]; - } - if (isStringSelectDisplayType(displayType)) { - return ROW_LISTING_SOURCE_KINDS; - } - return NON_PROMQL_SOURCE_KINDS; +/** The variables a chart form's source, or a raw SQL tile's connection, references. */ +export function getFormReferenceVariables( + form: Pick< + ChartEditorFormState, + 'source' | 'connection' | 'configType' | 'displayType' + >, +): string[] { + // Only raw SQL tiles store a connection of their own + const isRawSql = + form.configType === 'sql' && isRawSqlDisplayType(form.displayType); + return getConfigReferenceVariables({ + source: form.source, + connection: isRawSql ? form.connection : undefined, + }); } const isCustomOrderByDisplayType = ( @@ -255,9 +234,23 @@ const isCustomOrderByDisplayType = ( // ChartEditorControls and the server-side surfaces cannot drift. export { isFormulaDisplayType, isFormulaSourceKind }; +// Shared with MCP tile runs, which reject a variable's source selection the +// tile can't use, as the dashboard does. +export { + getAllowedSourceKinds, + isPromqlDisplayType, + isStringSelectDisplayType, + toBuilderHeatmapMode, +}; + +/** + * `sourceKind` stands in for `source` when there is no source to read it from, + * as for a data source variable with no selection. + */ export function convertFormStateToSavedChartConfig( form: ChartEditorFormState, source: TSource | undefined, + sourceKind: SourceKind | undefined = source?.kind, ): SavedChartConfig | undefined { if (form.configType === 'promql' && isPromqlDisplayType(form.displayType)) { const promqlConfig: PromqlSavedChartConfig = { @@ -280,7 +273,7 @@ export function convertFormStateToSavedChartConfig( // 'alert', // TODO: Support alerts on PromQL (HDX-4636) ]), promqlExpression: formPromqlExpressions(form), - source: source?.id ?? form.source ?? '', + source: form.source || (source?.id ?? ''), legendTemplate: form.legendTemplate?.trim() || undefined, heatmap: formPromqlHeatmap(form), }; @@ -331,12 +324,12 @@ export function convertFormStateToSavedChartConfig( heatmap: formBuilderHeatmap(form), select: [], where: form.where ?? '', - source: source?.id ?? form.source ?? '', + source: form.source || (source?.id ?? ''), }; return config; } - if (source) { + if (sourceKind) { // Merge the series and select fields back together, and prevent the series field from being submitted const config: BuilderSavedChartConfig = { ...omit(form, [ @@ -354,10 +347,10 @@ export function convertFormStateToSavedChartConfig( : '' : form.series, where: form.where ?? '', - source: source.id, + source: form.source || (source?.id ?? ''), }; - return normalizeChartConfig(config, source); + return normalizeChartConfig(config, sourceKind); } } @@ -416,7 +409,7 @@ export function convertFormStateToChartConfig( ]), sqlTemplate: form.sqlTemplate ?? '', connection: form.connection ?? '', - source: form.source || undefined, + source: source?.id ?? (form.source || undefined), from: source?.from, implicitColumnExpression: source && (isLogSource(source) || isTraceSource(source)) @@ -489,7 +482,7 @@ export function convertFormStateToChartConfig( : mergedSelect, }; - return structuredClone(normalizeChartConfig(newConfig, source)); + return structuredClone(normalizeChartConfig(newConfig, source.kind)); } } @@ -572,13 +565,6 @@ function formBuilderHeatmap( : { mode: toBuilderHeatmapMode(form.heatmap.mode) }; } -/** A heatmap mode as a builder heatmap's, which has no histogram mode. */ -export function toBuilderHeatmapMode( - mode: PromqlHeatmapMode | undefined, -): HeatmapMode | undefined { - return mode === 'histogram' ? undefined : mode; -} - const DEFAULT_PROMQL_PLACEHOLDER = "rate(http_requests_total{service='api'}[5m])"; @@ -612,6 +598,8 @@ export const validateChartForm = ( setError: UseFormSetError, { requireAlertDisplayName = false, + sourceKind = source?.kind, + missingSourceMessage = 'Source is required', }: { /** * Whether the alert must carry a name. Set for inline alerts, which have @@ -619,6 +607,13 @@ export const validateChartForm = ( * name the alert after whatever the chart happens to be called. */ requireAlertDisplayName?: boolean; + /** + * Stands in for `source` when there is no source to read the kind from, + * as for a data source variable with no selection. + */ + sourceKind?: SourceKind; + /** Replaces the generic error for a chart with no usable source. */ + missingSourceMessage?: string; } = {}, ) => { const errors: { path: Path; message: string }[] = []; @@ -642,9 +637,9 @@ export const validateChartForm = ( if ( !isRawSqlChart && form.displayType !== DisplayType.Markdown && - (!form.source || !source) + (!form.source || !sourceKind) ) { - errors.push({ path: `source`, message: 'Source is required' }); + errors.push({ path: `source`, message: missingSourceMessage }); } // Validate that valueExpressions are specified for each series. @@ -653,7 +648,7 @@ export const validateChartForm = ( if ( !isRawSqlChart && Array.isArray(form.series) && - source?.kind !== SourceKind.Metric && + sourceKind !== SourceKind.Metric && form.displayType !== DisplayType.Markdown && !isStringSelectDisplayType(form.displayType) ) { @@ -669,7 +664,7 @@ export const validateChartForm = ( // Validate metric names for metric sources if ( - source?.kind === SourceKind.Metric && + sourceKind === SourceKind.Metric && Array.isArray(form.series) && form.displayType !== DisplayType.Markdown && form.displayType !== DisplayType.Search && @@ -691,7 +686,7 @@ export const validateChartForm = ( // source kind + display type). if ( !isRawSqlChart && - isFormulaSourceKind(source?.kind) && + isFormulaSourceKind(sourceKind) && isFormulaDisplayType(form.displayType) && Array.isArray(form.formulas) ) { @@ -789,7 +784,7 @@ export const validateChartForm = ( !isRawSqlChart && Array.isArray(form.series) && form.displayType === DisplayType.Number && - !(form.formulas?.length && isFormulaSourceKind(source?.kind)) && + !(form.formulas?.length && isFormulaSourceKind(sourceKind)) && form.series.length > (form.seriesReturnType === 'ratio' ? 2 : 1) ) { errors.push({ diff --git a/packages/app/src/components/ConnectionSelect.tsx b/packages/app/src/components/ConnectionSelect.tsx index 2422377cfb..eccaacc5b3 100644 --- a/packages/app/src/components/ConnectionSelect.tsx +++ b/packages/app/src/components/ConnectionSelect.tsx @@ -1,35 +1,51 @@ -import { useMemo } from 'react'; -import { UseControllerProps } from 'react-hook-form'; +import { UseControllerProps, useWatch } from 'react-hook-form'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; +import { SelectProps } from '@mantine/core'; import { IconServer } from '@tabler/icons-react'; import SelectControlled from '@/components/SelectControlled'; -import { useConnections } from '@/connection'; +import { + useWithConnectionVariableItems, + VARIABLE_ICON, +} from '@/components/sourceSelectUtils'; +import { useConnectionItems } from '@/hooks/useConnectionItems'; export function ConnectionSelectControlled({ size, + allowConnectionVariables = false, + placeholder = 'Connection', + clearable = false, ...props -}: { size?: string } & UseControllerProps) { - const { data } = useConnections(); - - const values = useMemo( - () => - data?.map(d => ({ - value: d.id, - label: d.name, - })), - [data], +}: { + size?: string; + /** Whether to offer the dashboard's connection variables. */ + allowConnectionVariables?: boolean; +} & Pick & + UseControllerProps) { + const selected = useWatch({ control: props.control, name: props.name }); + const connectionItems = useConnectionItems(); + const items = useWithConnectionVariableItems( + connectionItems, + allowConnectionVariables, ); return ( } + placeholder={placeholder} + leftSection={ + parseVariableReference(selected) != null ? ( + VARIABLE_ICON + ) : ( + + ) + } maxDropdownHeight={280} size={size} /> diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx index 4524f411ab..7c5d577cd3 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx @@ -211,6 +211,7 @@ export function ChartEditorControls({ name="source" data-testid="source-selector" allowedSourceKinds={allowedSourceKinds} + allowSourceVariables onSchemaPreview={() => setIsSourceSchemaPreviewOpen(true)} isSchemaPreviewEnabled={isSourceSchemaPreviewEnabled(tableSource)} /> diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx index 61e1b47af8..a061b8811a 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx @@ -178,6 +178,10 @@ type ChartPreviewPanelProps = { dbTimeChartConfig?: ChartConfigWithDateRange; /** Required dashboard filters with nothing selected that block this tile. */ missingRequiredFilterNames?: string[]; + /** Whether turning off "Apply filters" would clear the required-filter block. */ + canPreviewWithoutFilters?: boolean; + /** Why the current selections can't be queried, shown instead of the chart. */ + blockedReason?: string; setValue: (name: 'orderBy', value: string) => void; setDisplayType: (displayType: DisplayType) => void; onSubmit: () => void; @@ -197,6 +201,8 @@ export function ChartPreviewPanel({ showGeneratedPromql, dbTimeChartConfig, missingRequiredFilterNames, + canPreviewWithoutFilters = false, + blockedReason, setValue, setDisplayType, onSubmit, @@ -213,8 +219,12 @@ export function ChartPreviewPanel({ const blockingFilterNames = missingRequiredFilterNames ?? []; const isBlockedByRequiredFilters = blockingFilterNames.length > 0 && tabQueriesData(activeTab); + const isBlocked = + blockedReason != null && + !isBlockedByRequiredFilters && + tabQueriesData(activeTab); const queryReady = - !isBlockedByRequiredFilters && !!isQueryReady(queriedConfig); + !isBlockedByRequiredFilters && !isBlocked && !!isQueryReady(queriedConfig); const onTableSortingChange = useCallback( (sortState: SortingState | null) => { @@ -262,13 +272,24 @@ export function ChartPreviewPanel({ <> {isBlockedByRequiredFilters ? ( + ) : isBlocked ? ( + ) : !queryReady && tabQueriesData(activeTab) ? ( = ( + values, + context, + options, +) => + zodChartFormResolver( + getFormReferenceVariables(values).length > 0 + ? { ...values, alert: undefined } + : values, + context, + options, + ); + const ALERT_IGNORES_DASHBOARD_FILTERS = 'Dashboard-level filter and variable selections cannot be applied when an alert is configured.'; @@ -243,7 +276,6 @@ export default function EditTimeChartForm({ isAlertRequired = false, showSaveToDashboard, }: EditTimeChartFormProps) { - const alertsEnabled = enableAlerts ?? dashboardId != null; const formValue: ChartEditorFormState = useMemo( () => convertSavedChartConfigToFormState(chartConfig), [chartConfig], @@ -266,7 +298,7 @@ export default function EditTimeChartForm({ } = useForm({ defaultValues: formValue, values: formValue, - resolver: zodResolver(zSavedChartConfig), + resolver: chartFormResolver, }); const { @@ -346,13 +378,75 @@ export default function EditTimeChartForm({ [configType, displayType, heatmapMode], ); + // The form keeps a data source variable reference as written; everything + // that queries uses the source the variable currently selects. + const sourceVariableName = parseVariableReference(sourceId); + const resolvedSourceId = useResolvedReference(sourceId); + const resolvedConnection = useResolvedReference(connection); + const sourceVariableDeclarations = useSourceVariableDeclarations(); + + const referenceVariableValues = useReferenceVariableValues(); + const referenceVariableNames = useMemo( + () => + getFormReferenceVariables({ + source: sourceId, + connection, + configType, + displayType, + }), + [sourceId, connection, configType, displayType], + ); + const usesReferenceVariable = referenceVariableNames.length > 0; + + // An alert must query one fixed source and connection, not the viewer's + // current selection. + const alertsEnabled = + (enableAlerts ?? dashboardId != null) && !usesReferenceVariable; + // The alert as it will save + const activeAlert = usesReferenceVariable ? undefined : alert; + // A source selection that current mode can't query counts as no source, // so that nothing downstream builds a query from it. const { data: tableSource } = useSource({ - id: sourceId, + id: resolvedSourceId, kinds: allowedSourceKinds, }); + // Saving reads only the source's kind. With no source selected, a variable + // whose kinds charts all treat alike still determines it. + const sourceVariable = sourceVariableDeclarations.find( + variable => variable.name === sourceVariableName, + ); + const sourceKind = useMemo(() => { + if (tableSource) return tableSource.kind; + if (resolvedSourceId != null) return; + const kinds = sourceVariable?.allowedSourceKinds.filter(kind => + allowedSourceKinds.includes(kind), + ); + return kinds && getInterchangeableSourceKind(kinds); + }, [tableSource, resolvedSourceId, sourceVariable, allowedSourceKinds]); + + // Why a `$name` source gave no usable source kind + const missingSourceMessage = + sourceVariableName == null + ? undefined + : sourceVariable == null + ? `This dashboard has no data source variable named $${sourceVariableName}` + : resolvedSourceId == null + ? `Select a source for $${sourceVariableName} in the filter bar to save this tile` + : `The source selected for $${sourceVariableName} can't be used with this chart type`; + + // A variable can select a source on another connection than the one a raw + // SQL query runs on, which the dashboard blocks too + const previewBlockedReason = + isRawSqlInput && + usesReferenceVariable && + tableSource != null && + resolvedConnection != null && + tableSource.connection !== resolvedConnection + ? "The selected data source is on a different connection than this tile's query. Select a source on the same connection." + : undefined; + const databaseName = tableSource?.from.databaseName; const tableName = tableSource?.from.tableName; @@ -501,7 +595,7 @@ export default function EditTimeChartForm({ // Alerts ignore dashboard-level filters and variables, // so disable the toggle when an alert is configured. const [applyFilters, setApplyFilters] = useState(true); - const resolvedApplyFilters = applyFilters && alert == null; + const resolvedApplyFilters = applyFilters && activeAlert == null; const dashboardFiltersToggleProps = useMemo< DashboardFiltersToggleProps | undefined @@ -512,10 +606,10 @@ export default function EditTimeChartForm({ : { checked: resolvedApplyFilters, disabledReason: - alert != null ? ALERT_IGNORES_DASHBOARD_FILTERS : undefined, + activeAlert != null ? ALERT_IGNORES_DASHBOARD_FILTERS : undefined, onChange: setApplyFilters, }, - [getDashboardFilters, resolvedApplyFilters, alert], + [getDashboardFilters, resolvedApplyFilters, activeAlert], ); const previewDashboardFilters = useMemo(() => { @@ -534,6 +628,7 @@ export default function EditTimeChartForm({ variables, unsatisfiedRequiredFilters, applySelections: resolvedApplyFilters, + referenceVariableNames, }); }, [ queriedConfig, @@ -541,6 +636,7 @@ export default function EditTimeChartForm({ variables, unsatisfiedRequiredFilters, resolvedApplyFilters, + referenceVariableNames, ]); // Attach the dashboard's filters and variables so that the preview queries @@ -555,17 +651,42 @@ export default function EditTimeChartForm({ }; }, [queriedConfig, previewDashboardFilters]); + const debouncedForm = useDebouncedFormValues(watch, getValues, 300); + + // With no selection for a variable it references the tile has nothing to + // query, so there may be no queried config to compute the block from. + const previewBlockingFilters = useMemo(() => { + if (previewDashboardFilters) return previewDashboardFilters; + if ( + !referenceVariableNames.some(name => !referenceVariableValues.get(name)) + ) + return undefined; + return getPreviewBlockingFilters({ + config: convertFormStateToSavedChartConfig(debouncedForm, tableSource), + sourceId: undefined, + variables, + unsatisfiedRequiredFilters, + applySelections: resolvedApplyFilters, + referenceVariableNames, + }); + }, [ + previewDashboardFilters, + referenceVariableNames, + referenceVariableValues, + debouncedForm, + tableSource, + variables, + unsatisfiedRequiredFilters, + resolvedApplyFilters, + ]); + const dbTimeChartConfig = useMemo( - () => computeDbTimeChartConfig(previewConfig, alert), - [previewConfig, alert], + () => computeDbTimeChartConfig(previewConfig, activeAlert), + [previewConfig, activeAlert], ); - // Casting because `useWatch` returns a deep partial type, but we know that the - // form state is complete due to default values set above. - const watchedForm = useWatch({ control }) as ChartEditorFormState; - const [debouncedForm] = useDebouncedValue(watchedForm, 300); const additionalAlertWarnings = useMemo(() => { - if (alert == null) return []; + if (activeAlert == null) return []; const config = convertFormStateToSavedChartConfig( debouncedForm, tableSource, @@ -574,7 +695,7 @@ export default function EditTimeChartForm({ ? getAlertVariableWarning(config, variables) : undefined; return variableWarning ? [variableWarning] : []; - }, [alert, debouncedForm, tableSource, variables]); + }, [activeAlert, debouncedForm, tableSource, variables]); const [saveToDashboardModalOpen, setSaveToDashboardModalOpen] = useState(false); @@ -584,10 +705,16 @@ export default function EditTimeChartForm({ const errors = validateChartForm(form, tableSource, setError, { // An inline alert has no tile to inherit a name from. requireAlertDisplayName: alertsEnabled && dashboardId == null, + sourceKind, + missingSourceMessage, }); if (errors.length > 0) return { errors, config: null }; - const savedConfig = convertFormStateToSavedChartConfig(form, tableSource); + const savedConfig = convertFormStateToSavedChartConfig( + form, + tableSource, + sourceKind, + ); if (!savedConfig) { console.error( 'convertFormStateToSavedChartConfig returned undefined after validation passed. ' + @@ -621,6 +748,8 @@ export default function EditTimeChartForm({ }, [ tableSource, + sourceKind, + missingSourceMessage, setError, alertsEnabled, dashboardId, @@ -646,11 +775,19 @@ export default function EditTimeChartForm({ return; } - const queriedConfig = convertFormStateToChartConfig( + // A raw SQL tile's connection may be a variable reference; the + // source is already resolved through `tableSource`. + const convertedQueriedConfig = convertFormStateToChartConfig( form, dateRange, tableSource, ); + const queriedConfig = + convertedQueriedConfig && + resolveConfigReferences( + convertedQueriedConfig, + referenceVariableValues, + ); if (config && queriedConfig) { const isRawSqlChart = @@ -670,6 +807,7 @@ export default function EditTimeChartForm({ setQueriedConfigAndSource, tableSource, dateRange, + referenceVariableValues, ], ); @@ -784,7 +922,7 @@ export default function EditTimeChartForm({ const allowedSourceItems = useFilteredSortedSourceItems({ sources, allowedSourceKinds, - connectionId: configType === 'sql' ? connection : undefined, + connectionId: configType === 'sql' ? resolvedConnection : undefined, groupBySection: true, }); @@ -817,6 +955,17 @@ export default function EditTimeChartForm({ // should be filled in. Raw SQL source is optional, so leave it. if (!sourceId && configType === 'sql') return; + // Kept on the same terms the picker offers it + if ( + isSourceVariableReferenceAccepted( + sourceId, + sourceVariableDeclarations, + allowedSourceKinds, + ) + ) { + return; + } + // If the currently selected source is still allowed, keep it. const selected = sources.find(s => s.id === sourceId); if ( @@ -846,6 +995,7 @@ export default function EditTimeChartForm({ setValue, sourceId, sources, + sourceVariableDeclarations, ]); useEffect(() => { @@ -1320,7 +1470,7 @@ export default function EditTimeChartForm({ onOpenDisplaySettings={openDisplaySettings} onSubmit={onSubmit} isDashboardForm={isDashboardForm} - alert={alert} + alert={activeAlert} additionalWarnings={additionalAlertWarnings} alertsEnabled={alertsEnabled} isAlertRequired={isAlertRequired} @@ -1349,7 +1499,7 @@ export default function EditTimeChartForm({ activeTab={activeTab} seriesReturnType={seriesReturnType} ratioMode={ratioMode} - alert={alert} + alert={activeAlert} additionalWarnings={additionalAlertWarnings} alertsEnabled={alertsEnabled} isAlertRequired={isAlertRequired} @@ -1363,6 +1513,18 @@ export default function EditTimeChartForm({ onHeatmapModeChange={onHeatmapModeChange} /> )} + {alert != null && usesReferenceVariable && ( + } + p="xs" + mt="sm" + > + Alerts aren't available on tiles that use a data source or + connection variable. This tile's alert will be removed when + you save. + + )} setValue(name, value)} setDisplayType={type => setValue('displayType', type, { shouldDirty: true }) diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx b/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx index 1b50d02185..878ccf4947 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx @@ -514,6 +514,7 @@ describe('ChartPreviewPanel', () => { queriedConfig: baseBuilderConfig, dbTimeChartConfig: baseBuilderConfig, missingRequiredFilterNames: ['Service', 'Environment'], + canPreviewWithoutFilters: true, }; it('names them instead of querying', () => { @@ -521,7 +522,7 @@ describe('ChartPreviewPanel', () => { expect( screen.getByText( - 'Missing required filters: Service, Environment. Select a value for each required filter, or turn off “Apply filters” to preview this tile without them.', + 'Missing required filters or variables: Service, Environment. Select a value for each required filter, or turn off “Apply filters” to preview this tile without them.', ), ).toBeInTheDocument(); expect(screen.queryByTestId('db-time-chart')).not.toBeInTheDocument(); @@ -531,6 +532,16 @@ describe('ChartPreviewPanel', () => { ).not.toBeInTheDocument(); }); + it('leaves out the "Apply filters" hint when turning it off would not help', () => { + renderPanel({ ...blockedProps, canPreviewWithoutFilters: false }); + + expect( + screen.getByTestId('preview-missing-required-filters'), + ).toHaveTextContent( + /^Missing required filters or variables: Service, Environment\. Select a value for each one to preview this tile\.$/, + ); + }); + it('does not block a markdown tile, which queries nothing', () => { renderPanel({ ...blockedProps, activeTab: 'markdown' }); @@ -544,8 +555,40 @@ describe('ChartPreviewPanel', () => { expect(screen.getByTestId('db-time-chart')).toBeInTheDocument(); expect( - screen.queryByText(/Missing required filters/), + screen.queryByText(/Missing required filters or variables/), ).not.toBeInTheDocument(); }); }); + + describe('when the selections are blocked', () => { + const blockedProps = { + queriedConfig: baseBuilderConfig, + dbTimeChartConfig: baseBuilderConfig, + blockedReason: 'The selected data source is on another connection.', + }; + + it('shows the reason instead of querying', () => { + renderPanel(blockedProps); + + expect(screen.getByTestId('preview-blocked')).toHaveTextContent( + 'The selected data source is on another connection.', + ); + expect(screen.queryByTestId('db-time-chart')).not.toBeInTheDocument(); + }); + + it('shows missing required filters first', () => { + renderPanel({ ...blockedProps, missingRequiredFilterNames: ['Service'] }); + + expect( + screen.getByTestId('preview-missing-required-filters'), + ).toBeInTheDocument(); + expect(screen.queryByTestId('preview-blocked')).not.toBeInTheDocument(); + }); + + it('does not block a markdown tile, which queries nothing', () => { + renderPanel({ ...blockedProps, activeTab: 'markdown' }); + + expect(screen.queryByTestId('preview-blocked')).not.toBeInTheDocument(); + }); + }); }); diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx b/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx index bd9dd337ba..8b35f1adaf 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx @@ -3,6 +3,8 @@ import React from 'react'; import { useController as mockUseController } from 'react-hook-form'; import { AlertThresholdType, + DashboardFilter, + DataSourceDashboardFilter, DisplayType, MetricsDataType, SavedChartConfig, @@ -13,6 +15,7 @@ import { fireEvent, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import DBEditTimeChartForm from '@/components/DBEditTimeChartForm'; +import { ReferenceVariablesProvider } from '@/components/sourceSelectUtils'; import { useSource } from '@/source'; import { DEFAULT_TILE_ALERT } from '@/utils/alerts'; @@ -40,6 +43,8 @@ jest.mock('@/hooks/useFetchMetricMetadata', () => ({ jest.mock('@/hooks/useMetadata', () => ({ useMetadataWithSettings: jest.fn().mockReturnValue({}), + // The raw SQL editor's completions + useMultipleAllFields: jest.fn().mockReturnValue({ data: [] }), useGetKeyValues: jest.fn().mockReturnValue({ data: [ { @@ -188,6 +193,7 @@ jest.mock('../../SourceSelect', () => ({ + ); }, @@ -1585,3 +1591,221 @@ describe('DBEditTimeChartForm - Inline alerts', () => { expect(screen.queryByTestId('remove-alert-button')).not.toBeInTheDocument(); }); }); + +describe('DBEditTimeChartForm - Raw SQL data source variables', () => { + const logsVariable: DataSourceDashboardFilter = { + id: 'logs', + type: 'DATA_SOURCE', + name: 'logs', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + const rawSqlConfig: SavedChartConfig = { + configType: 'sql', + displayType: DisplayType.Table, + name: 'Raw SQL tile', + source: '$logs', + connection: 'conn-2', + sqlTemplate: 'SELECT count() FROM $__sourceTable', + }; + + const renderWithSelection = (sourceId: string) => + renderWithMantine( + + + + + , + ); + + const logSource = (connection: string) => ({ + id: 'logs-source', + kind: SourceKind.Log, + name: 'Logs', + from: { databaseName: 'default', tableName: 'otel_logs' }, + connection, + timestampValueExpression: 'Timestamp', + }); + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it("blocks the preview when the variable's source is on another connection", async () => { + mockUseSourceData(logSource('conn-1')); + renderWithSelection('logs-source'); + + expect(await screen.findByTestId('preview-blocked')).toHaveTextContent( + "The selected data source is on a different connection than this tile's query.", + ); + }); + + it('blocks only on the unselected variable once filters are not applied', async () => { + const globalFilter: DashboardFilter = { + id: 'service', + type: 'QUERY_EXPRESSION', + name: 'Service', + expression: 'ServiceName', + source: 'logs-source', + minSelections: 1, + isGlobalRequirement: true, + }; + mockUseSourceData(undefined); + renderWithMantine( + + + []} + unsatisfiedRequiredFilters={[logsVariable, globalFilter]} + /> + + , + ); + + expect( + await screen.findByTestId('preview-missing-required-filters'), + ).toHaveTextContent( + /^Missing required filters or variables: logs, Service\. Select a value for each required filter, or turn off “Apply filters” to preview this tile without them\.$/, + ); + + await userEvent.click( + screen.getByRole('switch', { name: 'Apply filters' }), + ); + + expect( + screen.getByTestId('preview-missing-required-filters'), + ).toHaveTextContent( + /^Missing required filters or variables: logs\. Select a value for each one to preview this tile\.$/, + ); + }); + + it("previews when the variable's source is on the tile's connection", async () => { + mockUseSourceData(logSource('conn-2')); + renderWithSelection('logs-source'); + + await screen.findByTestId('chart-run-query-button'); + expect(screen.queryByTestId('preview-blocked')).not.toBeInTheDocument(); + }); +}); + +describe('DBEditTimeChartForm - Alerts on data source variables', () => { + const metricsVariable: DataSourceDashboardFilter = { + id: 'metrics', + type: 'DATA_SOURCE', + name: 'metrics', + variableName: 'metrics', + allowedSourceKinds: [SourceKind.Metric], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + const series = { + aggFn: 'avg' as const, + aggCondition: '', + aggConditionLanguage: 'lucene' as const, + valueExpression: 'Value', + metricType: MetricsDataType.Gauge, + metricName: 'test.metric.gauge', + }; + + const completeAlert = { + ...DEFAULT_TILE_ALERT, + channels: [{ type: 'webhook' as const, webhookId: 'webhook-1' }], + }; + + const renderWithAlert = ( + alert: NonNullable, + onSave: jest.Mock, + ) => + renderWithMantine( + + + + + , + ); + + const removalNotice = /This tile's alert will be removed when you save\./; + + beforeEach(() => { + jest.clearAllMocks(); + mockUseSource.mockImplementation(({ id }: { id?: string }) => ({ + data: + id === 'metric-source' + ? { + id: 'metric-source', + kind: SourceKind.Metric, + name: 'Test Metric Source', + from: { databaseName: 'default', tableName: '' }, + connection: 'default', + timestampValueExpression: 'Timestamp', + metricTables: { gauge: 'metrics.gauge' }, + } + : undefined, + })); + }); + + it('keeps the alert when the source goes to a variable and back', async () => { + const onSave = jest.fn(); + renderWithAlert(completeAlert, onSave); + const sourceSelector = screen.getByTestId('source-selector'); + + await userEvent.selectOptions(sourceSelector, '$metrics'); + expect(screen.getByText(removalNotice)).toBeInTheDocument(); + expect(screen.queryByTestId('alert-button')).not.toBeInTheDocument(); + + await userEvent.selectOptions(sourceSelector, 'metric-source'); + expect(screen.queryByText(removalNotice)).not.toBeInTheDocument(); + await userEvent.click(screen.getByTestId('chart-save-button')); + + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + expect(onSave.mock.calls[0][0].alert).toMatchObject(completeAlert); + }); + + it('saves without the alert while the source is a variable, even an invalid one', async () => { + const onSave = jest.fn(); + // No webhook picked, so the alert alone would block the save + renderWithAlert(DEFAULT_TILE_ALERT, onSave); + + await userEvent.selectOptions( + screen.getByTestId('source-selector'), + '$metrics', + ); + await userEvent.click(screen.getByTestId('chart-save-button')); + + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + const saved = onSave.mock.calls[0][0]; + expect(saved.source).toBe('$metrics'); + expect(saved.alert).toBeUndefined(); + }); +}); diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts b/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts index 2aa2410988..6635957e58 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts @@ -19,6 +19,7 @@ import { buildSampleEventsConfig, computeDbTimeChartConfig, displayTypeToActiveTab, + getPreviewBlockingFilters, isQueryReady, resolvePreviewVariables, resolveTilePreviewFilters, @@ -696,6 +697,7 @@ describe('resolveTilePreviewFilters', () => { filters: dashboardFilters, variables: [], missingRequiredFilterNames: [], + canPreviewWithoutFilters: false, }); }); @@ -708,6 +710,7 @@ describe('resolveTilePreviewFilters', () => { filters: undefined, variables: [{ name: 'service', values: [] }], missingRequiredFilterNames: [], + canPreviewWithoutFilters: false, }); }); @@ -796,6 +799,107 @@ describe('resolveTilePreviewFilters', () => { }).missingRequiredFilterNames, ).toEqual([]); }); + + it('still blocks on a referenced source variable while the filters are turned off', () => { + const sourceVariable: DashboardFilter = { + id: 'f3', + type: 'DATA_SOURCE', + name: 'Logs source', + allowedSourceKinds: [SourceKind.Log], + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'logs', + minSelections: 1, + maxSelections: 1, + }; + const unsatisfiedRequiredFilters = [requiredFilter, sourceVariable]; + + expect( + resolve({ + config: rawSqlWithFiltersMacro, + unsatisfiedRequiredFilters, + applySelections: false, + referenceVariableNames: ['logs'], + }).missingRequiredFilterNames, + ).toEqual(['Logs source']); + expect( + resolve({ unsatisfiedRequiredFilters, applySelections: false }) + .missingRequiredFilterNames, + ).toEqual([]); + }); +}); + +describe('getPreviewBlockingFilters', () => { + const sourceVariable: DashboardFilter = { + id: 'logs', + type: 'DATA_SOURCE', + name: 'Logs source', + allowedSourceKinds: [SourceKind.Log], + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'logs', + minSelections: 1, + maxSelections: 1, + }; + const requiredVariable: DashboardFilter = { + id: 'env', + type: 'STATIC_LIST', + name: 'Environment', + options: ['prod'], + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'env', + minSelections: 1, + }; + const rawSqlWithVariable: ChartConfigWithDateRange = { + configType: 'sql', + sqlTemplate: "SELECT count() FROM logs WHERE env = '$env'", + connection: 'clickhouse', + dateRange, + }; + + const getBlocking = ( + overrides: Partial[0]> = {}, + ) => + getPreviewBlockingFilters({ + config: rawSqlWithVariable, + sourceId: undefined, + variables: [{ name: 'env', values: [] }], + unsatisfiedRequiredFilters: [sourceVariable, requiredVariable], + applySelections: true, + referenceVariableNames: ['logs'], + ...overrides, + }); + + it('offers turning off the filters when that clears part of the block', () => { + expect(getBlocking()).toEqual({ + missingRequiredFilterNames: ['Logs source', 'Environment'], + canPreviewWithoutFilters: true, + }); + }); + + it('does not offer turning off the filters when only a reference variable blocks', () => { + expect( + getBlocking({ unsatisfiedRequiredFilters: [sourceVariable] }), + ).toEqual({ + missingRequiredFilterNames: ['Logs source'], + canPreviewWithoutFilters: false, + }); + }); + + it('does not offer turning off the filters when they are already off', () => { + expect(getBlocking({ applySelections: false })).toEqual({ + missingRequiredFilterNames: ['Logs source'], + canPreviewWithoutFilters: false, + }); + }); + + it('blocks only on reference variables when no query could be built', () => { + expect(getBlocking({ config: undefined })).toEqual({ + missingRequiredFilterNames: ['Logs source'], + canPreviewWithoutFilters: false, + }); + }); }); describe('withBroadcastFilters', () => { diff --git a/packages/app/src/components/DBEditTimeChartForm/useDebouncedFormValues.ts b/packages/app/src/components/DBEditTimeChartForm/useDebouncedFormValues.ts new file mode 100644 index 0000000000..80c504a1cb --- /dev/null +++ b/packages/app/src/components/DBEditTimeChartForm/useDebouncedFormValues.ts @@ -0,0 +1,25 @@ +import { useEffect, useState } from 'react'; +import { FieldValues, UseFormGetValues, UseFormWatch } from 'react-hook-form'; +import { useDebouncedCallback } from '@mantine/hooks'; + +/** + * The form's values, updated `delay` ms after the last change. Unlike + * `useWatch({ control })`, which types them as a deep partial, they're typed + * as complete. + * + * Kept out of the form component because the React Compiler skips any + * component that calls `watch`. + */ +export function useDebouncedFormValues( + watch: UseFormWatch, + getValues: UseFormGetValues, + delay: number, +): T { + const [values, setValues] = useState(() => getValues()); + const update = useDebouncedCallback(() => setValues(getValues()), delay); + useEffect(() => { + const subscription = watch(() => update()); + return () => subscription.unsubscribe(); + }, [watch, update]); + return values; +} diff --git a/packages/app/src/components/DBEditTimeChartForm/utils.ts b/packages/app/src/components/DBEditTimeChartForm/utils.ts index d49cc65bc1..4ee56423ed 100644 --- a/packages/app/src/components/DBEditTimeChartForm/utils.ts +++ b/packages/app/src/components/DBEditTimeChartForm/utils.ts @@ -10,7 +10,7 @@ import { import { isTimeSeriesDisplayType } from '@hyperdx/common-utils/dist/core/utils'; import { configConsumesBroadcastFilters, - getBlockingRequiredFilterNames, + getBlockingRequiredFilters, } from '@hyperdx/common-utils/dist/dashboardFilterValues'; import { getPromqlFilters, @@ -23,11 +23,13 @@ import { isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; import { substitutePromqlChartConfigTemplates } from '@hyperdx/common-utils/dist/macros'; +import { getReferenceVariableFilters } from '@hyperdx/common-utils/dist/referenceVariables'; import { BroadcastFilter, BuilderChartConfigWithDateRange, ChartAlertBaseSchema, ChartConfigWithDateRange, + ChartConfigWithOptDateRange, ChartConfigWithOptTimestamp, ChartVariable, DashboardFilter, @@ -204,21 +206,97 @@ export function resolvePreviewVariables({ : referenced.map(variable => ({ ...variable, values: [] })); } +/** + * The required filters that block a preview with `applySelections` off: only + * the reference variables the tile can't be queried without. + */ +function getUnappliedPreviewBlockingFilterNames( + unsatisfiedRequiredFilters: DashboardFilter[] | undefined, + referenceVariableNames: readonly string[] | undefined, +): string[] { + const referenced = new Set(referenceVariableNames); + return getReferenceVariableFilters(unsatisfiedRequiredFilters) + .filter(({ name }) => referenced.has(name)) + .map(({ filter }) => filter.name); +} + +export type PreviewBlockingFilters = { + /** Names of the required filters that have nothing selected and block the preview. */ + missingRequiredFilterNames: string[]; + /** Whether turning off "Apply filters" would clear the block. */ + canPreviewWithoutFilters: boolean; +}; + +/** + * The required filters with nothing selected that block a tile preview. + * + * With `applySelections` off, only the reference variables the tile can't be + * queried without still block. `config` is undefined when no query could be + * built, e.g. because a source variable has no selection; the tile then + * consumes no broadcast filters and references no template variables. + */ +export function getPreviewBlockingFilters({ + config, + sourceId, + variables, + unsatisfiedRequiredFilters, + applySelections, + referenceVariableNames, +}: { + config: ChartConfigWithOptDateRange | SavedChartConfig | undefined; + sourceId: string | undefined; + variables: ChartVariable[] | undefined; + unsatisfiedRequiredFilters: DashboardFilter[] | undefined; + applySelections: boolean; + /** The data source and connection variables the tile's stored config references. */ + referenceVariableNames: readonly string[] | undefined; +}): PreviewBlockingFilters { + const unappliedNames = getUnappliedPreviewBlockingFilterNames( + unsatisfiedRequiredFilters, + referenceVariableNames, + ); + if (!applySelections) { + return { + missingRequiredFilterNames: unappliedNames, + canPreviewWithoutFilters: false, + }; + } + + const missingRequiredFilterNames = getBlockingRequiredFilters( + unsatisfiedRequiredFilters ?? [], + { + sourceId, + referenceVariableNames, + referencedVariableNames: + config && variables + ? filterReferencedVariables(config, variables).map(v => v.name) + : undefined, + consumesBroadcastFilters: + config != null && configConsumesBroadcastFilters(config, sourceId), + }, + ).map(filter => filter.name); + return { + missingRequiredFilterNames, + canPreviewWithoutFilters: missingRequiredFilterNames.some( + name => !unappliedNames.includes(name), + ), + }; +} + /** What the dashboard's filter state contributes to a tile preview. */ -export type TilePreviewFilters = { +export type TilePreviewFilters = PreviewBlockingFilters & { /** Broadcast filter conditions to query the preview with, in its query language. */ filters: BroadcastFilter[] | undefined; /** The referenced variables, with or without their selections. */ variables: ChartVariable[] | undefined; - /** Names of the required filters that have nothing selected. */ - missingRequiredFilterNames: string[]; }; /** * Applies the parent dashboard's filter selections to a tile preview. * * With `applySelections` off, the preview runs as an alert would: no broadcast - * filters, empty variable selections, and no required-filter block. + * filters, empty variable selections, and no required-filter block other than + * the reference variables the tile can't be queried without. */ export function resolveTilePreviewFilters({ config, @@ -227,14 +305,25 @@ export function resolveTilePreviewFilters({ variables, unsatisfiedRequiredFilters, applySelections, + referenceVariableNames, }: { config: ChartConfigWithDateRange; sourceId: string | undefined; + /** The data source and connection variables the tile's stored config references. */ + referenceVariableNames?: readonly string[]; filters: BroadcastFilter[] | undefined; variables: ChartVariable[] | undefined; unsatisfiedRequiredFilters: DashboardFilter[] | undefined; applySelections: boolean; }): TilePreviewFilters { + const blocking = getPreviewBlockingFilters({ + config, + sourceId, + variables, + unsatisfiedRequiredFilters, + applySelections, + referenceVariableNames, + }); const previewVariables = resolvePreviewVariables({ config, variables, @@ -242,11 +331,7 @@ export function resolveTilePreviewFilters({ }); if (!applySelections) { - return { - filters: undefined, - variables: previewVariables, - missingRequiredFilterNames: [], - }; + return { ...blocking, filters: undefined, variables: previewVariables }; } // PromQL tiles take only PromQL conditions; `configConsumesBroadcastFilters` @@ -257,16 +342,7 @@ export function resolveTilePreviewFilters({ ? getSqlFilters(filters) : undefined; - return { - filters: previewFilters, - variables: previewVariables, - missingRequiredFilterNames: getBlockingRequiredFilterNames({ - config, - sourceId, - unsatisfiedRequiredFilters, - referencedVariables: previewVariables, - }), - }; + return { ...blocking, filters: previewFilters, variables: previewVariables }; } /** The config with the broadcast filters in its own query language attached. */ diff --git a/packages/app/src/components/DashboardFilterLabel.tsx b/packages/app/src/components/DashboardFilterLabel.tsx index 893e706970..c6a5020e5a 100644 --- a/packages/app/src/components/DashboardFilterLabel.tsx +++ b/packages/app/src/components/DashboardFilterLabel.tsx @@ -19,6 +19,16 @@ export const getPendingVariablesTooltip = ( } no selected value.`; }; +/** Explain a filter whose data source variable selects a source it can't use. */ +export const getIncompatibleVariablesTooltip = ( + incompatibleVariables: string[], +): string => { + const names = incompatibleVariables.map(name => `$${name}`).join(', '); + return `This filter can't use the source ${names} ${ + incompatibleVariables.length === 1 ? 'selects' : 'select' + }. Select a different source.`; +}; + /** 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/AdhocFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx index 6cf870d086..8eb2c5293a 100644 --- a/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx @@ -7,6 +7,11 @@ import { getAdhocFilterSourceKinds, isAdhocFilter, } from '@hyperdx/common-utils/dist/filters'; +import { + isSourceVariableReferenceAccepted, + parseVariableReference, + resolveVariableReference, +} from '@hyperdx/common-utils/dist/referenceVariables'; import { AdhocFilterSourceType, DashboardFilter, @@ -17,6 +22,10 @@ import { IconAlertTriangle } from '@tabler/icons-react'; import SearchWhereInput from '@/components/SearchInput/SearchWhereInput'; import { SourceMultiSelectControlled } from '@/components/SourceMultiSelect'; +import { + useReferenceVariableValues, + useSourceVariableDeclarations, +} from '@/components/sourceSelectUtils'; import { IS_PROMQL_ENABLED } from '@/config'; import { useSources } from '@/source'; @@ -44,6 +53,7 @@ export const AdhocFilterEditForm = ({ otherFilters, }: AdhocFilterEditFormProps) => { const { data: allSources } = useSources(); + const sourceVariables = useSourceVariableDeclarations(); const [sourceType, sourceIds, appliesToSourceIds] = useWatch({ control, name: ['sourceType', 'sources', 'appliesToSourceIds'], @@ -64,14 +74,26 @@ export const AdhocFilterEditForm = ({ ), ); }, [otherFilters, sourceType, sourceIds, appliesToSourceIds]); - const allowedSourceKinds = getAdhocFilterSourceKinds(sourceType); - const tableConnections = useMemo( - () => - (allSources ?? []) - .filter(source => sourceIds?.includes(source.id)) - .map(tcFromSource), - [allSources, sourceIds], + const allowedSourceKinds = useMemo( + () => getAdhocFilterSourceKinds(sourceType), + [sourceType], ); + const referenceVariableValues = useReferenceVariableValues(); + const tableConnections = useMemo(() => { + const resolvedIds = new Set( + sourceIds?.map(id => + resolveVariableReference(id, referenceVariableValues), + ), + ); + // A data source variable can select a source of a kind this filter can't use + return (allSources ?? []) + .filter( + source => + resolvedIds.has(source.id) && + allowedSourceKinds.includes(source.kind), + ) + .map(tcFromSource); + }, [allSources, sourceIds, referenceVariableValues, allowedSourceKinds]); // Kept visible for a saved PromQL filter so its source type can be changed const showSourceType = sourceType === 'promql' || @@ -82,6 +104,13 @@ export const AdhocFilterEditForm = ({ // hold after switching from another filter type. const validateSourceKinds = (ids: string[] | undefined) => { const hasOtherKind = ids?.some(id => { + if (parseVariableReference(id) != null) { + return !isSourceVariableReferenceAccepted( + id, + sourceVariables, + allowedSourceKinds, + ); + } const source = allSources?.find(s => s.id === id); return source && !allowedSourceKinds.includes(source.kind); }); @@ -131,6 +160,7 @@ export const AdhocFilterEditForm = ({ comboboxProps={{ withinPortal: true }} placeholder="Select sources" allowedSourceKinds={allowedSourceKinds} + allowSourceVariables rules={{ validate: (value: string[] | undefined) => !value?.length @@ -173,6 +203,7 @@ export const AdhocFilterEditForm = ({ comboboxProps={{ withinPortal: true }} placeholder="Same as data sources" allowedSourceKinds={allowedSourceKinds} + allowSourceVariables rules={{ validate: validateSourceKinds }} /> diff --git a/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx index f1a384dd68..cb8c5d784f 100644 --- a/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx @@ -3,6 +3,7 @@ import { useForm, useWatch } from 'react-hook-form'; import { deriveVariableName, getFilterVariableName, + isReferenceVariableFilterType, } from '@hyperdx/common-utils/dist/filters'; import { ChartVariable, @@ -33,6 +34,7 @@ import { useZIndex } from '@/zIndex'; import { AdhocFilterEditForm } from './AdhocFilterEditForm'; import { MODAL_SIZE } from './constants'; import { CustomInputWrapper } from './CustomInputWrapper'; +import { DataSourceFilterEditForm } from './DataSourceFilterEditForm'; import { FilterFormValues, toFormValues, @@ -41,6 +43,7 @@ import { import { PromqlLabelFilterEditForm } from './PromqlLabelFilterEditForm'; import { QueryExpressionFilterEditForm } from './QueryExpressionFilterEditForm'; import { StaticListFilterEditForm } from './StaticListFilterEditForm'; +import { VariableNameInput } from './VariableNameInput'; const FILTER_TYPE_OPTIONS = [ { @@ -64,6 +67,8 @@ const FILTER_TYPE_OPTIONS = [ }, ] : []), + { value: DashboardFilterType.enum.DATA_SOURCE, label: 'Data source' }, + { value: DashboardFilterType.enum.CONNECTION, label: 'Connection' }, ]; interface DashboardFilterEditFormProps { @@ -184,9 +189,30 @@ export const DashboardFilterEditForm = ({ return variables?.filter(variable => variable.name !== ownName); }, [variables, filter]); + // Ad hoc conditions and reference variables have fixed selection rules. + // Reference variables are always required, so only the global choice is left. + const isReferenceVariable = isReferenceVariableFilterType(formFilterType); + const showSelectionOptions = + showRequiredFilterOptions && + formFilterType !== 'ADHOC' && + !isReferenceVariable; + const showGlobalRequirementOption = + showRequiredFilterOptions && (isReferenceVariable || !!isRequired); + const isNew = !filter; const showTypeInput = !!showVariableOptions; + const globalRequirementCheckbox = ( + + ); + return ( - {formFilterType === 'STATIC_LIST' ? ( + {formFilterType === 'CONNECTION' ? ( + + ) : formFilterType === 'DATA_SOURCE' ? ( + + ) : formFilterType === 'STATIC_LIST' ? ( - {showRequiredFilterOptions && formFilterType !== 'ADHOC' && ( + {showSelectionOptions && ( - {!!isRequired && ( - - - + {showGlobalRequirementOption && ( + {globalRequirementCheckbox} )} )} + {isReferenceVariable && showGlobalRequirementOption && ( + + + {globalRequirementCheckbox} + + )} {formState.errors.root && ( sources?.find(s => s.id === id)?.name) + .map(id => getObjectName(id, sources)) .filter((name): name is string => !!name) .join(', '); } @@ -63,19 +68,20 @@ function getSourceNames( function getValuesAttribute( filter: DashboardFilter, sources?: { id: string; name: string }[], + connections?: { id: string; name: string }[], ): DashboardFilterAttribute { switch (filter.type) { case 'QUERY_EXPRESSION': return { icon: , tooltip: 'Source the dropdown values are queried from', - label: sources?.find(s => s.id === filter.source)?.name ?? '', + label: getObjectName(filter.source, sources) ?? '', }; case 'PROMETHEUS_LABEL': return { icon: , tooltip: 'PromQL source and label the dropdown values come from', - label: [sources?.find(s => s.id === filter.source)?.name, filter.label] + label: [getObjectName(filter.source, sources), filter.label] .filter(Boolean) .join(' · '), }; @@ -98,6 +104,25 @@ function getValuesAttribute( tooltip: 'The dropdown values come from a SQL query', label: 'SQL query', }; + case 'DATA_SOURCE': + return { + icon: , + tooltip: + 'Kinds of sources offered, and the connection they are limited to', + label: [ + filter.allowedSourceKinds + .map(kind => SOURCE_KIND_LABELS[kind]) + .join(', '), + filter.connection && getObjectName(filter.connection, connections), + ] + .filter(Boolean) + .join(' · '), + }; + case 'CONNECTION': + return { + icon: , + label: 'Connections', + }; default: filter satisfies never; // exhaustive check return { icon: , label: '' }; @@ -129,6 +154,7 @@ export const DashboardFiltersList = ({ onAddNew, }: DashboardFiltersListProps) => { const { data: sources } = useSources(); + const { data: connections } = useConnections(); return ( {filters.map(filter => { - const attributes = [getValuesAttribute(filter, sources)]; + const attributes = [getValuesAttribute(filter, sources, connections)]; const broadcastTarget = getBroadcastTargetDisplay(filter, sources); if (!hideAppliesTo && broadcastTarget != null) { diff --git a/packages/app/src/components/DashboardFiltersModal/DataSourceFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/DataSourceFilterEditForm.tsx new file mode 100644 index 0000000000..b92e553a1a --- /dev/null +++ b/packages/app/src/components/DashboardFiltersModal/DataSourceFilterEditForm.tsx @@ -0,0 +1,100 @@ +import { Controller, useFormState, useWatch } from 'react-hook-form'; +import { DashboardFilter, SourceKind } from '@hyperdx/common-utils/dist/types'; +import { Alert, Group, MultiSelect } from '@mantine/core'; +import { IconAlertTriangle } from '@tabler/icons-react'; + +import { getInterchangeableSourceKind } from '@/components/ChartEditor/utils'; +import { ConnectionSelectControlled } from '@/components/ConnectionSelect'; +import { SOURCE_KIND_LABELS } from '@/components/Sources/SourceForm/constants'; +import { SOURCE_KIND_ICONS } from '@/components/sourceSelectUtils'; +import { IS_PROMQL_ENABLED } from '@/config'; + +import { CustomInputWrapper } from './CustomInputWrapper'; +import { FilterFormControl } from './filterFormState'; +import { VariableNameInput } from './VariableNameInput'; + +const SOURCE_KIND_OPTIONS = Object.values(SourceKind) + .filter(kind => IS_PROMQL_ENABLED || kind !== SourceKind.Promql) + .map(kind => ({ value: kind, label: SOURCE_KIND_LABELS[kind] })); + +interface DataSourceFilterEditFormProps { + control: FilterFormControl; + /** Filters other than the one being edited, used to keep variable names unique. */ + otherFilters: DashboardFilter[]; +} + +/** Form for editing a variable whose value is a source. */ +export const DataSourceFilterEditForm = ({ + control, + otherFilters, +}: DataSourceFilterEditFormProps) => { + const { errors } = useFormState({ control }); + const allowedSourceKinds = useWatch({ control, name: 'allowedSourceKinds' }); + const hasMixedKinds = + (allowedSourceKinds?.length ?? 0) > 1 && + getInterchangeableSourceKind(allowedSourceKinds) == null; + + return ( + <> + + + (value?.length ?? 0) > 0 || 'Select at least one source kind', + }} + render={({ field: { onChange, value } }) => ( + ( + + {SOURCE_KIND_ICONS[option.value]} + {option.label} + + )} + /> + )} + /> + + + + + + + {hasMixedKinds && ( + } + data-testid="filter-mixed-source-kinds-warning" + > + These kinds support different chart options, such as metrics and + formulas. A tile built while one kind is selected may not load when + the variable is switched to another, and a new tile can't be + saved until a source is selected. + + )} + + + + ); +}; diff --git a/packages/app/src/components/DashboardFiltersModal/PromqlLabelFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/PromqlLabelFilterEditForm.tsx index bb3d90a8f0..32092ff438 100644 --- a/packages/app/src/components/DashboardFiltersModal/PromqlLabelFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/PromqlLabelFilterEditForm.tsx @@ -8,6 +8,7 @@ import { import { AutocompleteControlled } from '@/components/InputControlled'; import PromQLEditor from '@/components/PromQLEditor/PromQLEditor'; import { SourceSelectControlled } from '@/components/SourceSelect'; +import { useResolvedReference } from '@/components/sourceSelectUtils'; import { usePromqlLabelNames, usePromqlMetricNames, @@ -42,7 +43,7 @@ export const PromqlLabelFilterEditForm = ({ // Only a PromQL source can answer the label lookup; the form may briefly hold // another kind while the user switches types. - const sourceId = useWatch({ control, name: 'source' }); + const sourceId = useResolvedReference(useWatch({ control, name: 'source' })); const source = sources?.find(s => s.id === sourceId); const promqlSource = source && isPromqlSource(source) ? source : undefined; const { data: labelNames } = usePromqlLabelNames(promqlSource?.id); @@ -64,6 +65,7 @@ export const PromqlLabelFilterEditForm = ({ }} comboboxProps={{ withinPortal: true }} allowedSourceKinds={[SourceKind.Promql]} + allowSourceVariables /> diff --git a/packages/app/src/components/DashboardFiltersModal/QueryExpressionFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/QueryExpressionFilterEditForm.tsx index 8d88a40b0a..a806135d43 100644 --- a/packages/app/src/components/DashboardFiltersModal/QueryExpressionFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/QueryExpressionFilterEditForm.tsx @@ -27,6 +27,7 @@ import SourceSchemaPreview, { isSourceSchemaPreviewEnabled, } from '@/components/SourceSchemaPreview'; import { SourceSelectControlled } from '@/components/SourceSelect'; +import { useResolvedReference } from '@/components/sourceSelectUtils'; import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor'; import { useSource } from '@/source'; import { getMetricTableName } from '@/utils'; @@ -60,7 +61,11 @@ export const QueryExpressionFilterEditForm = ({ showVariableOptions, }: QueryExpressionFilterEditFormProps) => { const sourceId = useWatch({ control, name: 'source' }); - const { data: source } = useSource({ id: sourceId }); + // A data source variable can select a source of a kind this filter can't use + const { data: source } = useSource({ + id: useResolvedReference(sourceId), + kinds: QUERY_EXPRESSION_FILTER_SOURCE_KINDS, + }); const metricType = useWatch({ control, name: 'sourceMetricType' }); const tableName = source && getMetricTableName(source, metricType); @@ -137,6 +142,7 @@ export const QueryExpressionFilterEditForm = ({ isSchemaPreviewEnabled={isSourceSchemaPreviewEnabled(source)} disabled={!!presetSource} allowedSourceKinds={QUERY_EXPRESSION_FILTER_SOURCE_KINDS} + allowSourceVariables /> diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx b/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx index 91d55296f3..04b1d99c62 100644 --- a/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx @@ -12,6 +12,7 @@ import { FilterFormControl } from '@/components/DashboardFiltersModal/filterForm jest.mock('@/useConfirm', () => ({ useConfirm: () => jest.fn() })); jest.mock('@/source', () => ({ useSources: () => ({ data: [] }) })); +jest.mock('@/connection', () => ({ useConnections: () => ({ data: [] }) })); // Mantine's Combobox calls scrollIntoView when its dropdown opens; jsdom lacks it. window.HTMLElement.prototype.scrollIntoView = jest.fn(); diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/DataSourceFilterEditForm.test.tsx b/packages/app/src/components/DashboardFiltersModal/__tests__/DataSourceFilterEditForm.test.tsx new file mode 100644 index 0000000000..6df2ba9be4 --- /dev/null +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/DataSourceFilterEditForm.test.tsx @@ -0,0 +1,84 @@ +import { useForm } from 'react-hook-form'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { DataSourceFilterEditForm } from '@/components/DashboardFiltersModal/DataSourceFilterEditForm'; +import { + FilterFormValues, + toFormValues, + toSavedFilter, +} from '@/components/DashboardFiltersModal/filterFormState'; + +jest.mock('@/connection', () => ({ + useConnections: () => ({ data: [{ id: 'conn-1', name: 'Primary' }] }), +})); + +function Harness({ + allowedSourceKinds, + connection, + onSave, +}: { + allowedSourceKinds: SourceKind[]; + connection?: string; + onSave?: (values: FilterFormValues) => void; +}) { + const { control, getValues } = useForm({ + defaultValues: { + ...toFormValues(), + type: 'DATA_SOURCE', + name: 'Logs source', + allowedSourceKinds, + connection, + }, + }); + return ( + <> + + + + ); +} + +const warning = () => screen.queryByTestId('filter-mixed-source-kinds-warning'); + +describe('DataSourceFilterEditForm', () => { + it('warns when the kinds support different chart options', () => { + renderWithMantine( + , + ); + expect(warning()).toBeInTheDocument(); + }); + + it('does not warn for kinds that charts treat alike', () => { + renderWithMantine( + , + ); + expect(warning()).not.toBeInTheDocument(); + }); + + it('saves no connection once the connection is cleared', async () => { + const onSave = jest.fn(); + renderWithMantine( + , + ); + + const input = screen.getByTestId('filter-data-source-connection-input'); + expect(input).toHaveValue('Primary'); + const clearButton = input.parentElement?.querySelector('button'); + if (!clearButton) throw new Error('Expected a clear button'); + await userEvent.click(clearButton); + expect(input).toHaveValue(''); + await userEvent.click(screen.getByRole('button', { name: 'Save' })); + + expect(toSavedFilter(onSave.mock.calls[0][0])).toMatchObject({ + connection: undefined, + }); + }); +}); diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts index 63e0497c84..1729594933 100644 --- a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts @@ -1,4 +1,4 @@ -import { DashboardFilter } from '@hyperdx/common-utils/dist/types'; +import { DashboardFilter, SourceKind } from '@hyperdx/common-utils/dist/types'; import { FilterFormValues, @@ -318,6 +318,74 @@ describe('toSavedFilter', () => { ).toThrow(); }); + it('saves a data source filter as single-select and required', () => { + const saved = toSavedFilter( + formValues({ + type: 'DATA_SOURCE', + name: 'Logs source', + allowedSourceKinds: [SourceKind.Log], + isRequired: false, + isSingleSelect: false, + expression: 'ignored', + source: 'ignored', + }), + ); + + expect(saved).toEqual({ + id: expect.any(String), + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'Logs_source', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }); + expect(toFormValues(saved).allowedSourceKinds).toEqual([SourceKind.Log]); + }); + + it('saves a data source filter limited to a connection variable', () => { + expect( + toSavedFilter( + formValues({ + type: 'DATA_SOURCE', + name: 'Logs source', + allowedSourceKinds: [SourceKind.Log], + connection: '$conn', + }), + ), + ).toMatchObject({ connection: '$conn' }); + }); + + it('saves a connection filter as single-select and required', () => { + const saved = toSavedFilter( + formValues({ + type: 'CONNECTION', + name: 'Cluster', + isSingleSelect: false, + source: 'ignored', + }), + ); + + expect(saved).toEqual({ + id: expect.any(String), + type: 'CONNECTION', + name: 'Cluster', + variableName: 'Cluster', + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }); + }); + + it('rejects a data source filter without source kinds', () => { + expect(() => + toSavedFilter(formValues({ type: 'DATA_SOURCE', name: 'Source' })), + ).toThrow(); + }); + it('rejects values the schema cannot accept', () => { expect(() => toSavedFilter(formValues({ type: 'STATIC_LIST', options: [] })), @@ -325,9 +393,15 @@ describe('toSavedFilter', () => { }); }); -/** The minimum a form needs to save, per filter type the form supports. */ +/** + * The minimum a form needs to save, per filter type with configurable + * selection limits. + */ const byType: Record< - Exclude, + Exclude< + DashboardFilter['type'], + 'ADHOC' | 'SQL_QUERY' | 'DATA_SOURCE' | 'CONNECTION' + >, Partial > = { QUERY_EXPRESSION: { @@ -432,6 +506,36 @@ describe('isGlobalRequirement', () => { ).not.toHaveProperty('isGlobalRequirement'); }, ); + + // Reference variables are always required, so the form has no "Required" + // checkbox for them to gate the requirement's scope. + it('round-trips a dashboard-wide data source requirement without isRequired', () => { + const saved = toSavedFilter( + formValues({ + type: 'DATA_SOURCE', + name: 'Source', + allowedSourceKinds: [SourceKind.Log], + isRequired: false, + isGlobalRequirement: true, + }), + ); + + expect(saved).toMatchObject({ isGlobalRequirement: true }); + expect(toFormValues(saved).isGlobalRequirement).toBe(true); + }); + + it('emits no key for a data source filter that blocks only its own tiles', () => { + expect( + toSavedFilter( + formValues({ + type: 'DATA_SOURCE', + name: 'Source', + allowedSourceKinds: [SourceKind.Log], + isGlobalRequirement: false, + }), + ), + ).not.toHaveProperty('isGlobalRequirement'); + }); }); describe('maxSelections', () => { diff --git a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts index 7b681fe2f5..caa45a6952 100644 --- a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts +++ b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts @@ -5,11 +5,13 @@ import { isFilterGlobalRequirement, isFilterRequired, isFilterVariableEnabled, + isReferenceVariableFilterType, } from '@hyperdx/common-utils/dist/filters'; import { AdhocDashboardFilter, DashboardFilter, DashboardFilterSchema, + DataSourceDashboardFilter, PromqlLabelDashboardFilter, QueryExpressionDashboardFilter, StaticListDashboardFilter, @@ -53,7 +55,8 @@ export type FilterFormValues = { | 'isGlobalRequirement' | 'maxSelections' > & - Pick; + Pick & + Pick; export type FilterFormControl = Control; @@ -65,6 +68,7 @@ export const toFormValues = ( const staticList = filter?.type === 'STATIC_LIST' ? filter : undefined; const promqlLabel = filter?.type === 'PROMETHEUS_LABEL' ? filter : undefined; const adhoc = filter?.type === 'ADHOC' ? filter : undefined; + const dataSource = filter?.type === 'DATA_SOURCE' ? filter : undefined; return { id: filter?.id ?? crypto.randomUUID(), @@ -100,6 +104,10 @@ export const toFormValues = ( // ADHOC fields sourceType: adhoc?.sourceType ?? 'sql', sources: adhoc?.sources ?? [], + + // DATA_SOURCE fields + allowedSourceKinds: dataSource?.allowedSourceKinds ?? [], + connection: dataSource?.connection, }; }; @@ -140,6 +148,28 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { }); } + // Reference variables are always single-select and required, so only the + // global requirement checkbox is consulted + if (isReferenceVariableFilterType(values.type)) { + return DashboardFilterSchema.parse({ + id: values.id, + type: values.type, + name: values.name, + ...(values.type === 'DATA_SOURCE' + ? { + allowedSourceKinds: values.allowedSourceKinds, + connection: values.connection || undefined, + } + : {}), + minSelections: 1, + maxSelections: 1, + ...(isGlobalRequirement ? { isGlobalRequirement: true } : {}), + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: getFilterVariableName(values), + }); + } + const appliesTo = values.appliesToSourceIds?.filter(id => !!id?.length); const trimmedWhere = values.where?.trim() ?? ''; const whereFields = { diff --git a/packages/app/src/components/ReferenceVariableDashboardFilter.tsx b/packages/app/src/components/ReferenceVariableDashboardFilter.tsx new file mode 100644 index 0000000000..0f163c5f1b --- /dev/null +++ b/packages/app/src/components/ReferenceVariableDashboardFilter.tsx @@ -0,0 +1,188 @@ +import { useCallback, useMemo } from 'react'; +import { isSourceOfferedByVariable } from '@hyperdx/common-utils/dist/referenceVariables'; +import { + ConnectionDashboardFilter as ConnectionFilter, + DataSourceDashboardFilter as DataSourceFilter, + TSource, +} from '@hyperdx/common-utils/dist/types'; +import { + Center, + CheckIcon, + ComboboxItem, + Group, + Select, + Stack, + Text, +} from '@mantine/core'; +import { IconServer, IconStack } from '@tabler/icons-react'; + +import { isValueInSelectData } from '@/components/SelectControlled'; +import { + getSourceOptionIcon, + sourceSelectFilter, + SourceSelectGroup, + useFilteredSortedSourceItems, + useSourceKindMap, +} from '@/components/sourceSelectUtils'; +import { useConnectionItems } from '@/hooks/useConnectionItems'; +import { useSources } from '@/source'; + +import { + DashboardFilterLabel, + FilterCaution, + FilterEffect, + getPendingVariablesTooltip, +} from './DashboardFilterLabel'; + +import sourceSelectStyles from '@styles/SourceSelectControlled.module.scss'; + +type ReferenceVariableFilterProps = { + value: string | undefined; + onChange: (id: string | undefined) => void; + effect: FilterEffect; + requiredTooltip: string; +}; + +/** + * The filter bar control shared by data source and connection variables: a + * single picker over the IDs the variable can select. + */ +function ReferenceVariableSelect({ + name, + items, + value, + onChange, + effect, + requiredTooltip, + pendingVariables, + placeholder, + renderIcon, +}: ReferenceVariableFilterProps & { + name: string; + items: ComboboxItem[] | SourceSelectGroup[]; + pendingVariables?: string[]; + placeholder: string; + renderIcon: (value: string | null) => React.ReactNode; +}) { + // A selection that is no longer offered (deleted, disabled, or no longer + // allowed by the variable) shows as empty, so it reads as unselected. + const isOffered = useMemo( + () => isValueInSelectData(items, value), + [items, value], + ); + const selected = value && isOffered ? value : null; + + const renderOption = useCallback( + ({ option, checked }: { option: ComboboxItem; checked?: boolean }) => ( + + {checked ? ( +
+ +
+ ) : ( + renderIcon(option.value) + )} + {option.label} +
+ ), + [renderIcon], + ); + + return ( + + + {selected == null && ( + + )} + {!!pendingVariables?.length && ( + + )} + + , +})); +jest.mock('@/components/SQLEditor/SQLEditor', () => ({ + SQLEditorControlled: ({ + control, + name, + rules, + additionalCompletions, + }: { + control: FilterFormControl; + name: 'sqlTemplate'; + rules?: RegisterOptions; + additionalCompletions?: { label: string }[]; + }) => { + mockCompletionLabels.splice( + 0, + mockCompletionLabels.length, + ...(additionalCompletions ?? []).map(c => c.label), + ); + return ( +