Skip to content

feat(mcp): report each tile's wall time and read counts in query_tiles - #3822

Draft
bcanvural wants to merge 2 commits into
ClickHouse:mainfrom
bcanvural:feat/mcp-cost-statistics
Draft

bcanvural wants to merge 2 commits into
ClickHouse:mainfrom
bcanvural:feat/mcp-cost-statistics

Conversation

@bcanvural

Copy link
Copy Markdown
Contributor

Summary

Part of #3649 (not all of it; see "Not in this PR"). clickstack_query_tiles returned only status, hasData and rowCount per tile, so an agent couldn't tell a tile that read 10 GiB from one that read 4 MB. Now:

  • Every tile that ran reports elapsedMs, its wall time. It's measured from when the tile's query starts, so time spent waiting in the queue (6 tiles at a time) doesn't count. Failed tiles report it too, since the slow tiles are often the ones that fail.
  • Builder and SQL tiles also report rowsRead and bytesRead. These are ClickHouse's own numbers: they're already in each tile's JSON result (statistics), and summarizeRows now keeps them.
  • PromQL results carry elapsedMs, in clickstack_promql, clickstack_query_tile and per tile in clickstack_query_tiles. The Prometheus API returns no read counts, so wall time is the only cost signal there. The tool descriptions say so.

Not in this PR

How to reproduce

Starting point: make dev-int.

On main: clickstack_query_tiles on any dashboard returns tiles without elapsedMs, rowsRead or bytesRead, and clickstack_promql returns no elapsedMs.

On this branch:

  1. make dev-int FILE="mcp/__tests__/(dashboards/(queryTiles|promqlQueryTile)|promqlQueryTool)" passes, including the new assertions on elapsedMs, rowsRead and bytesRead.
  2. yarn jest src/mcp/__tests__/dashboards/queryTiles (unit) covers summarizeRows with statistics, and elapsedMs on a tile that throws.

How to test on Vercel preview

N/A — non-UI change.

References

Agents could not tell an expensive dashboard tile from a cheap one: query_tiles
kept only status, hasData and rowCount. Each tile that ran now reports
elapsedMs (measured from when it starts, so time waiting in the queue doesn't
count, and on failures too, since slow tiles are often the ones that fail),
plus ClickHouse's rowsRead and bytesRead when the tile's result carries them.

PromQL results get elapsedMs as well: the Prometheus API returns no read
counts, so wall time is the only cost signal there.

Part of ClickHouse#3649.
@bcanvural
bcanvural requested a review from a team as a code owner November 25, 2026 08:05
@changeset-bot

changeset-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: ab3eea3

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

This PR includes changesets to release 3 packages
Name Type
@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 25, 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.

// timeout, folding either into a status:'error' entry so one
// misbehaving tile never rejects the whole batch.
const started = Date.now();
const elapsed = () => ({ elapsedMs: Date.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 — Tiles skipped by the batch deadline still report elapsedMs (≈0), as if they ran

started is captured before withDeadline, and withDeadline (packages/api/src/mcp/utils/timeout.ts:87-90) throws DeadlineExceededError without starting the query once the budget is spent. The catch block then spreads ...elapsed(), so a tile that never ran comes back with elapsedMs: 0. That contradicts the new description ('Each tile that ran reports elapsedMs'), and an agent ranking tiles by cost will read 0 as 'cheap'. Fix: omit elapsedMs when err instanceof DeadlineExceededError and the work never started, or record started inside the thunk passed to withDeadline. Then assert in the existing 'does not issue a query for tiles scheduled after the deadline' test that elapsedMs is absent.

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 ab3eea3: the clock starts inside the work withDeadline runs, so a skipped tile has no elapsedMs. The deadline test now checks that.

signal: options?.abortSignal,
}),
);
const started = Date.now();

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 elapsedMs includes source lookup and backend probing, not just query wall time

started is taken before runPromqlTile, which first runs resolvePromqlTarget (Mongo lookups) and resolvePromqlQueryBackend, which probes the server for its Prometheus HTTP API (packages/api/src/mcp/tools/query/promqlTile.ts:127-150). Only then does it run the queries. The clickstack_promql description calls this "the query's wall time". Fix: either time only the runPromqlQuery calls inside runPromqlTile and return that value, or change the description to say it is the whole tile's wall time, including setup.

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 ab3eea3 by wording: the description now says the call's wall time. It includes the source lookup and backend probe on purpose, since that's part of what the call costs.

@github-actions

github-actions Bot commented Nov 25, 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.

1 finding(s): 🔴 0 P0/P1 · 🟡 1 P2 · 🔵 0 P3

1 posted as inline comment(s) on the changed lines.


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 25, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. This is an additive observability change: new optional fields (elapsedMs, rowsRead, bytesRead) with no removed or retyped fields, and the timing/deadline/failure-isolation logic was verified correct across all paths (deadline-skipped tiles correctly omit elapsedMs; failed and timed-out tiles report it; summarizeRows safely handles array and incomplete-statistics payloads). The two prior author-reported fixes are confirmed present.

🟡 P2 -- recommended

  • packages/api/src/mcp/tools/dashboards/queryTile.ts:38 -- the changed runConfigTile now spreads elapsedMs into the PromQL result, so clickstack_query_tile returns result.elapsedMs for PromQL tiles, but this tool's description still lists only result, note, hints, and warnings, leaving the new cost signal undiscoverable to agents.
    • Fix: Document elapsedMs (nested under result, PromQL-only) in the clickstack_query_tile description, mirroring the wording added to clickstack_promql and clickstack_query_tiles.
    • api-contract, agent-native
🔵 P3 nitpicks (4)
  • packages/api/src/mcp/tools/query/helpers.ts:760 -- elapsedMs placement is inconsistent across tools: top-level per tile in clickstack_query_tiles versus nested under result in clickstack_promql and clickstack_query_tile, and no description states where to read it.
    • Fix: State the read location in each tool description, or converge the three tools on one placement.
    • maintainability, api-contract, agent-native, kieran-typescript, correctness
  • packages/api/src/mcp/tools/dashboards/queryTiles.ts:169 -- the description says builder and SQL tiles "also report rowsRead and bytesRead," but both are omitted whenever ClickHouse statistics are absent or incomplete, so the fields are not guaranteed.
    • Fix: Soften the wording to note the counts are omitted when ClickHouse returns no read statistics.
    • api-contract
  • packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts:158 -- the ClickHouse isError (non-throw) branch spreads ...elapsed(), but only the thrown/catch path and the deadline-skip case assert elapsedMs; the isError branch is exercised without asserting it.
    • Fix: Assert elapsedMs is a number on the existing isError tile in the integration test.
    • testing, correctness
  • packages/api/src/mcp/tools/dashboards/queryTiles.ts:312 -- elapsed() returns {} | { elapsedMs } for spreading rather than a duration, so the name reads like a scalar and the let started mutable capture is non-obvious.
    • Fix: Rename to something like elapsedFields() to signal the spread-partial shape.
    • maintainability

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

Testing gaps:

  • No test covers a PromQL tile inside the clickstack_query_tiles batch (elapsedMs present, rowsRead/bytesRead absent); only the single-tile path is covered.
  • No test exercises the deadline-overrun path (query starts, then times out) to confirm elapsedMs is still reported.
  • No test confirms rowsRead/bytesRead behavior when a large result is trimmed by trimToolResponse.

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

Start a tile's clock inside the work withDeadline runs, so a tile that never
started reports no time instead of 0, which reads as cheap. Time with
performance.now(), and describe the PromQL elapsedMs as the call's wall time:
it includes the source lookup and backend probe. Test statistics without
bytes_read.
// 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.

@bcanvural

Copy link
Copy Markdown
Contributor Author

Deep review P2 on queryTile.ts: that file isn't part of this PR. Its description lists the envelope fields, not what each backend puts in result, so I'd leave that for a follow-up rather than widen this one.

Two review rounds are done with no P0/P1 left, so I'll stop on the automated findings here. @brandon-pereira, could you take a look when you have time?

@bcanvural
bcanvural marked this pull request as draft November 25, 2026 09:58

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant