Repository navigation
feat(mcp): report the ClickHouse cost of event_patterns, emerging_signals and describe_source - #3856
Conversation
…nals 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 ClickHouse#3649
🦋 Changeset detectedLatest commit: 7832f16 The changes in this PR will be included in the next version bump. This PR includes changesets to release 4 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
@bcanvural is attempting to deploy a commit to the HyperDX Team on Vercel. A member of the Team first needs to authorize it. |
PR Review
2 finding(s): 🔴 0 P0/P1 · 🟡 1 P2 · 🔵 1 P3 1 posted as inline comment(s) on the changed lines. 1 P3 folded at the bottom. 🔵 1 P3 — no action needed before merge
Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides. |
Deep Review✅ No critical issues found. This is a focused, well-tested observability change. The core meter is gated on an active 🟡 P2 — recommended
🔵 P3 nitpicks (5)
Reviewers (12): correctness, adversarial, testing, maintainability, performance, reliability, api-contract, kieran-typescript, project-standards, previous-comments, agent-native, learnings-researcher. Testing gaps:
No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond |
…e 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.
| if (parsed.success) { | ||
| const stats = parsed.data.statistics; | ||
| for (const cost of meters) { | ||
| cost.elapsed += stats.elapsed; |
There was a problem hiding this comment.
🟡 P2 — Adding up elapsed as floats puts long decimal tails in agent-facing output
Adding ClickHouse's elapsed seconds as floats (e.g. 0.001234 + 0.002345 = 0.0035790000000000006) puts rounding noise into the statistics that the three tools serialise. Round once where the cost is read, in getQueryCost() and in the cost copy that withQueryCost returns, e.g. Math.round(elapsed * 1e6) / 1e6. Keep the running total unrounded.
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.
Fixed in 488d433: getQueryCost() and the returned cost round elapsed to microseconds; the running total stays exact.
Review round 2: adding float seconds leaves noise like 0.30000000000000004 in the tools' output. The running total stays exact.
| endDate, | ||
| { | ||
| // Its own meter, so a dashboard tile reports only its own queries. | ||
| const { result: mined, cost: statistics } = await withQueryCost(() => |
There was a problem hiding this comment.
🟡 P2 — The nested meter's totals are thrown away on the one path where they differ from the call's meter
The nested withQueryCost gives different numbers from the call-level meter only inside clickstack_query_tiles, where several tiles share one call. But that path runs the tile output through summarizeRows (packages/api/src/mcp/tools/dashboards/queryTiles.ts:79-125). Its tilePayloadSchema only reads result.statistics, and the event-pattern payload is {summary, patterns, statistics} with no result key, so those per-tile numbers are dropped. In clickstack_event_patterns and clickstack_query_tile the inner and outer meters count the same queries. Fix: have summarizeRows also accept a top-level statistics and map it to rowsRead/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 use getQueryCost().
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.
True for now: clickstack_query_tiles is 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 read statistics in summarizeRows to get per-tile numbers. Without it, each tile would report the whole call's total so far.
|
Round 1, fixed in 8d68bd6:
Not changed:
Round 2, fixed in 488d433:
Not changed:
Round 3 (488d433) has no P0/P1, so no code change. That is two rounds, so from here I'll only fix P0/P1 bot findings. |
|
@karl-power would you have time to review this? It follows #3822, which you reviewed: the same cost numbers for the three tools that still had none. |
|
@bcanvural is this one ready for review? |
|
Yes, it's ready. I only moved it to draft to stay within the three-open-PR limit while #3863 is in review. Happy to mark it ready now if you'd like to review it. |
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues block the ClickHouse cost-reporting changes.
No open issues 🎉
What changed in this PR
Adds ClickHouse cost reporting to MCP pattern and source-description tools, continuing #3649 after #3822’s tile timing work. Agents can now compare query costs using server-reported statistics.
Changes:
- Adds nested, request-scoped metering for ClickHouse JSON results.
- Returns cost statistics from event patterns, emerging signals, and source descriptions, with isolated totals for event-pattern tiles.
- Adds unit and integration coverage, documentation, and release notes.
| File | Description |
|---|---|
packages/common-utils/src/clickhouse/node.ts |
Adds query-cost meters and accumulates JSON statistics. |
packages/common-utils/src/clickhouse/__tests__/nodeQueryCost.test.ts |
Tests totals, nesting, isolation, and rounding. |
packages/api/src/mcp/utils/tracing.ts |
Wraps MCP tool calls in a cost meter. |
packages/api/src/mcp/tools/sources/describeSource.ts |
Includes statistics in source descriptions. |
packages/api/src/mcp/tools/sources/describePromqlSource.ts |
Includes statistics in PromQL source descriptions. |
packages/api/src/mcp/tools/query/runEventPatterns.ts |
Adds isolated pattern-query totals to results. |
packages/api/src/mcp/tools/query/emergingSignals.ts |
Includes call-level statistics in results. |
packages/api/src/mcp/__tests__/sources.int.test.ts |
Checks source-description cost fields. |
packages/api/src/mcp/__tests__/queryTool.int.test.ts |
Checks event-pattern cost fields. |
packages/api/src/mcp/__tests__/emergingSignalsTool.int.test.ts |
Checks emerging-signal cost fields. |
MCP.md |
Documents cost fields and metering limits. |
.changeset/mcp-cost-meter.md |
Records API and common-utils patch releases. |
Review effort: Balanced
…ape-hatch ratchet
| endDate, | ||
| { | ||
| // Its own meter, so a dashboard tile reports only its own queries. | ||
| const { result: mined, cost: statistics } = await withQueryCost(() => |
There was a problem hiding this comment.
🟡 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. clickstack_event_patterns and clickstack_query_tile each run one pattern job per call, so their tool-level meter (tracing.ts) gives the same totals. Per-tile cost would only add something in clickstack_query_tiles, but there summarizeRows (dashboards/queryTiles.ts:79-124) only parses { result: ... } payloads. It throws away the top-level statistics that an event-pattern tile returns. Fix one of two ways: (a) teach tilePayloadSchema/summarizeRows to read the event-pattern payload's top-level statistics so the tile gets rowsRead/bytesRead, and update the MCP.md line saying event-pattern tiles report only elapsedMs; or (b) remove the inner withQueryCost and use getQueryCost() like the other two tools.
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
Part of #3649 (follows #3822)
Problem
clickstack_event_patterns,clickstack_emerging_signalsandclickstack_describe_sourcereturn no cost numbers. They build their own output, so thestatisticsin ClickHouse's JSON responses get dropped. An agent can't tell a describe that read 5 GiB from one served by the metadata cache.Change
common-utils/src/clickhouse/node.ts):withQueryCost(fn)andgetQueryCost(), an AsyncLocalStorage next to the existing attribution store. Inside a meter,__querywraps the result'sjson(). When the body hasstatistics, they are added to every enclosing meter, along with a query count.createToolHandlerinmcp/utils/tracing.ts, next towithQueryAttribution).statistics:{ elapsed, rows_read, bytes_read, queries }, summed over the call, in the shapeclickstack_tableuses.describe_sourcecovers all its outputs: full, partial at the deadline, no table, and PromQL sources.runEventPatternshas its own nested meter, so an event-pattern tile inclickstack_query_tilereports only its own queries. The call's meter still counts them.Limits
elapsedis ClickHouse time, so concurrent queries add up to more than the wall time.json(). Streams, commands andJSONEachRowdon't carry statistics.read_rowsandread_bytesinX-ClickHouse-Summaryof the Prometheus query API ClickHouse#134761.clickstack_query_tilesis unchanged.Testing
nodeQueryCost.test.ts(unit): sums JSON statistics, skips bodies without them, nested meters add to the enclosing one, nothing counted outside a meter.clickstack_event_patterns,clickstack_emerging_signalsandclickstack_describe_sourcereturnstatisticswithqueries,rows_readandbytes_read> 0.Note
Low Risk
Additive response metadata and transparent
json()wrapping on the ClickHouse client; no auth, data, or query semantics changes.Overview
Adds ClickHouse query cost metering in the node client via
withQueryCost/getQueryCost, which accumulateselapsed,rows_read,bytes_read, andqueriesfrom JSON result bodies whenjson()is called. Every MCP tool invocation is wrapped in a cost meter alongside existing query attribution.clickstack_event_patterns,clickstack_emerging_signals, andclickstack_describe_source(including PromQL describe paths) now include a top-levelstatisticsobject in the same shape asclickstack_table.runEventPatternsuses a nested meter so dashboard event-pattern tiles can report only their own queries while the outer tool meter still counts everything.MCP.md documents the new fields and their limits (JSON-only, no streams/cached schema). Unit and integration tests cover the meter and the three tools’ responses.
Reviewed by Cursor Bugbot for commit 7832f16. Bugbot is set up for automated code reviews on this repo. Configure here.