From 0501198c85147f1a189f23ef13379e9a2fe1c519 Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Sat, 28 Nov 2026 17:04:28 +0100 Subject: [PATCH 1/3] feat(mcp): report the ClickHouse cost of event_patterns, emerging_signals and describe_source These tools build their own output, so the statistics in ClickHouse's JSON responses were dropped. A meter in the node ClickHouse client (withQueryCost) sums the statistics of each JSON result read inside it. Every MCP tool call runs in one, and the three tools return the totals as `statistics`, in the shape clickstack_table uses, plus a query count. runEventPatterns has its own meter, so an event-pattern tile reports only its own queries. Part of #3649 --- .changeset/mcp-cost-meter.md | 10 +++ MCP.md | 8 ++ .../__tests__/emergingSignalsTool.int.test.ts | 4 + .../src/mcp/__tests__/queryTool.int.test.ts | 4 + .../api/src/mcp/__tests__/sources.int.test.ts | 4 + .../src/mcp/tools/query/emergingSignals.ts | 2 + .../src/mcp/tools/query/runEventPatterns.ts | 14 ++-- .../mcp/tools/sources/describePromqlSource.ts | 2 + .../src/mcp/tools/sources/describeSource.ts | 3 + packages/api/src/mcp/utils/tracing.ts | 10 ++- .../__tests__/nodeQueryCost.test.ts | 63 +++++++++++++++ packages/common-utils/src/clickhouse/node.ts | 78 ++++++++++++++++++- 12 files changed, 189 insertions(+), 13 deletions(-) create mode 100644 .changeset/mcp-cost-meter.md create mode 100644 packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts diff --git a/.changeset/mcp-cost-meter.md b/.changeset/mcp-cost-meter.md new file mode 100644 index 0000000000..eca2e31f21 --- /dev/null +++ b/.changeset/mcp-cost-meter.md @@ -0,0 +1,10 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/api': patch +--- + +feat(mcp): `clickstack_event_patterns`, `clickstack_emerging_signals` and +`clickstack_describe_source` return `statistics` (`elapsed`, `rows_read`, +`bytes_read`, `queries`), summed over the ClickHouse queries of the call. A +query cost meter in the node ClickHouse client (`withQueryCost`) adds up the +statistics of each JSON result. diff --git a/MCP.md b/MCP.md index ea99bd3160..f1c695c36a 100644 --- a/MCP.md +++ b/MCP.md @@ -185,6 +185,14 @@ and PromQL tiles report the cost of the call: rows returned or the size of the response. Builder and SQL tiles report them when available. PromQL and event-pattern tiles report only `elapsedMs`. - A successful PromQL response carries its time at `result.elapsedMs`. +- `clickstack_event_patterns`, `clickstack_emerging_signals` and + `clickstack_describe_source` return `statistics` in the shape + `clickstack_table` uses (`elapsed` in seconds, `rows_read`, `bytes_read`), + summed over the ClickHouse queries of the call, and `queries`, how many there + were. `elapsed` is ClickHouse time, so queries that run at the same time add + up to more than the wall time. A cached schema lookup runs no query and adds + nothing. An event-pattern tile in `clickstack_query_tile` reports only its own + queries. ### Metric Sources diff --git a/packages/api/src/mcp/__tests__/emergingSignalsTool.int.test.ts b/packages/api/src/mcp/__tests__/emergingSignalsTool.int.test.ts index fb72744460..9db1fd9f5b 100644 --- a/packages/api/src/mcp/__tests__/emergingSignalsTool.int.test.ts +++ b/packages/api/src/mcp/__tests__/emergingSignalsTool.int.test.ts @@ -196,6 +196,10 @@ describe('MCP Emerging Signals Tool', () => { expect(output.summary.currentWindow.sampled).toBeGreaterThan(0); expect(output.summary.baselineWindow.sampled).toBeGreaterThan(0); expect(output.summary.warning).toBeUndefined(); + // What ClickHouse read for the call. + expect(output.statistics.queries).toBeGreaterThan(0); + expect(output.statistics.rows_read).toBeGreaterThan(0); + expect(output.statistics.bytes_read).toBeGreaterThan(0); // The shadow-eval template must appear in the emerging list as "new". expect(output.emerging.length).toBeGreaterThan(0); diff --git a/packages/api/src/mcp/__tests__/queryTool.int.test.ts b/packages/api/src/mcp/__tests__/queryTool.int.test.ts index 0169fe6c1e..5e25708c31 100644 --- a/packages/api/src/mcp/__tests__/queryTool.int.test.ts +++ b/packages/api/src/mcp/__tests__/queryTool.int.test.ts @@ -798,6 +798,10 @@ describe('MCP Query Tools', () => { expect(output).toHaveProperty('summary'); expect(output).toHaveProperty('patterns'); expect(output.summary).toHaveProperty('totalCount'); + // What ClickHouse read for the call. + expect(output.statistics.queries).toBeGreaterThan(0); + expect(output.statistics.rows_read).toBeGreaterThan(0); + expect(output.statistics.bytes_read).toBeGreaterThan(0); expect(output.summary).toHaveProperty('sampledCount'); expect(output.summary).toHaveProperty('sampleMultiplier'); expect(output.summary).toHaveProperty('bodyColumn', 'Body'); diff --git a/packages/api/src/mcp/__tests__/sources.int.test.ts b/packages/api/src/mcp/__tests__/sources.int.test.ts index a72dd60777..7c0574d0d3 100644 --- a/packages/api/src/mcp/__tests__/sources.int.test.ts +++ b/packages/api/src/mcp/__tests__/sources.int.test.ts @@ -445,6 +445,10 @@ describe('MCP Source Tools', () => { expect(output.source.columns[0]).toHaveProperty('name'); expect(output.source.columns[0]).toHaveProperty('type'); expect(output.source.columns[0]).toHaveProperty('jsType'); + // What ClickHouse read for the call. + expect(output.statistics.queries).toBeGreaterThan(0); + expect(output.statistics.rows_read).toBeGreaterThan(0); + expect(output.statistics.bytes_read).toBeGreaterThan(0); }); it('should return full column schema for a log source', async () => { diff --git a/packages/api/src/mcp/tools/query/emergingSignals.ts b/packages/api/src/mcp/tools/query/emergingSignals.ts index ad2fc5b20a..4786fbee3a 100644 --- a/packages/api/src/mcp/tools/query/emergingSignals.ts +++ b/packages/api/src/mcp/tools/query/emergingSignals.ts @@ -1,3 +1,4 @@ +import { getQueryCost } from '@hyperdx/common-utils/dist/clickhouse/node'; import { flattenBody, TemplateMiner, @@ -587,6 +588,7 @@ export function registerEmergingSignals({ }, emerging: emerging.slice(0, input.topN).map(fmt), disappeared: disappeared.slice(0, input.topN).map(fmt), + statistics: getQueryCost(), usage: 'emerging = patterns newly present or >= minShareRatioĂ— more frequent ' + '(by share of window) now vs baseline; status "new" means absent from ' + diff --git a/packages/api/src/mcp/tools/query/runEventPatterns.ts b/packages/api/src/mcp/tools/query/runEventPatterns.ts index 23462a51de..0fa697f75e 100644 --- a/packages/api/src/mcp/tools/query/runEventPatterns.ts +++ b/packages/api/src/mcp/tools/query/runEventPatterns.ts @@ -1,3 +1,4 @@ +import { withQueryCost } from '@hyperdx/common-utils/dist/clickhouse/node'; import { getMetadata } from '@hyperdx/common-utils/dist/core/metadata'; import { getSourceTableFilters } from '@hyperdx/common-utils/dist/core/searchChartConfig'; import { @@ -451,12 +452,9 @@ export async function runEventPatterns( // conversion, sampleMultiplier usage). The helper wraps minePatterns in // try/catch and returns an {error} union, so a thrown Drain error surfaces as // a clean MCP error here rather than escaping. - const mined = await mineWindowPatterns( - context, - sourceId, - startDate, - endDate, - { + // Its own meter, so a dashboard tile reports only its own queries. + const { result: mined, cost: statistics } = await withQueryCost(() => + mineWindowPatterns(context, sourceId, startDate, endDate, { where: options?.where, whereLanguage: options?.whereLanguage, bodyExpression: options?.bodyExpression, @@ -466,7 +464,7 @@ export async function runEventPatterns( abortSignal: options?.abortSignal, variables: options?.variables, includeDrilldownWhere: true, - }, + }), ); if ('error' in mined) return mined.error; @@ -503,6 +501,7 @@ export async function runEventPatterns( timeRange, }, patterns: [], + statistics, hint: 'No data found in the queried time range. Try setting startTime to a wider window (e.g. 24 hours ago) or check that filters match existing data.', }, null, @@ -604,6 +603,7 @@ export async function runEventPatterns( }, }, patterns, + statistics, usage: 'totalCount is exact. sampleCount is the number of sampled rows in the pattern. ' + 'estimatedCount = sampleCount * sampleMultiplier, an extrapolation, not a count; ' + diff --git a/packages/api/src/mcp/tools/sources/describePromqlSource.ts b/packages/api/src/mcp/tools/sources/describePromqlSource.ts index 9317f9678d..3a68e28bbb 100644 --- a/packages/api/src/mcp/tools/sources/describePromqlSource.ts +++ b/packages/api/src/mcp/tools/sources/describePromqlSource.ts @@ -1,3 +1,4 @@ +import { getQueryCost } from '@hyperdx/common-utils/dist/clickhouse/node'; import { quoteIdentifierIfNeeded } from '@hyperdx/common-utils/dist/core/metadata'; import { getPromqlLabelCatalog } from '@/controllers/promql'; @@ -129,6 +130,7 @@ function toResult( query: PROMQL_QUERY_USAGE, ...(sqlUsage ? { sql: sqlUsage } : {}), }, + statistics: getQueryCost(), }, null, 2, diff --git a/packages/api/src/mcp/tools/sources/describeSource.ts b/packages/api/src/mcp/tools/sources/describeSource.ts index bd4ff88eb9..2353a8a9bc 100644 --- a/packages/api/src/mcp/tools/sources/describeSource.ts +++ b/packages/api/src/mcp/tools/sources/describeSource.ts @@ -3,6 +3,7 @@ import { filterColumnMetaByType, JSDataType, } from '@hyperdx/common-utils/dist/clickhouse'; +import { getQueryCost } from '@hyperdx/common-utils/dist/clickhouse/node'; import { getMetadata, tcFromSource, @@ -203,6 +204,7 @@ async function describeSourceSchema( nextSteps: { query: `Use clickstack_timeseries, clickstack_table, or clickstack_search with sourceId "${sourceId}".`, }, + statistics: getQueryCost(), }, null, 2, @@ -552,6 +554,7 @@ function formatDescribeResult({ "Use bracket syntax for map columns: ResourceAttributes['service.name'], SpanAttributes['http.method']", ...(discoveryNextStep && { discovery: discoveryNextStep }), }, + statistics: getQueryCost(), }); const finalOutput = isTrimmed diff --git a/packages/api/src/mcp/utils/tracing.ts b/packages/api/src/mcp/utils/tracing.ts index 48ae9d9b3f..98d780045c 100644 --- a/packages/api/src/mcp/utils/tracing.ts +++ b/packages/api/src/mcp/utils/tracing.ts @@ -1,4 +1,7 @@ -import { withQueryAttribution } from '@hyperdx/common-utils/dist/clickhouse/node'; +import { + withQueryAttribution, + withQueryCost, +} from '@hyperdx/common-utils/dist/clickhouse/node'; import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { recordOnboardingTaskCompletion } from '@/controllers/user'; @@ -110,14 +113,15 @@ export function withToolTracing( try { // Around the whole handler, so every query the tool makes carries - // the tool name and who called it. + // the tool name and who called it, and tools can report the call's + // cost with getQueryCost(). const result = await withQueryAttribution( { surface: 'mcp', label: toolName, trace: getActiveTraceId(), }, - async () => handler(args), + async () => (await withQueryCost(async () => handler(args))).result, ); const durationMs = Date.now() - startTime; const responseBytes = getResponseSizeBytes(result.content); diff --git a/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts b/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts new file mode 100644 index 0000000000..a470d9457d --- /dev/null +++ b/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts @@ -0,0 +1,63 @@ +import type { ClickHouseClient as NodeClickHouseClient } from '@clickhouse/client'; + +import { + ClickhouseClient, + getQueryCost, + withQueryCost, +} from '@/clickhouse/node'; + +/** Answers every query with the statistics `statsFor` gives for its SQL. */ +class FakeServerClient extends ClickhouseClient { + constructor(private statsFor: (query: string) => object | undefined) { + super({ host: 'http://localhost:8123' }); + } + + protected getClient(): NodeClickHouseClient { + return { + query: async ({ query }: { query: string }) => ({ + json: async () => ({ data: [], statistics: this.statsFor(query) }), + }), + } as unknown as NodeClickHouseClient; + } +} + +const run = async (client: ClickhouseClient, query: string) => + (await client.query({ query, shouldSkipApplySettings: true })).json(); + +const client = new FakeServerClient(query => + query === 'SELECT none' + ? undefined + : { elapsed: 0.5, rows_read: 10, bytes_read: 100 }, +); + +describe('withQueryCost', () => { + it('sums the statistics of the JSON results read in it', async () => { + const { result, cost } = await withQueryCost(async () => { + await run(client, 'SELECT 1'); + await run(client, 'SELECT 2'); + // No statistics in the body: not counted. + await run(client, 'SELECT none'); + return getQueryCost(); + }); + + const expected = { elapsed: 1, rows_read: 20, bytes_read: 200, queries: 2 }; + expect(result).toEqual(expected); + expect(cost).toEqual(expected); + }); + + it('adds a nested meter to the enclosing one, not the reverse', async () => { + const { result: inner, cost: outer } = await withQueryCost(async () => { + await run(client, 'SELECT outer'); + const { cost } = await withQueryCost(() => run(client, 'SELECT inner')); + return cost; + }); + + expect(inner).toMatchObject({ rows_read: 10, queries: 1 }); + expect(outer).toMatchObject({ rows_read: 20, queries: 2 }); + }); + + it('counts nothing outside a meter', async () => { + await run(client, 'SELECT 1'); + expect(getQueryCost()).toBeUndefined(); + }); +}); diff --git a/packages/common-utils/src/clickhouse/node.ts b/packages/common-utils/src/clickhouse/node.ts index 6fd48afb1d..a3363dba5f 100644 --- a/packages/common-utils/src/clickhouse/node.ts +++ b/packages/common-utils/src/clickhouse/node.ts @@ -7,6 +7,7 @@ import type { DataFormat, } from '@clickhouse/client'; import { createClient } from '@clickhouse/client'; +import { z } from 'zod/v3'; import { mergeQueryAttribution, QueryAttribution } from './attribution'; import { @@ -47,6 +48,55 @@ export function getCurrentQueryAttribution(): QueryAttribution | undefined { return attributionStore.getStore(); } +/** ClickHouse's own numbers, summed over the queries that reported them. */ +export type QueryCost = { + /** Server time in seconds; concurrent queries add up past wall time. */ + elapsed: number; + rows_read: number; + bytes_read: number; + /** How many queries reported statistics (JSON results read with json()). */ + queries: number; +}; + +const statisticsBodySchema = z.object({ + statistics: z.object({ + elapsed: z.number().catch(0), + rows_read: z.number(), + bytes_read: z.number(), + }), +}); + +// Every meter in effect, innermost last: a query adds to all of them. +const costStore = new AsyncLocalStorage(); + +/** + * Sums the `statistics` of every JSON query `fn` issues, including queries in + * nested meters. Read the totals with getQueryCost() inside `fn`, or from the + * returned `cost` after it. + */ +export async function withQueryCost( + fn: () => Promise, +): Promise<{ result: T; cost: QueryCost }> { + const cost: QueryCost = { + elapsed: 0, + rows_read: 0, + bytes_read: 0, + queries: 0, + }; + const result = await costStore.run( + [...(costStore.getStore() ?? []), cost], + fn, + ); + return { result, cost: { ...cost } }; +} + +/** The innermost meter's totals so far, if a meter is in effect. */ +export function getQueryCost(): QueryCost | undefined { + const meters = costStore.getStore(); + const cost = meters?.[meters.length - 1]; + return cost && { ...cost }; +} + export class ClickhouseClient extends BaseClickhouseClient { constructor(options: ClickhouseClientOptions) { super(options); @@ -113,14 +163,36 @@ export class ClickhouseClient extends BaseClickhouseClient { } // TODO: Custom error handling - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- client library type mismatch - return this.getClient().query({ + const resultSet = await this.getClient().query({ query, query_params, format, abort_signal, clickhouse_settings: clickhouseSettings, query_id: queryId, - }) as unknown as Promise>; + }); + const meters = costStore.getStore(); + if (meters) { + // A JSON body ends with the query's statistics, so count them when the + // caller reads it. + const json = resultSet.json.bind(resultSet); + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- same method, wrapped + resultSet.json = (async () => { + const body = await json(); + const parsed = statisticsBodySchema.safeParse(body); + if (parsed.success) { + const stats = parsed.data.statistics; + for (const cost of meters) { + cost.elapsed += stats.elapsed; + cost.rows_read += stats.rows_read; + cost.bytes_read += stats.bytes_read; + cost.queries++; + } + } + return body; + }) as typeof resultSet.json; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- client library type mismatch + return resultSet as unknown as BaseResultSet; } } From 8d68bd64194c11c6a3a6353ca3eded89ce721953 Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Sat, 28 Nov 2026 18:01:10 +0100 Subject: [PATCH 2/3] fix(mcp): count only complete statistics, test concurrent meters, name the reads not counted Review round 1: elapsed is required like rows_read and bytes_read, so a body with incomplete statistics is skipped as a whole. Tests cover malformed statistics, two concurrent meters, and a result issued outside a meter. MCP.md says that results read as a stream are not counted. --- MCP.md | 12 +++--- .../__tests__/nodeQueryCost.test.ts | 37 +++++++++++++++---- packages/common-utils/src/clickhouse/node.ts | 7 ++-- 3 files changed, 41 insertions(+), 15 deletions(-) diff --git a/MCP.md b/MCP.md index f1c695c36a..41d6e27439 100644 --- a/MCP.md +++ b/MCP.md @@ -188,11 +188,13 @@ and PromQL tiles report the cost of the call: - `clickstack_event_patterns`, `clickstack_emerging_signals` and `clickstack_describe_source` return `statistics` in the shape `clickstack_table` uses (`elapsed` in seconds, `rows_read`, `bytes_read`), - summed over the ClickHouse queries of the call, and `queries`, how many there - were. `elapsed` is ClickHouse time, so queries that run at the same time add - up to more than the wall time. A cached schema lookup runs no query and adds - nothing. An event-pattern tile in `clickstack_query_tile` reports only its own - queries. + summed over the ClickHouse queries of the call, and `queries`, how many + queries reported them. Only JSON results carry statistics: a result read as a + stream, like the primary key values `clickstack_describe_source` reads from + the index, is not counted. `elapsed` is ClickHouse time, so queries that run + at the same time add up to more than the wall time. A cached schema lookup + runs no query and adds nothing. An event-pattern tile in + `clickstack_query_tile` reports only its own queries. ### Metric Sources diff --git a/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts b/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts index a470d9457d..d8b2ead8b2 100644 --- a/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts +++ b/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts @@ -24,19 +24,22 @@ class FakeServerClient extends ClickhouseClient { const run = async (client: ClickhouseClient, query: string) => (await client.query({ query, shouldSkipApplySettings: true })).json(); -const client = new FakeServerClient(query => - query === 'SELECT none' - ? undefined - : { elapsed: 0.5, rows_read: 10, bytes_read: 100 }, -); +const client = new FakeServerClient(query => { + if (query === 'SELECT none') return undefined; + if (query === 'SELECT malformed') { + return { elapsed: 0.5, rows_read: '10', bytes_read: 100 }; + } + return { elapsed: 0.5, rows_read: 10, bytes_read: 100 }; +}); describe('withQueryCost', () => { it('sums the statistics of the JSON results read in it', async () => { const { result, cost } = await withQueryCost(async () => { await run(client, 'SELECT 1'); await run(client, 'SELECT 2'); - // No statistics in the body: not counted. + // No complete statistics in the body: not counted. await run(client, 'SELECT none'); + await run(client, 'SELECT malformed'); return getQueryCost(); }); @@ -56,8 +59,28 @@ describe('withQueryCost', () => { expect(outer).toMatchObject({ rows_read: 20, queries: 2 }); }); + it('keeps concurrent meters apart', async () => { + const [one, two] = await Promise.all([ + withQueryCost(() => run(client, 'SELECT 1')), + withQueryCost(async () => { + await run(client, 'SELECT 1'); + await run(client, 'SELECT 2'); + }), + ]); + + expect(one.cost.queries).toBe(1); + expect(two.cost.queries).toBe(2); + }); + it('counts nothing outside a meter', async () => { - await run(client, 'SELECT 1'); + const resultSet = await client.query({ + query: 'SELECT 1', + shouldSkipApplySettings: true, + }); expect(getQueryCost()).toBeUndefined(); + + // Read inside a meter, but issued outside one. + const { cost } = await withQueryCost(() => resultSet.json()); + expect(cost.queries).toBe(0); }); }); diff --git a/packages/common-utils/src/clickhouse/node.ts b/packages/common-utils/src/clickhouse/node.ts index a3363dba5f..cfecb584f1 100644 --- a/packages/common-utils/src/clickhouse/node.ts +++ b/packages/common-utils/src/clickhouse/node.ts @@ -60,7 +60,7 @@ export type QueryCost = { const statisticsBodySchema = z.object({ statistics: z.object({ - elapsed: z.number().catch(0), + elapsed: z.number(), rows_read: z.number(), bytes_read: z.number(), }), @@ -71,8 +71,9 @@ const costStore = new AsyncLocalStorage(); /** * Sums the `statistics` of every JSON query `fn` issues, including queries in - * nested meters. Read the totals with getQueryCost() inside `fn`, or from the - * returned `cost` after it. + * nested meters. A query whose body has no complete statistics is not counted. + * Read the totals with getQueryCost() inside `fn`, or from the returned + * `cost`, which holds the results read before `fn` resolved. */ export async function withQueryCost( fn: () => Promise, From 488d4334bf4a305864ea72bde7ce604b345453f3 Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Sat, 28 Nov 2026 18:11:47 +0100 Subject: [PATCH 3/3] fix(mcp): round the summed elapsed to microseconds when it is read Review round 2: adding float seconds leaves noise like 0.30000000000000004 in the tools' output. The running total stays exact. --- .../src/clickhouse/__tests__/nodeQueryCost.test.ts | 14 ++++++++++++++ packages/common-utils/src/clickhouse/node.ts | 10 ++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts b/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts index d8b2ead8b2..57febf2714 100644 --- a/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts +++ b/packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts @@ -26,6 +26,9 @@ const run = async (client: ClickhouseClient, query: string) => const client = new FakeServerClient(query => { if (query === 'SELECT none') return undefined; + if (query === 'SELECT tenth') { + return { elapsed: 0.1, rows_read: 1, bytes_read: 1 }; + } if (query === 'SELECT malformed') { return { elapsed: 0.5, rows_read: '10', bytes_read: 100 }; } @@ -59,6 +62,17 @@ describe('withQueryCost', () => { expect(outer).toMatchObject({ rows_read: 20, queries: 2 }); }); + it('rounds elapsed to microseconds', async () => { + const { result, cost } = await withQueryCost(async () => { + // 0.1 + 0.1 + 0.1 is 0.30000000000000004 in floating point. + for (let i = 0; i < 3; i++) await run(client, 'SELECT tenth'); + return getQueryCost(); + }); + + expect(result?.elapsed).toBe(0.3); + expect(cost.elapsed).toBe(0.3); + }); + it('keeps concurrent meters apart', async () => { const [one, two] = await Promise.all([ withQueryCost(() => run(client, 'SELECT 1')), diff --git a/packages/common-utils/src/clickhouse/node.ts b/packages/common-utils/src/clickhouse/node.ts index cfecb584f1..add25d3854 100644 --- a/packages/common-utils/src/clickhouse/node.ts +++ b/packages/common-utils/src/clickhouse/node.ts @@ -88,14 +88,20 @@ export async function withQueryCost( [...(costStore.getStore() ?? []), cost], fn, ); - return { result, cost: { ...cost } }; + return { result, cost: readCost(cost) }; } +// The running total stays exact; a copy for output drops float noise. +const readCost = (cost: QueryCost): QueryCost => ({ + ...cost, + elapsed: Math.round(cost.elapsed * 1e6) / 1e6, +}); + /** The innermost meter's totals so far, if a meter is in effect. */ export function getQueryCost(): QueryCost | undefined { const meters = costStore.getStore(); const cost = meters?.[meters.length - 1]; - return cost && { ...cost }; + return cost && readCost(cost); } export class ClickhouseClient extends BaseClickhouseClient {