Repository navigation
feat(mcp): emerging_signals compares both windows in one Drain tree and reports new variants - #3753
Conversation
…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 detectedLatest commit: 155fd01 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. |
…-one-tree # Conflicts: # packages/api/src/mcp/tools/query/emergingSignals.ts # packages/api/src/mcp/tools/query/runEventPatterns.ts
|
No description provided. |
PR Review
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
🔵 3 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. |
|
No description provided. |
1 similar comment
|
No description provided. |
| baseCount: a.baseCount, | ||
| sample: b?.sample ?? baselinePattern, | ||
| }; | ||
| if (classifyShift(rest, ratio, newPatternShareFloor) === 'disappeared') |
There was a problem hiding this comment.
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:
emergingholds onlynew_variant(payment failed: <*> <*>) at share 0.002. The 0.01 → 0.5 jump ofcard declineddoesn't appear anywhere. - Without the 2
gateway timeoutrows: the same data reportsshifted0.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:
- Classify
restin both directions:This gives a cluster twoconst restVerdict = classifyShift(rest, ratio, newPatternShareFloor); if (restVerdict === 'emerging') emerging.push(rest); else if (restVerdict === 'disappeared') disappeared.push(rest);
emergingentries 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. - 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.
There was a problem hiding this comment.
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 }); |
There was a problem hiding this comment.
🟡 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
There was a problem hiding this comment.
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.
Deep ReviewScope: 8 files vs base ✅ 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 🟡 P2 — recommended
🔵 P3 nitpicks (6)
Pre-existing (not counted toward verdict)
Reviewers (9): correctness, adversarial, testing, maintainability, performance, api-contract, kieran-typescript, previous-comments, project-standards. 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 |
| 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); |
There was a problem hiding this comment.
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:
emerginganddisappearedare both empty.payment status: failedwent from 50% of the window to 0, and nothing shows it. - On
main: the windows are mined separately, so you getnew "payment status: ok"andgone "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:
- 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
disappearedwith something likestatus: "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. - 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.
There was a problem hiding this comment.
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 }); |
There was a problem hiding this comment.
🟡 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
There was a problem hiding this comment.
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.
| t.tokens = miner.drain.createTemplate(tokens, t.tokens); | ||
| t.rows++; | ||
| } | ||
| }); |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit ca4688b. Configure here.
There was a problem hiding this comment.
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.
|
On the deep review of ca4688b:
@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. |
There was a problem hiding this comment.
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).
Reviewed by Cursor Bugbot for commit 0afa065. Configure here.
| curCount: rest.curCount, | ||
| baseCount: Math.max(rest.baseCount - goneCount, 0), | ||
| sample: gone.fitSample, | ||
| }; |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 0afa065. Configure here.
There was a problem hiding this comment.
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.
#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
left a comment
There was a problem hiding this comment.
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.
|
Done in cda5e50: both fields are in |
emerging_signals no longer imports it, so knip reports the export as unused.


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_signalsmines 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:
TemplateMiner, baseline first, and compares them by cluster id. The order is fixed, so the result doesn't depend on which query finishes first.user login failed: account lockedintouser 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 inemergingwithstatus: "new_variant",baselinePattern,variantShare, and the new line as its sample. Baseline clusters with fewer than 3 sampled rows are skipped.dateRangeEndInclusive: false), so a row at the boundary is counted once.Supporting changes:
minePatternstakes an optionalminerand returnsrowClusterIds(the cluster of each input row);TemplateMiner.tokenizereturns the masked tokens Drain compares.mineWindowPatternsis split intofetchWindowSample+mineWindowSampleand kept as a wrapper, soevent_patternsis 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:packages/api/src/mcp/__tests__/emergingSignalsOrder.test.tsfrom this PR.npx jest src/mcp/__tests__/emergingSignalsOrder.test.tsinpackages/api: it fails, becausemainhas nofetchWindowSample/mineWindowSampleand reports nonew_variant.On this branch:
emergingSignalsOrder.test.tspasses (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 indisappeared.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
emerging_signalsreports dated log lines as both "new" and "gone": Drain keeps the literal date, and each window is mined separately #3544Note
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_signalsno 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 sharedTemplateMinerin 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, withbaselinePattern/variantShare) andgone_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:
minePatternsaccepts an optional sharedminerand returnsrowClusterIds;TemplateMiner.tokenizeexposes masked tokens; window mining is split intofetchWindowSample+mineWindowSample(existing single-window flow still uses the wrapper). Response trimming now coversbaselinePatternandcurrentPattern, 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.