diff --git a/.changeset/query-tiles-cost.md b/.changeset/query-tiles-cost.md new file mode 100644 index 000000000..7aec237d5 --- /dev/null +++ b/.changeset/query-tiles-cost.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': patch +--- + +feat(mcp): `clickstack_query_tiles` reports each tile's wall time (`elapsedMs`), +and rows and bytes read for builder and SQL tiles; PromQL results from +`clickstack_promql` and `clickstack_query_tile` carry `elapsedMs` diff --git a/packages/api/src/mcp/__tests__/dashboards/promqlQueryTile.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/promqlQueryTile.int.test.ts index 31960fe98..f5e30666c 100644 --- a/packages/api/src/mcp/__tests__/dashboards/promqlQueryTile.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/promqlQueryTile.int.test.ts @@ -331,8 +331,10 @@ describe('MCP query_tile - PromQL tiles', () => { tileId: 'promql-tile', status: 'ok', hasData: true, + elapsedMs: expect.any(Number), }), ]); + expect(tiles[0]).not.toHaveProperty('rowsRead'); }); it('does not find a PromQL tile with PromQL disabled', async () => { 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 6b154c40e..d6077e4fd 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts @@ -243,6 +243,9 @@ describe('MCP Dashboard Tools - clickstack_query_tiles', () => { expect(tile.status).toBe('ok'); expect(tile.hasData).toBe(true); expect(tile.rowCount).toBeGreaterThan(0); + expect(tile.elapsedMs).toEqual(expect.any(Number)); + expect(tile.rowsRead).toBeGreaterThan(0); + expect(tile.bytesRead).toBeGreaterThan(0); }); it('skips a markdown tile passed explicitly in tileIds', async () => { diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts index 883408525..9bcf9dec8 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts @@ -123,6 +123,9 @@ describe('clickstack_query_tiles handler — per-tile failure isolation', () => expect(good.status).toBe('ok'); expect(boom.status).toBe('error'); expect(boom.error).toContain('source lookup exploded'); + // Failed tiles report their time too: the slow ones often fail. + expect(good.elapsedMs).toEqual(expect.any(Number)); + expect(boom.elapsedMs).toEqual(expect.any(Number)); }); it('does not issue a query for tiles scheduled after the deadline has passed', async () => { @@ -176,6 +179,8 @@ describe('clickstack_query_tiles handler — per-tile failure isolation', () => ); expect(overflow.status).toBe('error'); expect(overflow.error).toContain('deadline'); + // It never ran, so it reports no time (0 would read as cheap). + expect(overflow).not.toHaveProperty('elapsedMs'); const queriedIds = mockRunConfigTile.mock.calls.map((call: unknown[]) => { const t = call[1]; return t && typeof t === 'object' && 'id' in t ? t.id : undefined; diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts index 8a01a97ad..0256cb03a 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTilesSummarizeRows.test.ts @@ -11,6 +11,28 @@ describe('summarizeRows', () => { expect(summarizeRows(text)).toEqual({ hasData: true, rowCount: 1 }); }); + it("reports ClickHouse's read counts when the result carries statistics", () => { + const text = JSON.stringify({ + result: { + data: [{ a: 1 }], + statistics: { elapsed: 0.01, rows_read: 50, bytes_read: 483 }, + }, + }); + expect(summarizeRows(text)).toEqual({ + hasData: true, + rowCount: 1, + rowsRead: 50, + bytesRead: 483, + }); + }); + + it('omits both read counts when statistics are incomplete', () => { + const text = JSON.stringify({ + result: { data: [{ a: 1 }], statistics: { rows_read: 50 } }, + }); + expect(summarizeRows(text)).toEqual({ hasData: true, rowCount: 1 }); + }); + it('reports hasData=false and rowCount=0 for an empty result set', () => { expect(summarizeRows(JSON.stringify({ result: [] }))).toEqual({ hasData: false, diff --git a/packages/api/src/mcp/__tests__/promqlQueryTool.int.test.ts b/packages/api/src/mcp/__tests__/promqlQueryTool.int.test.ts index d9918ba01..03a55ad3b 100644 --- a/packages/api/src/mcp/__tests__/promqlQueryTool.int.test.ts +++ b/packages/api/src/mcp/__tests__/promqlQueryTool.int.test.ts @@ -104,7 +104,8 @@ describe('MCP clickstack_promql', () => { }); expect(result.isError ? getFirstText(result) : '').toBe(''); - const { data, seriesLabels } = parseResult(result); + const { data, seriesLabels, elapsedMs } = parseResult(result); + expect(elapsedMs).toEqual(expect.any(Number)); expect(seriesLabels).toEqual({ '{instance="checkout-0"}': { instance: 'checkout-0' }, '{instance="checkout-1"}': { instance: 'checkout-1' }, diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index bbde9c0dd..038af13f1 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -71,6 +71,11 @@ function isMarkdownTile(tile: ExternalDashboardTileWithId): boolean { return tile.config.displayType === 'markdown'; } +const readStatisticsSchema = z.object({ + rows_read: z.number(), + bytes_read: z.number(), +}); + /** * Derive a compact data summary from a successful tile query payload. The * payload shape is `{ result: , ... }` where `` is either an array @@ -83,6 +88,8 @@ function isMarkdownTile(tile: ExternalDashboardTileWithId): boolean { export function summarizeRows(text: string): { hasData?: boolean; rowCount?: number; + rowsRead?: number; + bytesRead?: number; } { let parsed: unknown; try { @@ -106,7 +113,19 @@ export function summarizeRows(text: string): { rows = result.data; } if (rows == null) return {}; - return { hasData: rows.length > 0, rowCount: rows.length }; + // ClickHouse's own read counts, present on builder and raw SQL tiles. + const stats = readStatisticsSchema.safeParse( + result != null && typeof result === 'object' && 'statistics' in result + ? result.statistics + : undefined, + ); + return { + hasData: rows.length > 0, + rowCount: rows.length, + ...(stats.success + ? { rowsRead: stats.data.rows_read, bytesRead: stats.data.bytes_read } + : {}), + }; } type TileSummary = { @@ -116,6 +135,10 @@ type TileSummary = { status: 'ok' | 'error' | 'skipped'; hasData?: boolean; rowCount?: number; + /** Wall time of the tile's query, from when it started (not queued). */ + elapsedMs?: number; + rowsRead?: number; + bytesRead?: number; error?: string; warnings?: string[]; }; @@ -144,7 +167,10 @@ export function registerQueryTiles({ 'unrecognized tile IDs come back as unknownTileIds rather than failing. ' + 'At most 50 tiles run per call; any beyond that are returned as ' + 'unrunTileIds — call again with those as tileIds to run the remainder. ' + - 'Drill into a specific failing tile with clickstack_query_tile.', + 'Drill into a specific failing tile with clickstack_query_tile. ' + + 'Each tile that ran reports elapsedMs, its wall time; builder and SQL ' + + 'tiles also report rowsRead and bytesRead. PromQL tiles report only ' + + 'elapsedMs: the Prometheus API returns no read counts.', inputSchema: z.object({ dashboardId: objectIdSchema.describe( 'Dashboard ID, from clickstack_get_dashboard (no id lists dashboards) ' + @@ -278,23 +304,30 @@ export function registerQueryTiles({ // results; the try/catch covers an unexpected throw or a deadline // timeout, folding either into a status:'error' entry so one // misbehaving tile never rejects the whole batch. + // Set when the query starts, so a tile the deadline skipped + // reports no time rather than 0. + let started: number | undefined; + const elapsed = () => + started === undefined + ? {} + : { elapsedMs: Math.round(performance.now() - started) }; try { - const result = await withDeadline( - signal => - runConfigTile( - context, - resolvedTile.tile, - startDate, - endDate, - { abortSignal: signal, variables }, - ), - deadlineAt, - ); + const result = await withDeadline(signal => { + started = performance.now(); + return runConfigTile( + context, + resolvedTile.tile, + startDate, + endDate, + { abortSignal: signal, variables }, + ); + }, deadlineAt); if ('isError' in result && result.isError) { return { ...base, status: 'error', + ...elapsed(), error: result.content?.[0]?.text ?? 'Unknown error', }; } @@ -310,6 +343,7 @@ export function registerQueryTiles({ return { ...base, status: 'ok', + ...elapsed(), ...summarizeRows(text), ...(warnings.length > 0 ? { warnings } : {}), }; @@ -317,6 +351,7 @@ export function registerQueryTiles({ return { ...base, status: 'error', + ...elapsed(), error: err instanceof Error ? err.message : String(err), }; } diff --git a/packages/api/src/mcp/tools/query/helpers.ts b/packages/api/src/mcp/tools/query/helpers.ts index 0f1467df9..b722186c2 100644 --- a/packages/api/src/mcp/tools/query/helpers.ts +++ b/packages/api/src/mcp/tools/query/helpers.ts @@ -746,15 +746,21 @@ export async function runConfigTile( // PromQL is evaluated by the Prometheus API, not the SQL renderer. if (isPromqlSavedChartConfig(savedConfig)) { try { - return formatQueryResult( - await runPromqlTile({ - context, - config: savedConfig, - dateRange: [startDate, endDate], - variables: options?.variables, - signal: options?.abortSignal, - }), - ); + const started = performance.now(); + const result = await runPromqlTile({ + context, + config: savedConfig, + dateRange: [startDate, endDate], + variables: options?.variables, + signal: options?.abortSignal, + }); + // The Prometheus API returns no read counts (unlike the JSON statistics + // of a SQL query), so wall time is the cost signal. It covers the whole + // tile: the source lookup and backend probe as well as the queries. + return formatQueryResult({ + ...result, + elapsedMs: Math.round(performance.now() - started), + }); } catch (e) { if (e instanceof PromQLQueryError) { return e.category === 'user' diff --git a/packages/api/src/mcp/tools/query/promql.ts b/packages/api/src/mcp/tools/query/promql.ts index 712c71e8a..a4403ba81 100644 --- a/packages/api/src/mcp/tools/query/promql.ts +++ b/packages/api/src/mcp/tools/query/promql.ts @@ -64,7 +64,9 @@ export function registerPromql({ context, registerTool }: ToolRegistrar) { 'A range query (the default) returns rows { __hdx_time_bucket, ' + 'series_name, value } plus seriesLabels, which maps each series_name to ' + 'its labels once. An instant query returns one row per series with a ' + - 'column per label plus Value, capped at 10,000 series.\n\n' + + 'column per label plus Value, capped at 10,000 series. Both carry ' + + "elapsedMs, the call's wall time; the Prometheus API returns no rows " + + 'or bytes read.\n\n' + 'Counters need rate() or increase(), e.g. ' + 'sum by (job) (rate(http_requests_total[$__rate_interval])). Percentiles ' + 'from histograms: histogram_quantile(0.95, sum by (le) ' +