Skip to content

feat(mcp): report the ClickHouse cost of event_patterns, emerging_signals and describe_source - #3856

Merged
kodiakhq[bot] merged 6 commits into
ClickHouse:mainfrom
bcanvural:feat/mcp-cost-meter
Dec 1, 2026
Merged

kodiakhq[bot] merged 6 commits into
ClickHouse:mainfrom
bcanvural:feat/mcp-cost-meter

Conversation

@bcanvural

@bcanvural bcanvural commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Part of #3649 (follows #3822)

Problem

clickstack_event_patterns, clickstack_emerging_signals and clickstack_describe_source return no cost numbers. They build their own output, so the statistics in 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

  • Meter in the node ClickHouse client (common-utils/src/clickhouse/node.ts): withQueryCost(fn) and getQueryCost(), an AsyncLocalStorage next to the existing attribution store. Inside a meter, __query wraps the result's json(). When the body has statistics, they are added to every enclosing meter, along with a query count.
  • Every MCP tool call runs in a meter (createToolHandler in mcp/utils/tracing.ts, next to withQueryAttribution).
  • The three tools return statistics: { elapsed, rows_read, bytes_read, queries }, summed over the call, in the shape clickstack_table uses. describe_source covers all its outputs: full, partial at the deadline, no table, and PromQL sources.
  • runEventPatterns has its own nested meter, so an event-pattern tile in clickstack_query_tile reports only its own queries. The call's meter still counts them.
  • Docs: a bullet in the MCP.md "Query cost metadata" section.

Limits

Testing

  • nodeQueryCost.test.ts (unit): sums JSON statistics, skips bodies without them, nested meters add to the enclosing one, nothing counted outside a meter.
  • Int: clickstack_event_patterns, clickstack_emerging_signals and clickstack_describe_source return statistics with queries, rows_read and bytes_read > 0.
  • MCP unit tests (1,122) and the MCP and dashboard int suites (453) pass.

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 accumulates elapsed, rows_read, bytes_read, and queries from JSON result bodies when json() is called. Every MCP tool invocation is wrapped in a cost meter alongside existing query attribution.

clickstack_event_patterns, clickstack_emerging_signals, and clickstack_describe_source (including PromQL describe paths) now include a top-level statistics object in the same shape as clickstack_table. runEventPatterns uses 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.

…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
@bcanvural
bcanvural requested a review from a team as a code owner November 28, 2026 16:49
@changeset-bot

changeset-bot Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 7832f16

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@hyperdx/common-utils Patch
@hyperdx/api Patch
@hyperdx/app Patch
@hyperdx/otel-collector Patch

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

@vercel

vercel Bot commented Nov 28, 2026

Copy link
Copy Markdown

@bcanvural is attempting to deploy a commit to the HyperDX Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

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
  • 🔵 P3 packages/common-utils/src/clickhouse/node.ts:49 — QueryCost restates the ClickHouse statistics shape instead of deriving it → elapsed/rows_read/bytes_read is already defined as ResponseJSON['statistics'] in @clickhouse/client, which windowedSearch.ts:63-81 uses for the same summing. Following the DRY rule in the repository conventions ("derive from it"), declare type QueryCost = NonNullable<ResponseJSON['statistics']> & { queries: number } so the two can't drift apart.

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.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. This is a focused, well-tested observability change. The core meter is gated on an active AsyncLocalStorage scope, so non-MCP ClickHouse callers are provably unaffected; concurrency isolation, microsecond rounding, nested-meter accumulation, and error propagation through the withQueryCost → withQueryAttribution wrapper were all independently confirmed clean. All prior-round review feedback (required elapsed in the schema, stream-read wording, concurrent-meter test, microsecond rounding) is verified present in the current diff.

🟡 P2 — recommended

  • packages/api/src/mcp/utils/tracing.ts:124 — the wrapper now computes the call's ClickHouse cost via withQueryCost but takes only .result and discards .cost, so the numbers reach the MCP client yet never land on the tool's own span or a metric, contrary to the repo's observability guidance for countable query costs.
    • Fix: Capture cost and set span attributes (e.g. mcp.tool.ch.rows_read, bytes_read, elapsed_s, queries) and/or emit a histogram alongside the existing response-size instrumentation.
    • project-standards
🔵 P3 nitpicks (5)
  • packages/common-utils/src/clickhouse/node.ts:188 — countedJson re-accumulates into every captured meter on each call with no idempotency guard; harmless today because no caller reads one result set's json() twice, but it is a latent trap on the shared __query path and is untested.
    • Fix: Guard countedJson with a counted flag captured in the closure so a result set's statistics are summed at most once, and add a double-read unit case.
    • testing, adversarial, correctness, reliability, kieran-typescript
  • packages/common-utils/src/clickhouse/node.ts:181 — cost accounting is wired only into result-set json(); queries drained via stream() + per-row row.json() (reachable from describe_source through getMapKeys) contribute nothing, and the type gives no signal of this exclusion.
    • Fix: Note on the QueryCost type / withQueryCost doc comment that only result-set json() reads are metered, so a future streaming consumer's silent under-count is expected rather than surprising.
    • maintainability, adversarial, correctness, kieran-typescript
  • packages/api/src/mcp/tools/sources/describeSource.ts:207 — the newly added statistics field on the no-table early-return and PromQL (describePromqlSource.ts:133) branches is never asserted; integration tests cover only the normal source path.
    • Fix: Add statistics assertions to the no-table and PromQL describe_source integration cases so all branches that emit the field are exercised.
    • testing
  • MCP.md:189 — the doc states the field is "in the shape clickstack_table uses," but clickstack_table nests statistics under result.statistics with only { elapsed, rows_read, bytes_read }, whereas these tools emit a top-level statistics that also carries queries.
    • Fix: Reword to describe a top-level statistics object with an added queries count, distinct from the nested result.statistics that table/search emit.
    • api-contract
  • packages/api/src/mcp/tools/query/emergingSignals.ts:591 — three of the four tools build statistics: getQueryCost(), which is dropped by JSON.stringify when no meter is active, while event_patterns uses the always-defined withQueryCost(...).cost; the field is guaranteed only because every handler currently runs inside the tool-tracing meter.
    • Fix: Fall back to a zeroed QueryCost (getQueryCost() ?? { elapsed: 0, rows_read: 0, bytes_read: 0, queries: 0 }) for structural consistency, or document statistics as best-effort.
    • api-contract, agent-native, kieran-typescript

Reviewers (12): correctness, adversarial, testing, maintainability, performance, reliability, api-contract, kieran-typescript, project-standards, previous-comments, agent-native, learnings-researcher.

Testing gaps:

  • No unit test reads one result set's json() twice (double-count behavior) or consumes a query via stream() instead of json() (silent under-count) inside a meter.
  • No assertion that the enclosing tool meter still counts runEventPatterns' nested-meter queries, nor that the ClickHouse-backed PromQL describe_source path accumulates non-zero statistics.
  • No test asserts statistics presence when a handler runs outside the withToolTracing wrapper, where getQueryCost() would return undefined for three of the four tools.

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;

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 — 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

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.

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(() =>

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 — 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

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.

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.

@bcanvural

Copy link
Copy Markdown
Contributor Author

Round 1, fixed in 8d68bd6:

  • deep-review P2 (schema): elapsed is now required like rows_read and bytes_read, so a body with incomplete statistics is skipped as a whole. There is a unit case with a malformed rows_read.
  • deep-review P2 (stream reads) and P3 (queries wording): MCP.md now says queries counts the queries that reported statistics, and that a result read as a stream is not counted. It names the primary key values clickstack_describe_source reads from the index, a small index read. The large sampling queries return JSON and are counted.
  • claude-review P3 (tests): added a test for two concurrent meters, and the "outside a meter" test now reads, inside a meter, a result issued outside one.
  • deep-review P3 (cost JSDoc): it now says the returned cost holds the results read before fn resolved.

Not changed:

  • QueryCost from ResponseJSON['statistics'] and a shared addStatistics with mergeWindowResults: that means changing windowedSearch.ts, which this PR does not touch. I'd leave it for a follow-up.
  • statistics: getQueryCost() at each output and comments at the call sites: it is one field per output, and createToolHandler runs every tool call in a meter (commented there). A helper would not be shorter.

Round 2, fixed in 488d433:

  • claude-review P2 (float noise): getQueryCost() and the returned cost round elapsed to microseconds. The running total stays exact.

Not changed:

  • Cost when the metadata cache merges two identical lookups: the call that runs the query is credited with it, and the other call read nothing. That seems right to me.
  • Each tool owning its meter: as above, createToolHandler runs every tool call in a meter.
  • A counted-once guard on json(): a result set's stream can be read only once, so a second json() throws instead of counting again.
  • More branch assertions: the no-table, no-data and PromQL outputs add the same field from the same call as the tested paths.
  • minor changeset for @hyperdx/common-utils: the package is private, so the new exports are not a public surface.

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.

@bcanvural

Copy link
Copy Markdown
Contributor Author

@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
bcanvural marked this pull request as draft November 30, 2026 13:19
@brandon-pereira

Copy link
Copy Markdown
Member

@bcanvural is this one ready for review?

@bcanvural

Copy link
Copy Markdown
Contributor Author

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.

@bcanvural
bcanvural marked this pull request as ready for review December 1, 2026 13:35
@brandon-pereira
brandon-pereira requested a balanced review from Copilot December 1, 2026 21:04
brandon-pereira
brandon-pereira previously approved these changes Dec 1, 2026

@brandon-pereira brandon-pereira left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM!

Copilot AI left a comment

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.

🟢 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

endDate,
{
// Its own meter, so a dashboard tile reports only its own queries.
const { result: mined, cost: statistics } = await withQueryCost(() =>

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 — 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

@kodiakhq
kodiakhq Bot merged commit 210ba59 into ClickHouse:main Dec 1, 2026
27 of 29 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants