Repository navigation
feat(mcp): report the ClickHouse cost of event_patterns, emerging_signals and describe_source #3856
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
0501198
8d68bd6
488d433
48f441a
0c52c23
7832f16
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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(() => | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 P2 — The nested meter in runEventPatterns can't help clickstack_query_tiles, the only place it would matter Two of the three callers already get the right number without the inner meter. 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 |
||
| 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; ' + | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| 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 => { | ||
| 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 }; | ||
| } | ||
| 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 complete statistics in the body: not counted. | ||
| await run(client, 'SELECT none'); | ||
| await run(client, 'SELECT malformed'); | ||
| 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('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')), | ||
| 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 () => { | ||
| 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); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 P2 — The nested meter's totals are thrown away on the one path where they differ from the call's meter
The nested
withQueryCostgives different numbers from the call-level meter only insideclickstack_query_tiles, where several tiles share one call. But that path runs the tile output throughsummarizeRows(packages/api/src/mcp/tools/dashboards/queryTiles.ts:79-125). ItstilePayloadSchemaonly readsresult.statistics, and the event-pattern payload is{summary, patterns, statistics}with noresultkey, so those per-tile numbers are dropped. Inclickstack_event_patternsandclickstack_query_tilethe inner and outer meters count the same queries. Fix: havesummarizeRowsalso accept a top-levelstatisticsand map it torowsRead/bytesRead, then update the queryTiles description ('event-pattern tiles do not') and MCP.md:186. If that is out of scope, remove the nested meter and usegetQueryCost().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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
True for now:
clickstack_query_tilesis unchanged in this PR (see Limits in the description), so its summary drops these numbers. The nested meter means that a later change only has to readstatisticsinsummarizeRowsto get per-tile numbers. Without it, each tile would report the whole call's total so far.