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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/query-tiles-cost.md
Original file line number Diff line number Diff line change
@@ -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`
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down
61 changes: 48 additions & 13 deletions packages/api/src/mcp/tools/dashboards/queryTiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: <data>, ... }` where `<data>` is either an array
Expand All @@ -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 {
Expand All @@ -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 = {
Expand All @@ -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[];
};
Expand Down Expand Up @@ -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) ' +
Expand Down Expand Up @@ -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',
};
}
Expand All @@ -310,13 +343,15 @@ export function registerQueryTiles({
return {
...base,
status: 'ok',
...elapsed(),
...summarizeRows(text),
...(warnings.length > 0 ? { warnings } : {}),
};
} catch (err) {
return {
...base,
status: 'error',
...elapsed(),
error: err instanceof Error ? err.message : String(err),
};
}
Expand Down
24 changes: 15 additions & 9 deletions packages/api/src/mcp/tools/query/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — PromQL and SQL results now report wall time under different keys and units

clickstack_query_tile / clickstack_sql already put ClickHouse's time in result.statistics.elapsed, in seconds (windowedSearch.ts:68-80 builds the same shape). This change puts PromQL time in result.elapsedMs, in milliseconds. An agent comparing tiles from clickstack_query_tile now has to know two field names and two units. Fix: emit PromQL time as statistics: { elapsed: seconds } to match the SQL shape, or add elapsedMs to the builder and SQL branches of runConfigTile as well, so every result carries the same field.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping this as is. statistics is ClickHouse's own block and comes with read counts. A PromQL call has none, so a statistics block with only elapsed would look like ClickHouse output with the counts missing. elapsedMs names its unit.

});
} catch (e) {
if (e instanceof PromQLQueryError) {
return e.category === 'user'
Expand Down
4 changes: 3 additions & 1 deletion packages/api/src/mcp/tools/query/promql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) ' +
Expand Down
Loading