Skip to content

feat(mcp): emerging_signals compares both windows in one Drain tree and reports new variants - #3753

Merged
kodiakhq[bot] merged 10 commits into
ClickHouse:mainfrom
bcanvural:feat/emerging-signals-one-tree
Nov 27, 2026
Merged

kodiakhq[bot] merged 10 commits into
ClickHouse:mainfrom
bcanvural:feat/emerging-signals-one-tree

Conversation

@bcanvural

@bcanvural bcanvural commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Refs #3556, #3544 (option 2). Replaces draft #3557, which was stacked on the pre-merge version of #3551; this is the same change on current main.

emerging_signals mines the baseline and current windows in two separate Drain trees and matches their templates as strings. The two trees can generalize the same message differently: a token that is constant in one window stays literal there and becomes <*> in the other, so one unchanged pattern is reported as both "new" and "gone". Date masking (#3551) removed the most common cause; this removes the rest.

This PR:

  • fetches both windows in parallel, then mines them in one TemplateMiner, baseline first, and compares them by cluster id. The order is fixed, so the result doesn't depend on which query finishes first.
  • New variants. One tree can hide a new message that Drain merges into a similar baseline pattern (e.g. user login failed: account locked into user login failed: invalid password). Baseline templates are copied after the baseline is mined. A current row whose cluster came from the baseline but doesn't match that baseline template (token compare, no regex) is reported in emerging with status: "new_variant", baselinePattern, variantShare, and the new line as its sample. Baseline clusters with fewer than 3 sampled rows are skipped.
  • makes the earlier window half-open (dateRangeEndInclusive: false), so a row at the boundary is counted once.

Supporting changes: minePatterns takes an optional miner and returns rowClusterIds (the cluster of each input row); TemplateMiner.tokenize returns the masked tokens Drain compares. mineWindowPatterns is split into fetchWindowSample + mineWindowSample and kept as a wrapper, so event_patterns is unchanged.

Cost: on test data with 100 changed patterns, the variant step takes about 10 ms per 10K rows, and the whole call went from 496 ms to 221 ms (one tree instead of two).

How to reproduce

Starting point: make dev-int.

On main:

  1. Add packages/api/src/mcp/__tests__/emergingSignalsOrder.test.ts from this PR.
  2. npx jest src/mcp/__tests__/emergingSignalsOrder.test.ts in packages/api: it fails, because main has no fetchWindowSample / mineWindowSample and reports no new_variant.

On this branch:

  1. emergingSignalsOrder.test.ts passes (17 tests): the login example → new_variant; dated lines on two days → nothing; identical windows → nothing; a token varying only in the current window; same result whichever query finishes first; small baseline clusters skipped; a variant never shows in disappeared.
  2. drain-masking.test.ts (shared miner, rowClusterIds, tokenize) passes; common-utils 3,412, MCP unit 654 and MCP integration (queryTool, emergingSignalsTool, eventPatterns, dashboard) 370 tests pass.

How to test on Vercel preview

N/A — non-UI change.

References


Note

Medium Risk
Changes novelty-detection semantics and MCP output shape for emerging_signals; risk is mainly behavioral regressions in pattern classification, mitigated by extensive new tests rather than security or data-handling impact.

Overview
clickstack_emerging_signals no longer mines baseline and current in separate Drain trees and keys patterns by normalized template strings. It fetches both windows in parallel, then mines them in a single shared TemplateMiner in fixed order (baseline first) and compares by cluster id, so results are stable regardless of which query finishes first and tokens that are constant in one window no longer produce false paired “new” and “gone” signals.

The tool adds new_variant (new lines merged into an existing baseline cluster, with baselinePattern / variantShare) and gone_variant (baseline-only messages within a pattern that still appears). The earlier of the two windows uses a half-open end (endExclusive / dateRangeEndInclusive: false) so boundary rows are not double-counted.

Supporting plumbing: minePatterns accepts an optional shared miner and returns rowClusterIds; TemplateMiner.tokenize exposes masked tokens; window mining is split into fetchWindowSample + mineWindowSample (existing single-window flow still uses the wrapper). Response trimming now covers baselinePattern and currentPattern, with a large unit test suite for the new behavior.

Reviewed by Cursor Bugbot for commit 155fd01. Bugbot is set up for automated code reviews on this repo. Configure here.

…nd reports new variants

Both windows are mined in one tree, baseline first, and compared by cluster, so
a token that is constant in one window and varies in the other no longer splits
a pattern. New messages that Drain merges into a baseline pattern are found from
Drain's own row assignment with a token compare against the baseline template,
and reported as new_variant. The baseline window excludes its end.
@changeset-bot

changeset-bot Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 155fd01

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 21, 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.

…-one-tree

# Conflicts:
#	packages/api/src/mcp/tools/query/emergingSignals.ts
#	packages/api/src/mcp/tools/query/runEventPatterns.ts
@bcanvural
bcanvural marked this pull request as ready for review November 24, 2026 09:49
@bcanvural
bcanvural requested a review from a team as a code owner November 24, 2026 09:49
@github-actions

Copy link
Copy Markdown
Contributor

No description provided.

@github-actions

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

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

None could be anchored to changed lines; they are listed below. 3 P3 folded at the bottom.

Findings outside the changed lines

  • 🟡 P2 packages/api/src/mcp/tools/query/emergingSignals.ts:740 — gone_variant fires when a high-cardinality cluster just gets rarer in the current window → Here is the failure case. The baseline has 1,000 rows of a cluster where one token takes about 50 values with no digits (e.g. GET /api/<path> ok). The current window samples only 3 rows of that cluster, all with one path that also appears in the baseline. Then curTemplates is fully literal, fit > 0, and the other ~49 values are reported as one gone_variant with about 98% of the baseline share. The cluster only got rarer, which classifyShift would report as shifted. Fix: scale the evidence to the baseline's variety. For example, require the current template to have at least as many rows as the baseline has distinct values at the generalized positions, or require fit / (fit + rows) to be a meaningful share, before splitting out a gone variant.
🔵 3 P3 — no action needed before merge
  • 🔵 P3 packages/api/src/mcp/tools/query/emergingSignals.ts:686 — Token-length guards around getSeqDistance/createTemplate can never be false → Drain sends every message into a prefix tree keyed by token count (drain.ts treeSearch/addSeqToPrefixTree). miner.tokenize runs the same mask and getContentAsTokens as addLogMessage, so every row in a cluster has the cluster template's length. The checks tokens.length === tmpl.length, v.tokens.length === tokens.length, t.tokens.length === tokens.length, g.tokens.length === tokens.length and the second one at line 744 are always true. Drop them. Or, if the invariant is worth stating, assert it once, so a broken invariant isn't silently skipped (in curTemplates it would also stop t.rows from counting).
  • 🔵 P3 packages/api/src/mcp/tools/query/emergingSignals.ts:669 — About 200 lines of variant / gone-variant detection sit inside the MCP handler, testable only through a mocked tool call → Move the frozen-baseline snapshot, the variants/curTemplates/goneVariants passes and the split into rest/variant entries into a pure function next to minePatterns in packages/common-utils/src/drain/ (e.g. diffWindows(miner, baseSample, curSample)). The handler would then only fetch and format, and the logic could be unit-tested without mocking fetchWindowSample, @/models/source or the controllers.
  • 🔵 P3 packages/api/src/mcp/tools/query/emergingSignals.ts:714 — Almost every sampled row in both windows is masked and tokenized a second time → minePatterns already runs masker.mask and tokenizes every row through addLogMessage. The curTemplates pass runs miner.tokenize(flattenBody(...)) again on every current row in a baseline cluster with at least 3 rows, and the goneVariants pass does the same for the matching baseline rows. That is a second regex-mask pass over up to 2×25k bodies. Instead, have minePatterns return each row's masked tokens next to rowClusterIds, or let it take a callback, so the tokens are computed once.

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

Copy link
Copy Markdown
Contributor

No description provided.

1 similar comment
@github-actions

Copy link
Copy Markdown
Contributor

No description provided.

baseCount: a.baseCount,
sample: b?.sample ?? baselinePattern,
};
if (classifyShift(rest, ratio, newPatternShareFloor) === 'disappeared')

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.

Two variant rows hide a surge of the baseline message

Once a cluster has a variant above the floor, rest is only checked for disappeared. If the old message also grows past minShareRatio, that growth is dropped. Only the variant is reported, at its own small share.

Repro, using the helpers in emergingSignalsOrder.test.ts:

it('still reports a baseline message that surged next to a variant', async () => {
  const other = (n: number) =>
    Array.from({ length: n }, (_, i) => `cache warmed in ${i} regions ok`);
  const out = await run(
    [...repeat('payment failed: card declined', 10), ...other(990)],
    [
      ...repeat('payment failed: card declined', 500),
      ...repeat('payment failed: gateway timeout', 2),
      ...other(498),
    ],
  );
  expect(out.emerging).toContainEqual(
    expect.objectContaining({ status: 'shifted', pattern: 'payment failed: card declined' }),
  );
});
  • On this branch: emerging holds only new_variant (payment failed: <*> <*>) at share 0.002. The 0.01 → 0.5 jump of card declined doesn't appear anywhere.
  • Without the 2 gateway timeout rows: the same data reports shifted 0.01 → 0.5.

So 2 rows of a new message can hide a 50x increase in an existing one. That's probably the more important signal of the two.

Two possible fixes:

  1. Classify rest in both directions:
    const restVerdict = classifyShift(rest, ratio, newPatternShareFloor);
    if (restVerdict === 'emerging') emerging.push(rest);
    else if (restVerdict === 'disappeared') disappeared.push(rest);
    This gives a cluster two emerging entries in that case, so "gives one cluster at most one emerging entry" would need to change. I think two entries are correct here, because they are two separate changes.
  2. Keep one entry, but carry the remainder's shift on the variant entry, for example baselineMessageShare: { baseline, current }. Then rank it by the larger of the two swings, so a big surge isn't sorted under a 0.002 variant.

I'd lean toward option 1. The cost is that a cluster can take two emerging slots.

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.

Thanks, good catch. I went with option 1 in c8582fa. The rest of the cluster is now classified in both directions, so one cluster can have a new_variant entry and a shifted entry. I added your repro as a test (the surge ranks first), and changed the old "at most one emerging entry" test to expect both entries.

I also merged main, since #3742 landed; maxBodyChars now goes through fetchWindowSample.

…-one-tree

# Conflicts:
#	packages/api/src/mcp/tools/query/runEventPatterns.ts
A cluster with a new variant only checked the rest of the cluster for
disappeared, so a surge of the baseline message was dropped: two rows of a
new message could hide a 50x increase of an existing one. Classify the rest
in both directions; a cluster can now take two emerging entries, one per
change.
return;
const v = variants.get(key);
if (v) v.rows++;
else variants.set(key, { rows: 1, sample: raw });

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 — Different new messages in one baseline cluster merge into a single new_variant entry that shows only the first one's sample

variants is keyed by cluster id, and only the first row's body is kept as sample. Take a baseline of GET /api/cart 200 and a current window with 6× GET /api/cart 500 and 6× GET /api/cart 404: you get one entry with pattern GET /api/cart <*> and sample ...500, so the 404s are never shown. This is the same kind of hiding the PR set out to fix. Fix: key variants by cluster plus the masked token sequence (e.g. tokens.join(' ')), or keep several distinct samples per variant.

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.

This is intentional: variants are counted per baseline cluster, so one cluster gives at most one new_variant entry. Keying by the masked tokens would give one entry per distinct value of any unmasked token (IDs, hostnames), which can flood emerging. The entry's pattern (GET /api/cart <*>) shows which token varies, the share counts all the new rows, and sample is one example.

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

Scope: 8 files vs base f36e6788 — emerging_signals one-Drain-tree rewrite plus Drain plumbing (minePatterns shared miner + rowClusterIds, TemplateMiner.tokenize, fetchWindowSample/mineWindowSample split). Mode: report-only.

✅ No critical issues found. No P0/P1: correctness, adversarial, and previous-comments reviewers found no regression introduced by this diff. Every prior review thread claimed fixed (new-variant-drops-gone, a surge hidden behind a variant, the missing gone_variant direction, and the baselinePattern/currentPattern reduction caps) is verified present in the current code; the shared-miner index mapping (rowClusterIds ↔ sampleRows), baseline-token snapshot safety, sampleMultiplier window selection, and the length-guards before every getSeqDistance/createTemplate call all hold.

🟡 P2 — recommended

  • packages/api/src/mcp/tools/query/emergingSignals.ts:354 — The MCP tool drives Drain's own primitives (miner.drain.getSeqDistance/createTemplate/getCluster, cluster.logTemplateTokens) to re-implement cluster-membership one layer above the package that owns them; these are undocumented internals with no test pinning the contract, so a future Drain token/template change silently breaks variant detection rather than failing a build.
    • Fix: Add a public common-utils seam (e.g. a rowFitsTemplate(tokens, templateTokens) predicate and a template-merge helper) and depend on it instead of miner.drain.*.
    • maintainability, kieran-typescript, adversarial
  • packages/api/src/mcp/__tests__/emergingSignalsOrder.test.ts:57 — The mock sets totalCount: rows.length, forcing sampleMultiplier === 1 in every test, and no test asserts currentShare/baselineShare/currentEstimatedCount/baselineEstimatedCount; the new count-extrapolation and rest-split subtraction math (emergingSignals.ts:476-518) is therefore unverified.
    • Fix: Add a case where totalCount >> sampleRows.length and assert the count/share fields on a new_variant and a gone_variant entry.
    • testing, correctness, adversarial
  • packages/api/src/mcp/__tests__/emergingSignalsOrder.test.ts:440 — The >= 3 sampled-row floors (emergingSignals.ts:339,407) and the >= 2 stopped-row floor (:459) are exercised only with values strictly below the cut, so an inclusive-boundary off-by-one (>=→>) would leave the suite green.
    • Fix: Add boundary cases at exactly 3 sampled rows and exactly 2 stopped rows that DO report, alongside the existing just-under cases.
    • testing
🔵 P3 nitpicks (6)
  • packages/api/src/mcp/tools/query/emergingSignals.ts:550 — variantShare carries a different denominator on new_variant (current window, :550) vs gone_variant (baseline window, :556); a consumer reading it uniformly or comparing across the emerging/disappeared lists compares incommensurable quantities.
    • Fix: State the "share is always of this entry's own window" invariant explicitly in the usage text, or use distinct field names.
    • api-contract
  • packages/api/src/mcp/tools/query/emergingSignals.ts:347 — String(curRes.rowClusterIds.at(i)) yields the literal key "undefined" (silently missing every real key) if the cross-package parallel-array invariant ever desyncs, instead of failing loudly; it is safe today only because minePatterns emits exactly one id per row.
    • Fix: Index with rowClusterIds[i] and early-return on undefined, and/or document the length invariant on the rowClusterIds field.
    • kieran-typescript
  • packages/api/src/mcp/tools/query/emergingSignals.ts:342 — Redundant re-tokenization: the masked tokens Drain computes during mining are discarded, then recomputed per row across three passes (each tokenize ≈ 10 regex scans of the body); bounded at short bodies but scales with maxBodyChars (schema allows up to 1,000,000) and blocks the event loop synchronously.
    • Fix: Return the per-row token arrays minePatterns already computes and reuse them in the variant/gone passes; otherwise leave as the author's noted trade-off.
    • performance
  • packages/api/src/mcp/tools/query/emergingSignals.ts:198 — The registerTool handler is ~440 lines with six interleaved Map-building passes inline, so each collector can only be exercised end-to-end.
    • Fix: Extract collectNewVariants(...) / collectGoneVariants(...) helpers so each pass is independently nameable and testable.
    • maintainability
  • packages/api/src/mcp/__tests__/emergingSignalsOrder.test.ts:139 — The half-open test asserts only that endExclusive is passed to the mocked fetch; because the mock bypasses the query layer, the "boundary row counted once" claim is not verified end-to-end, and the assertion couples to positional call args.
    • Fix: Add an integration-level check (or note the dedup as a known mock-bypassed gap).
    • testing
  • packages/api/src/mcp/__tests__/emergingSignalsOrder.test.ts:128 — The order-independence deepEqual runs only the single-new_variant scenario; gone_variant, the double-variant single-cluster case, and shifted ranking are never checked for order independence.
    • Fix: Run the gone_variant and double-variant cases through both slowWindow orderings with a toEqual.
    • testing

Pre-existing (not counted toward verdict)

  • packages/api/src/mcp/tools/query/emergingSignals.ts:61 — classifyShift's disappeared branch (unchanged by this diff) applies no minimum-sampled-row floor, so a 1-row baseline-only cluster is labeled gone — asymmetric with the ~2-row floor gating brand-new emerging patterns. The one-tree path exercises it more often, but such entries have tiny share-swing, rank last, and are sliced off by topN; the main effect is an inflated disappearedCount summary. Pre-existing, not introduced here.

Reviewers (9): correctness, adversarial, testing, maintainability, performance, api-contract, kieran-typescript, previous-comments, project-standards.

Testing gaps:

  • New count/share math runs only at sampleMultiplier === 1; extrapolation and rest-split subtraction are unasserted.
  • Floor thresholds (3-row, 2-row) lack inclusive-boundary cases.
  • Half-open boundary single-counting and large-body (maxBodyChars) re-tokenization cost are unverified end-to-end.

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

Comment on lines +330 to +334
const changed = new Map<string, string[]>();
for (const [key, b] of baseline) {
const now = miner.drain.getCluster(Number(key))?.getTemplate();
if (b.rows >= 3 && now !== undefined && now !== b.tokens.join(' '))
changed.set(key, b.tokens);

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.

A message that disappears from a merged baseline pattern isn't reported

Variant detection only works in one direction. It finds current rows that don't fit the baseline template. There's no check for the opposite case: a value that varied in the baseline and is gone now. When the baseline cluster was already generalized and the current window has only one of its values, the cluster's share stays the same, so nothing is reported.

Repro, using the helpers in emergingSignalsOrder.test.ts:

it('reports a baseline message that is gone now', async () => {
  const out = await run(
    [
      ...repeat('payment status: ok', 500),
      ...repeat('payment status: failed', 500),
    ],
    repeat('payment status: ok', 1000),
  );
  expect(out.disappeared).toContainEqual(
    expect.objectContaining({ pattern: 'payment status: failed' }),
  );
});
  • On this branch: emerging and disappeared are both empty. payment status: failed went from 50% of the window to 0, and nothing shows it.
  • On main: the windows are mined separately, so you get new "payment status: ok" and gone "payment status: <*>". The labels are wrong, but the change is visible.

The mirror case is reported: if the baseline has only ok and the current window adds failed, you get new_variant. So the same change is visible in one direction and not the other.

This is the "token varies in the baseline, constant now" case that the PR deliberately stops reporting as new + gone. Usually that's noise. Here it hides a message that stopped (errors, heartbeats, a job that no longer runs).

Two possible fixes:

  1. Do the check in both directions. After mining the current window, find baseline rows in clusters the current window touched whose tokens don't fit the cluster's current-only template. Report them in disappeared with something like status: "gone_variant". To get a current-only template, copy the tokens when a current row first joins a baseline cluster and generalize that copy only with current rows.
  2. If that's out of scope, state the limit in usage (vanished variants inside a pattern the baseline already generalized aren't reported) and add the test above as a known gap.

I'd lean toward 1, since the other direction is what makes new_variant useful.

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.

Thanks, went with option 1 in ca4688b.

For each pattern with at least 3 current rows, a template is now built from the current rows alone. Baseline rows that don't fit it are reported in disappeared with status: "gone_variant": pattern is the template of the stopped rows, currentPattern the template of the rows that go on, and variantShare their share of the baseline. The floors match new_variant: 3 sampled rows in the cluster in each window, and at least 2 stopped rows.

One extra guard: some baseline rows must fit the current template. Without it, a rotating identifier (baseline job alpha and job beta, now only job gamma) would report alpha and beta as gone. That case still reports nothing, as the existing test expects.

Your repro is in the tests (also checking status and currentPattern), plus one for the 3-row floor. On your example the output is now a single gone_variant for payment status: failed (baseline share 0.5); payment status: ok going from 0.5 to 1.0 stays under the default 3× ratio.

Still not covered: a token that varies in both windows with different values (ok/failed, then ok/timeout). Both templates are already generalized, so neither direction sees it.

…t goes on

When the baseline already generalized a token and the current window
has only one of its values, the cluster's share stays the same and the
stopped message was not reported. Build a template from the current
rows alone and report baseline rows that don't fit it as gone_variant,
the mirror of new_variant.
return;
const v = variants.get(key);
if (v) v.rows++;
else variants.set(key, { rows: 1, sample: raw });

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 — Several new messages merged into one baseline cluster come back as a single new_variant, and its pattern is the merged template rather than the new message

Take a baseline of user login failed: invalid password and a current window with both user login failed: account locked and user login failed: token revoked. Drain puts all three into one cluster. variants keeps one {rows, sample} per cluster, so the output has one new_variant. Its sample is the first new line only, and its pattern is a.pattern, which is the whole merged template user login failed: <*> <*>. The second new message never appears, and that hidden-by-merge case is the one this PR is meant to fix. Fix: build a template from the non-fitting rows (createTemplate, as the gone-variant path does with g.tokens) and use it as the entry's pattern. Better still, group non-fitting rows into one sub-template per distinct shape and emit an entry for each.

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.

Still one entry per cluster, as in round 2 (#3753 (comment)): keying by message would give an entry per value of any unmasked token. Since 0afa065 the entry's pattern is the template of the new lines only, not the whole merged cluster, so a single new message reads as itself.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

t.tokens = miner.drain.createTemplate(tokens, t.tokens);
t.rows++;
}
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Outliers suppress gone variant detection

Medium Severity

curTemplates merges every current row in the cluster, so one differing token becomes <*>. Baseline messages that stopped in that field then match the wildcard and never count as gone_variant, even when that outlier is below the 2-row floor treated as noise for new_variant.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ca4688b. Configure here.

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, and the other direction works the same way: new_variant compares against the cluster's baseline template, which every baseline row generalizes, so one baseline outlier hides a new variant just as one current outlier hides a gone variant. Ignoring rare values would change both directions and Drain's own templates, so I'm leaving it out of this PR.

A cluster can have a new message and a stopped one at the same time
(baseline status ok/failed code 1, now status ok code 1/2). Report both,
and name a new_variant by the template of its new lines, like a
gone_variant is named by its stopped lines.
@bcanvural

Copy link
Copy Markdown
Contributor Author

On the deep review of ca4688b:

  • New and gone variant in one cluster: fixed in 0afa065 (see the Bugbot thread, feat(mcp): emerging_signals compares both windows in one Drain tree and reports new variants #3753 (comment)). The example in the finding (ok/failed, then ok/pending) is a different case: the token varies in both windows, which neither direction reports, as noted in my reply to Brandon.
  • pattern for the variant statuses: fixed in 0afa065. new_variant now uses the template of its new lines, as gone_variant uses the stopped lines, and usage says so for both.
  • Re-tokenizing: tokenizing is cheaper than mining, which also tokenizes every row and then searches the tree. Reusing the mined tokens means changing minePatterns in common-utils, which I'd rather keep out of this PR.
  • Half-open window test: that code is from an earlier round and is unchanged here, so I'm leaving it.

@brandon-pereira this is past the two bot rounds, so from here I'll only fix P0/P1 bot findings and leave the rest to you.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 0afa065. Configure here.

curCount: rest.curCount,
baseCount: Math.max(rest.baseCount - goneCount, 0),
sample: gone.fitSample,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Rest pattern too broad with both variants

Medium Severity

When a cluster reports both new_variant and gone_variant, rest shares count only the continuing message (current rows that fit the baseline template vs baseline rows that fit the current template), but rest.pattern stays the pre-change baseline template. That template still has wildcards from the stopped message, so a surge or drop of the continuing line is attributed to a broader pattern than the shares describe.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 0afa065. Configure here.

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: when both variants are reported, the rest keeps the old template as its label, which still has a wildcard for the stopped value. Its shares are right; only the label is broader. Leaving it, as noted in my comment above.

kodiakhq Bot pushed a commit that referenced this pull request Nov 27, 2026
#3822)

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

- **Rows and bytes read for PromQL on ClickHouse's Prometheus API.** The handler sends `X-ClickHouse-Summary` with `read_rows: 0`, also on ClickHouse master. It never wires query progress to the response, which `HTTPHandler` does. `system.query_log` has the real numbers under our query id, but only after the log flush. Reported as ClickHouse/ClickHouse#134380.
- **A per-call total for every tool** (`describe_source`, `event_patterns`, `emerging_signals`). This needs counting inside the ClickHouse client. I'd do it in a follow-up, after #3753 (which changes the pattern tools) lands.

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

- Part of #3649
- ClickHouse/ClickHouse#134380 (Prometheus query API reports no read counts)


---

> [!NOTE]
> **Low Risk**
> Additive MCP response fields and documentation; behavior of queries is unchanged aside from timing measurement and statistics passthrough.
> 
> **Overview**
> MCP query tools now expose **query cost metadata** so agents can compare expensive vs cheap dashboard tiles and PromQL calls.
> 
> **`clickstack_query_tiles`** adds per-tile `elapsedMs` (wall time from when the query starts, excluding queue wait; omitted if the tile never ran). Successful **builder and SQL** tiles also surface ClickHouse `rowsRead` and `bytesRead` by parsing `statistics` from the tile payload via a new Zod-backed `summarizeRows`. Failed tiles still report `elapsedMs` when the query started.
> 
> **PromQL** paths (`clickstack_promql`, `clickstack_query_tile`, and PromQL tiles in batch query) attach `elapsedMs` on the result object in `runConfigTile`; no read counts because the Prometheus API does not provide them. Tool descriptions and **MCP.md** document the new fields.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 39345ab. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>

@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.

Please add emerging[].baselinePattern and disappeared[].currentPattern (maxChars: 2000) to EMERGING_SIGNALS_REDUCTIONS. They are uncapped, and maxBodyChars allows bodies up to 1M characters. Otherwise LGTM.

…responses

Both carry a Drain template, which can be as long as a body (maxBodyChars
allows up to 1M characters). Shorten them to 2000 characters like the
pattern fields.
@bcanvural

Copy link
Copy Markdown
Contributor Author

Done in cda5e50: both fields are in EMERGING_SIGNALS_REDUCTIONS with maxChars: 2000, with a test in trimToolResponse.test.ts. Thanks for the review.

emerging_signals no longer imports it, so knip reports the export as unused.
@kodiakhq
kodiakhq Bot merged commit a1a5eac into ClickHouse:main Nov 27, 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