From 8abdf7ae13ddf37a24478adf7686d8ad7274b1a2 Mon Sep 17 00:00:00 2001 From: Mike Shi Date: Sun, 22 Nov 2026 19:14:53 +0000 Subject: [PATCH 1/2] fix(patterns): split MCP and CLI bodies on punctuation, as the web app does The MCP tools and the CLI mined patterns with whitespace-only splitting, so compact JSON lines became a few huge tokens and nearly every line got its own pattern. The web app's drain3 miner splits on ASCII punctuation. Use the same delimiters in a shared miner config. Date masks stay. With punctuation splitting, a mask is kept as a token of its own, and the drill-down predicate matches the raw date it replaced (up to three runs, separator beside it optional). Also fix the Drain port's tokenizer: it trimmed before turning delimiters into spaces, so a line starting or ending with one got an empty token, which drain3 never produces. --- .changeset/patterns-split-on-punctuation.md | 15 +++ .../query/__tests__/patternDrilldown.test.ts | 10 +- packages/api/src/mcp/tools/query/denoise.ts | 3 +- .../src/mcp/tools/query/patternDrilldown.ts | 6 +- .../src/mcp/tools/query/runEventPatterns.ts | 10 +- packages/cli/src/cli.tsx | 4 +- .../src/__tests__/drain-masking.test.ts | 6 +- .../common-utils/src/__tests__/drain.test.ts | 49 +++++++++- .../src/__tests__/mine-patterns.test.ts | 22 +++++ .../src/__tests__/noisy-matcher.test.ts | 4 +- .../src/__tests__/pattern-predicate.test.ts | 29 ++++-- packages/common-utils/src/drain/drain.ts | 50 ++++++++-- packages/common-utils/src/drain/index.ts | 5 +- .../common-utils/src/drain/mine-patterns.ts | 32 ++++++- .../common-utils/src/drain/noisy-matcher.ts | 30 +++--- .../src/drain/pattern-predicate.ts | 93 ++++++++++++++++--- .../common-utils/src/drain/template-miner.ts | 2 + 17 files changed, 302 insertions(+), 68 deletions(-) create mode 100644 .changeset/patterns-split-on-punctuation.md diff --git a/.changeset/patterns-split-on-punctuation.md b/.changeset/patterns-split-on-punctuation.md new file mode 100644 index 0000000000..ccb6ca41a1 --- /dev/null +++ b/.changeset/patterns-split-on-punctuation.md @@ -0,0 +1,15 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/api': patch +'@hyperdx/cli': patch +--- + +fix: MCP and CLI event patterns split bodies on punctuation, as the web app does + +The MCP tools (`event_patterns`, `emerging_signals`, search denoise) and the CLI +split bodies on ASCII punctuation as well as whitespace, the same as the web +app's drain3 miner. JSON and other compact bodies now mine into readable +templates instead of one cluster per line. Date masks stay: a mask is a token of +its own, and drill-down predicates match the raw date it replaced. The Drain +port also no longer makes empty tokens for lines that start or end with a +delimiter, matching drain3. diff --git a/packages/api/src/mcp/tools/query/__tests__/patternDrilldown.test.ts b/packages/api/src/mcp/tools/query/__tests__/patternDrilldown.test.ts index 490264e45f..c7135c6fdc 100644 --- a/packages/api/src/mcp/tools/query/__tests__/patternDrilldown.test.ts +++ b/packages/api/src/mcp/tools/query/__tests__/patternDrilldown.test.ts @@ -2,19 +2,21 @@ import { buildPatternPredicate, MAX_PREDICATE_TEMPLATE_LENGTH, minePatterns, + PATTERN_REGEX_OPTIONS, templateToRegex, } from '@hyperdx/common-utils/dist/drain'; import { andSql } from '@/mcp/tools/query/patternDrilldown'; // RE2 spells code points \x{HHHH} and categories \pZ; JS (with the u flag) -// spells them \u{HHHH} and \p{Z}. ClickHouse behaviour is covered by -// integration tests. +// spells them \u{HHHH} and \p{Z}, and has no POSIX classes. ClickHouse +// behaviour is covered by integration tests. function toJsRegex(re2: string): RegExp { return RegExp( re2 .replace(/\\x\{([0-9A-Fa-f]+)\}/g, '\\u{$1}') - .replace(/(? { expect(patterns.length).toBeGreaterThan(1); for (const p of patterns) { - const re = toJsRegex(templateToRegex(p.pattern)); + const re = toJsRegex(templateToRegex(p.pattern, PATTERN_REGEX_OPTIONS)); const members = p.samples.map(s => s.body); expect(members).toHaveLength(p.sampleCount); for (const m of members) expect(re.test(m)).toBe(true); diff --git a/packages/api/src/mcp/tools/query/denoise.ts b/packages/api/src/mcp/tools/query/denoise.ts index 2465ef766f..aea58c0a72 100644 --- a/packages/api/src/mcp/tools/query/denoise.ts +++ b/packages/api/src/mcp/tools/query/denoise.ts @@ -4,6 +4,7 @@ import { buildNoisyBodyMatcher, DENOISE_SAMPLE_SIZE, minePatterns, + PATTERN_EXTRA_DELIMITERS, selectNoisyPatterns, } from '@hyperdx/common-utils/dist/drain'; import type { ChartConfigWithDateRange } from '@hyperdx/common-utils/dist/types'; @@ -229,7 +230,7 @@ export async function denoiseSearchResults( const isNoisy = buildNoisyBodyMatcher( patterns.map(p => p.pattern), noisyTemplates, - { masked: true }, + { extraDelimiters: PATTERN_EXTRA_DELIMITERS, masked: true }, ); const filteredRows = rows.filter(row => { const bodyValue = row[bodyColumnKey]; diff --git a/packages/api/src/mcp/tools/query/patternDrilldown.ts b/packages/api/src/mcp/tools/query/patternDrilldown.ts index c78ada719b..f7c1e147b6 100644 --- a/packages/api/src/mcp/tools/query/patternDrilldown.ts +++ b/packages/api/src/mcp/tools/query/patternDrilldown.ts @@ -8,9 +8,9 @@ import type { import { substituteVariables } from '@hyperdx/common-utils/dist/variables'; export const PATTERN_MATCH_SEMANTICS = - 'whereSnippet matches values with the same whitespace-separated token count as the ' + - 'template, the same literal tokens (case-sensitive) in the same positions, and exactly ' + - `one non-whitespace token at each <*>, and one or more non-whitespace characters at each ${DATE_TOKEN} ` + + 'Tokens are separated by whitespace and ASCII punctuation. whereSnippet matches values ' + + 'with the same token count as the template, the same literal tokens (case-sensitive) in ' + + `the same positions, exactly one token at each <*>, and a date of up to three tokens at each ${DATE_TOKEN} ` + `(also inside a token, e.g. backup_${DATE_TOKEN}.tar). ` + 'Every sampled member of the cluster matches. ' + 'It can also match unsampled events whose shape fits, including ones Drain would have ' + diff --git a/packages/api/src/mcp/tools/query/runEventPatterns.ts b/packages/api/src/mcp/tools/query/runEventPatterns.ts index a6d6fbb507..6839e4b9ab 100644 --- a/packages/api/src/mcp/tools/query/runEventPatterns.ts +++ b/packages/api/src/mcp/tools/query/runEventPatterns.ts @@ -8,9 +8,9 @@ import { } from '@hyperdx/common-utils/dist/core/utils'; import { buildPatternPredicate, - DATE_MASK, MAX_PREDICATE_TEMPLATE_LENGTH, minePatterns, + PATTERN_REGEX_OPTIONS, } from '@hyperdx/common-utils/dist/drain'; import type { ChartConfigWithDateRange, @@ -471,9 +471,11 @@ export async function runEventPatterns( const slicedPatterns = rawPatterns.slice(0, topN); const patterns = slicedPatterns.map((p, i) => { - const predicate = buildPatternPredicate(bodyColumn, p.pattern, { - masks: [DATE_MASK], - }); + const predicate = buildPatternPredicate( + bodyColumn, + p.pattern, + PATTERN_REGEX_OPTIONS, + ); const whereSnippet = predicate == null ? '' : andSql(drilldown?.where, predicate); diff --git a/packages/cli/src/cli.tsx b/packages/cli/src/cli.tsx index b2060cd467..9db269cddd 100644 --- a/packages/cli/src/cli.tsx +++ b/packages/cli/src/cli.tsx @@ -14,8 +14,8 @@ import Spinner from 'ink-spinner'; import { Command } from 'commander'; import chalk from 'chalk'; import { + createPatternMinerConfig, TemplateMiner, - TemplateMinerConfig, } from '@hyperdx/common-utils/dist/drain'; import { DashboardWithoutIdSchema } from '@hyperdx/common-utils/dist/types'; @@ -2373,7 +2373,7 @@ Examples: .replace(/\s{2,}/g, ' ') .trim(); - const miner = new TemplateMiner(new TemplateMinerConfig()); + const miner = new TemplateMiner(createPatternMinerConfig()); const groups = new Map(); for (const row of rows) { const raw = opts.bodyColumn diff --git a/packages/common-utils/src/__tests__/drain-masking.test.ts b/packages/common-utils/src/__tests__/drain-masking.test.ts index f79b05fc9d..e9a51b3903 100644 --- a/packages/common-utils/src/__tests__/drain-masking.test.ts +++ b/packages/common-utils/src/__tests__/drain-masking.test.ts @@ -216,15 +216,15 @@ describe('patterns with the default masks', () => { it('keeps klog severities apart, which unmasked mining merges', () => { // Unmasked, I1104 and E1104 both route as numbers in Drain's prefix tree; - // masked, I and E route by their severity letter. + // masked, the severity letter is a token of its own and routes as a word. const lines = dayOfLogs(4, 'Wed').filter(line => /^[IE]\d{4} /.test(line)); expect( mine(lines) .map(p => p.pattern) .sort(), ).toEqual([ - 'E <*> 1 main.go:42] sync failed', - 'I <*> 1 main.go:42] sync done', + 'E <*> <*> <*> 345678 1 main go 42 sync failed', + 'I <*> <*> <*> 345678 1 main go 42 sync done', ]); }); diff --git a/packages/common-utils/src/__tests__/drain.test.ts b/packages/common-utils/src/__tests__/drain.test.ts index d348beb302..44d06b4483 100644 --- a/packages/common-utils/src/__tests__/drain.test.ts +++ b/packages/common-utils/src/__tests__/drain.test.ts @@ -1,5 +1,6 @@ import { TemplateMinerConfig } from '@/drain/config'; -import { Drain } from '@/drain/drain'; +import { Drain, tokenizeContent } from '@/drain/drain'; +import { ASCII_PUNCTUATION } from '@/drain/pattern-predicate'; import { TemplateMiner } from '@/drain/template-miner'; describe('Drain', () => { @@ -215,6 +216,52 @@ A format 3` expect(() => model.createTemplate(seq1, ['aa'])).toThrow(); }); + + it('drops the empty tokens left by delimiters at the ends of a line', () => { + const model = new Drain(4, 0.4, 100, null, ASCII_PUNCTUATION.split('')); + expect(model.getContentAsTokens('{"a":"b"}')).toEqual(['a', 'b']); + expect(model.getContentAsTokens(' [x] ')).toEqual(['x']); + expect(model.getContentAsTokens('{}')).toEqual([]); + }); + + it('makes each kept mask a token of its own when delimiters split the line', () => { + const delimiters = ASCII_PUNCTUATION.split(''); + expect( + tokenizeContent('[T06:12:12Z] ok', delimiters, ['']), + ).toEqual(['', 'T06', '12', '12Z', 'ok']); + expect(tokenizeContent('T06 ok', [], [''])).toEqual([ + 'T06', + 'ok', + ]); + }); + + it('clusters punctuation-delimited lines as drain3 does', () => { + const config = new TemplateMinerConfig(); + config.drainExtraDelimiters = ASCII_PUNCTUATION.split(''); + config.maskingInstructions = []; + const miner = new TemplateMiner(config); + const lines = [ + '{"level":"info","msg":"user 1 logged in"}', + '{"level":"info","msg":"user 2 logged in"}', + '{"level":"error","msg":"disk full"}', + '[worker-3] job 42 done.', + '[worker-7] job 43 done.', + '"quoted" line here', + ]; + const ids = lines.map(l => miner.addLogMessage(l).clusterId); + + // Expected values generated with drain3 0.9.11, drain_extra_delimiters = + // list(string.punctuation). + expect(ids).toEqual([1, 1, 2, 3, 3, 4]); + expect( + [1, 2, 3, 4].map(id => miner.drain.getCluster(id)?.getTemplate()), + ).toEqual([ + 'level info msg user <*> logged in', + 'level error msg disk full', + 'worker <*> job <*> done', + 'quoted line here', + ]); + }); }); describe('TemplateMiner', () => { diff --git a/packages/common-utils/src/__tests__/mine-patterns.test.ts b/packages/common-utils/src/__tests__/mine-patterns.test.ts index 1aa39020aa..47c3de0919 100644 --- a/packages/common-utils/src/__tests__/mine-patterns.test.ts +++ b/packages/common-utils/src/__tests__/mine-patterns.test.ts @@ -451,6 +451,28 @@ describe('minePatterns', () => { }); }); +describe('minePatterns tokenization', () => { + it('splits JSON bodies on punctuation, as the web app miner does', () => { + const rows = [ + '{"level":"info","msg":"user 1 logged in"}', + '{"level":"info","msg":"user 2 logged in"}', + '{"ts":"2026-11-04T06:12:12Z","msg":"done"}', + '{"ts":"2026-11-04T07:00:01Z","msg":"done"}', + ].map(body => makeRow(body)); + const { patterns } = minePatterns(rows, { + totalCount: rows.length, + startDate: baseDate, + endDate, + trendBuckets: 0, + ...defaultCallbacks, + }); + expect(patterns.map(p => p.pattern).sort()).toEqual([ + 'level info msg user <*> logged in', + 'ts <*> <*> <*> msg done', + ]); + }); +}); + describe('minePatterns template fidelity', () => { // Deterministic PRNG so the fuzz input is stable across runs. function lcg(seed: number) { diff --git a/packages/common-utils/src/__tests__/noisy-matcher.test.ts b/packages/common-utils/src/__tests__/noisy-matcher.test.ts index 3091e57d78..88137ac5b4 100644 --- a/packages/common-utils/src/__tests__/noisy-matcher.test.ts +++ b/packages/common-utils/src/__tests__/noisy-matcher.test.ts @@ -1,4 +1,4 @@ -import { minePatterns } from '@/drain/mine-patterns'; +import { minePatterns, PATTERN_EXTRA_DELIMITERS } from '@/drain/mine-patterns'; import { buildNoisyBodyMatcher, selectNoisyPatterns, @@ -124,7 +124,7 @@ describe('buildNoisyBodyMatcher', () => { const isNoisy = buildNoisyBodyMatcher( patterns.map(p => p.pattern), new Set([heartbeat!.pattern]), - { masked: true }, + { extraDelimiters: PATTERN_EXTRA_DELIMITERS, masked: true }, ); for (const body of noisy) expect(isNoisy(body)).toBe(true); expect(isNoisy(rare)).toBe(false); diff --git a/packages/common-utils/src/__tests__/pattern-predicate.test.ts b/packages/common-utils/src/__tests__/pattern-predicate.test.ts index 53172d1704..660f320caa 100644 --- a/packages/common-utils/src/__tests__/pattern-predicate.test.ts +++ b/packages/common-utils/src/__tests__/pattern-predicate.test.ts @@ -1,5 +1,5 @@ import { DATE_MASK, TemplateMinerConfig } from '@/drain/config'; -import { minePatterns } from '@/drain/mine-patterns'; +import { minePatterns, PATTERN_REGEX_OPTIONS } from '@/drain/mine-patterns'; import { buildCompactPatternPredicate, buildPatternPredicate, @@ -428,6 +428,23 @@ describe('templateToRegex with masks', () => { expect(matches(' <*> INFO x', '2026-11-04 INFO x')).toBe(false); }); + it('with delimiters, a mask matches a date of up to three runs', () => { + const m = (template: string, value: string) => + matches(template, value, PATTERN_REGEX_OPTIONS); + expect(m(' T06 started', '2026-11-04T06 started')).toBe(true); + expect(m(' <*> started', '2026-11-04T06 started')).toBe(true); + expect(m('access 12', 'access [04/Nov/2026:12]')).toBe(true); + expect(m(' started', '2026-11-04-01 started')).toBe(false); + expect(m(' started', 'boot started')).toBe(true); + expect( + buildCompactPatternPredicate( + 'Body', + ' T06 x', + PATTERN_REGEX_OPTIONS, + ), + ).not.toBeNull(); + }); + it('keeps literal without the option', () => { const t = 'wrote backup_.tar'; expect(matches(t, 'wrote backup_.tar', {})).toBe(true); @@ -449,7 +466,7 @@ describe('templateToRegex with masks', () => { ]); expect(patterns).toHaveLength(4); for (const p of patterns) { - const re = toJsRegex(templateToRegex(p.pattern, withDates)); + const re = toJsRegex(templateToRegex(p.pattern, PATTERN_REGEX_OPTIONS)); for (const s of p.samples) expect(re.test(s.body)).toBe(true); for (const o of patterns.filter(o => o !== p).flatMap(o => o.samples)) { expect(re.test(o.body)).toBe(false); @@ -464,14 +481,14 @@ describe('templateToRegex with masks', () => { 'Started job at shutdown', 'Started job at 2026-11-04T06:12:13Z', ]); - // The space-separated timestamp is two words, so it can't share a cluster - // with the one-word lines; the one-word timestamp can, as <*>. + // Punctuation splits the times into several tokens, so the dated lines + // share a cluster with each other, not with the one-word lines. expect(patterns.map(p => p.pattern).sort()).toEqual([ 'Started job at <*>', - 'Started job at 06:12:12', + 'Started job at <*> 12 <*>', ]); for (const p of patterns) { - const re = toJsRegex(templateToRegex(p.pattern, withDates)); + const re = toJsRegex(templateToRegex(p.pattern, PATTERN_REGEX_OPTIONS)); for (const sample of p.samples) expect(re.test(sample.body)).toBe(true); } }); diff --git a/packages/common-utils/src/drain/drain.ts b/packages/common-utils/src/drain/drain.ts index 661cf89e15..e07c271a8c 100644 --- a/packages/common-utils/src/drain/drain.ts +++ b/packages/common-utils/src/drain/drain.ts @@ -2,6 +2,46 @@ import { LogCluster } from './log-cluster'; import { LruCache } from './lru-cache'; import { Node } from './node'; +/** + * Split content into Drain tokens: each extra delimiter becomes a space, then + * the content splits on whitespace. With extra delimiters, each `keepTokens` + * string (a mask such as ``) is a token of its own, never split by the + * delimiters nor joined to the text around it: `T06` gives `` and + * `T06`, so a date stays `` when the time beside it varies. drain3 has + * no such option; with none given this splits exactly as drain3 does. + */ +export function tokenizeContent( + content: string, + extraDelimiters: string[], + keepTokens: string[] = [], +): string[] { + const replaceDelimiters = (part: string) => { + let c = part; + for (const delimiter of extraDelimiters) { + c = c.split(delimiter).join(' '); + } + return c; + }; + const replaceOutside = (part: string, keep: string[]): string => { + if (keep.length === 0) return replaceDelimiters(part); + const [token, ...rest] = keep; + return part + .split(token) + .map(p => replaceOutside(p, rest)) + .join(` ${token} `); + }; + let c = + extraDelimiters.length === 0 + ? content + : replaceOutside(content, keepTokens); + // Trim after the delimiters become spaces: a line that starts or ends + // with one would otherwise get an empty token, which drain3 (Python's + // str.split()) never produces. + c = c.trim(); + if (c.length === 0) return []; + return c.split(/\s+/); +} + export class Drain { logClusterDepth: number; private maxNodeDepth: number; @@ -12,6 +52,7 @@ export class Drain { maxClusters: number | null; paramStr: string; parametrizeNumericTokens: boolean; + keepTokens: string[]; private unlimitedStore: Map | null; private limitedStore: LruCache | null; @@ -25,6 +66,7 @@ export class Drain { extraDelimiters: string[] = [], paramStr: string = '<*>', parametrizeNumericTokens: boolean = true, + keepTokens: string[] = [], ) { if (depth < 3) { throw new Error('depth argument must be at least 3'); @@ -39,6 +81,7 @@ export class Drain { this.maxClusters = maxClusters; this.paramStr = paramStr; this.parametrizeNumericTokens = parametrizeNumericTokens; + this.keepTokens = keepTokens; this.clustersCounter = 0; if (maxClusters !== null) { @@ -102,12 +145,7 @@ export class Drain { } getContentAsTokens(content: string): string[] { - let c = content.trim(); - for (const delimiter of this.extraDelimiters) { - c = c.split(delimiter).join(' '); - } - if (c.length === 0) return []; - return c.split(/\s+/); + return tokenizeContent(content, this.extraDelimiters, this.keepTokens); } getSeqDistance( diff --git a/packages/common-utils/src/drain/index.ts b/packages/common-utils/src/drain/index.ts index f9a38642cf..1f6f7ef62e 100644 --- a/packages/common-utils/src/drain/index.ts +++ b/packages/common-utils/src/drain/index.ts @@ -1,6 +1,6 @@ export type { MaskingInstructionConfig } from './config'; export { DATE_MASK, DATE_TOKEN, TemplateMinerConfig } from './config'; -export { Drain } from './drain'; +export { Drain, tokenizeContent } from './drain'; export { LogCluster } from './log-cluster'; export { LruCache } from './lru-cache'; export { LogMasker, MaskingInstruction } from './masking'; @@ -12,10 +12,13 @@ export type { } from './mine-patterns'; export { createPatternMasker, + createPatternMinerConfig, DENOISE_NOISE_THRESHOLD, DENOISE_SAMPLE_SIZE, flattenBody, minePatterns, + PATTERN_EXTRA_DELIMITERS, + PATTERN_REGEX_OPTIONS, } from './mine-patterns'; export { Node } from './node'; export { buildNoisyBodyMatcher, selectNoisyPatterns } from './noisy-matcher'; diff --git a/packages/common-utils/src/drain/mine-patterns.ts b/packages/common-utils/src/drain/mine-patterns.ts index 505cf81c1f..b7b4cb490b 100644 --- a/packages/common-utils/src/drain/mine-patterns.ts +++ b/packages/common-utils/src/drain/mine-patterns.ts @@ -5,10 +5,35 @@ import { toStartOfInterval, } from '@/core/utils'; -import { TemplateMinerConfig } from './config'; +import { DATE_MASK, TemplateMinerConfig } from './config'; import { LogMasker } from './masking'; +import { + ASCII_PUNCTUATION, + type PatternRegexOptions, +} from './pattern-predicate'; import { TemplateMiner } from './template-miner'; +// ─── Miner config ──────────────────────────────────────────────────────────── + +/** + * The extra delimiters of the pattern miner: ASCII punctuation, the same as + * the web app's drain3 miner, so both split a body into the same tokens. + */ +export const PATTERN_EXTRA_DELIMITERS = ASCII_PUNCTUATION.split(''); + +/** The miner config of minePatterns: punctuation delimiters and date masks. */ +export function createPatternMinerConfig(): TemplateMinerConfig { + const config = new TemplateMinerConfig(); + config.drainExtraDelimiters = [...PATTERN_EXTRA_DELIMITERS]; + return config; +} + +/** Regex options for templates mined with createPatternMinerConfig. */ +export const PATTERN_REGEX_OPTIONS: PatternRegexOptions = { + extraDelimiters: PATTERN_EXTRA_DELIMITERS, + masks: [DATE_MASK], +}; + // ─── Denoise constants ─────────────────────────────────────────────────────── // Shared between the web app and MCP server denoise paths. @@ -27,7 +52,7 @@ export const DENOISE_NOISE_THRESHOLD = 0.05; * compared token by token with a mined template. */ export function createPatternMasker(): LogMasker { - return LogMasker.fromConfig(new TemplateMinerConfig()); + return LogMasker.fromConfig(createPatternMinerConfig()); } // ─── Body normalization ────────────────────────────────────────────────────── @@ -148,8 +173,7 @@ export function minePatterns>( } // ── Set up Drain miner ── - const drainConfig = new TemplateMinerConfig(); - const miner = new TemplateMiner(drainConfig); + const miner = new TemplateMiner(createPatternMinerConfig()); // ── Process each row through Drain ── const clustered: Array<{ diff --git a/packages/common-utils/src/drain/noisy-matcher.ts b/packages/common-utils/src/drain/noisy-matcher.ts index d96925fb8f..ab37de2c53 100644 --- a/packages/common-utils/src/drain/noisy-matcher.ts +++ b/packages/common-utils/src/drain/noisy-matcher.ts @@ -1,3 +1,4 @@ +import { tokenizeContent } from './drain'; import { createPatternMasker, DENOISE_NOISE_THRESHOLD, @@ -30,9 +31,10 @@ export function selectNoisyPatterns( * member on a different same-length cluster than the one it was counted in. * * `extraDelimiters` must be the ones the miner was configured with, so the - * body splits into the same tokens the templates were built from. Likewise set - * `masked` when the templates come from `minePatterns` (default masks), so the - * body is masked the same way; drain3's default config has no masks. + * body splits into the same tokens the templates were built from + * (`PATTERN_EXTRA_DELIMITERS` for `minePatterns`). Likewise set `masked` when + * the templates come from `minePatterns` (default masks), so the body is + * masked the same way; drain3's default config has no masks. */ export function buildNoisyBodyMatcher( templates: string[], @@ -41,7 +43,7 @@ export function buildNoisyBodyMatcher( ): (body: string) => boolean { const extraDelimiters = options?.extraDelimiters ?? []; const candidates = templates.map(template => { - const tokens = tokenize(template, []); + const tokens = tokenizeContent(template, []); return { tokens, wildcards: tokens.filter(t => t === PATTERN_WILDCARD).length, @@ -49,9 +51,15 @@ export function buildNoisyBodyMatcher( }; }); const masker = options?.masked ? createPatternMasker() : undefined; + const maskTokens = + masker?.maskNames.map(n => masker.maskPrefix + n + masker.maskSuffix) ?? []; return body => { const flat = flattenBody(body); - const tokens = tokenize(masker ? masker.mask(flat) : flat, extraDelimiters); + const tokens = tokenizeContent( + masker ? masker.mask(flat) : flat, + extraDelimiters, + maskTokens, + ); let best: (typeof candidates)[number] | undefined; for (const c of candidates) { const fits = @@ -71,15 +79,3 @@ export function buildNoisyBodyMatcher( return best?.noisy ?? false; }; } - -// Mirrors Drain's tokenizer: delimiters become spaces, then split(/\s+/). -// Templates are already space-joined tokens, and splitting one on a -// delimiter would break up `<*>`. -function tokenize(text: string, extraDelimiters: string[]): string[] { - let c = text.trim(); - for (const delimiter of extraDelimiters) { - c = c.split(delimiter).join(' '); - } - c = c.trim(); - return c === '' ? [] : c.split(/\s+/); -} diff --git a/packages/common-utils/src/drain/pattern-predicate.ts b/packages/common-utils/src/drain/pattern-predicate.ts index 145d77d3b1..d40f62ea10 100644 --- a/packages/common-utils/src/drain/pattern-predicate.ts +++ b/packages/common-utils/src/drain/pattern-predicate.ts @@ -25,8 +25,14 @@ export type PatternRegexOptions = { * The names of the masks the miner applied, e.g. `[DATE_MASK]`. Each * `` in a template then matches one or more characters of a token, * as a whole token or inside one (`backup_.tar`). Without this, it - * is literal text. A whole-token mask matches like `<*>`, so - * parsePatternPredicate reads it back as `<*>`. + * is literal text. Without extra delimiters a whole-token mask matches + * like `<*>`, so parsePatternPredicate reads it back as `<*>`. + * + * With extra delimiters the miner makes each mask a token of its own while + * the delimiters split the raw date (`2026-11-04T06` mines as ` T06`). + * So a mask matches up to three runs joined by one separator, and the + * separator beside it is optional. parsePatternPredicate reads none of + * these back. */ masks?: string[]; }; @@ -85,15 +91,58 @@ function tokensOf(template: string, options?: PatternRegexOptions): string[] { return template.split(split).filter(t => t.length > 0); } -// A template token as a regex: `<*>` and each mask become `wildcard`, the -// rest is literal. -function tokenRegex(word: string, masks: string[], wildcard: string): string { +// A template token as a regex: `<*>` becomes `wildcard`, each mask becomes +// `mask`, the rest is literal. +function tokenRegex( + word: string, + masks: string[], + wildcard: string, + mask: string, +): string { if (word === PATTERN_WILDCARD) return wildcard; if (masks.length === 0) return escapeRe2Literal(word); return word .split(`<${masks[0]}>`) - .map(part => tokenRegex(part, masks.slice(1), wildcard)) - .join(wildcard); + .map(part => tokenRegex(part, masks.slice(1), wildcard, mask)) + .join(mask); +} + +// A masked date spans at most three runs between delimiters: 2026-11-04, +// 04/Nov/2026, 04.11.2026. +const MAX_MASK_RUNS = 3; + +// Joins token regexes with `separator`, or with `optionalSeparator` beside a +// mask token when the miner split masks off with extra delimiters. +function joinTokens( + tokens: string[], + toRegex: (token: string) => string, + separator: string, + optionalSeparator: string, + options?: PatternRegexOptions, +): string { + const maskTokens = new Set( + (options?.extraDelimiters ?? []).length === 0 + ? [] + : (options?.masks ?? []).map(m => `<${m}>`), + ); + return tokens + .map((t, i) => + i === 0 + ? toRegex(t) + : (maskTokens.has(t) || maskTokens.has(tokens[i - 1]) + ? optionalSeparator + : separator) + toRegex(t), + ) + .join(''); +} + +function maskRegex( + run: string, + separator: string, + options?: PatternRegexOptions, +): string { + if ((options?.extraDelimiters ?? []).length === 0) return run; + return `${run}(?:${separator}${run}){0,${MAX_MASK_RUNS - 1}}`; } /** Anchored RE2 regex that a value matches when it fits the Drain template. */ @@ -104,9 +153,14 @@ export function templateToRegex( const separators = separatorClass(options); const separator = `[${separators}]`; const nonSeparators = `[^${separators}]+`; - const body = tokensOf(template, options) - .map(t => tokenRegex(t, options?.masks ?? [], nonSeparators)) - .join(`${separator}+`); + const mask = maskRegex(nonSeparators, separator, options); + const body = joinTokens( + tokensOf(template, options), + t => tokenRegex(t, options?.masks ?? [], nonSeparators, mask), + `${separator}+`, + `${separator}*`, + options, + ); return `^${separator}*${body}${separator}*$`; } @@ -131,9 +185,14 @@ const COMPACT_WILDCARD = '[^ ]+'; // Regex over a value whose separator runs were replaced by single spaces. function compactRegex(template: string, options?: PatternRegexOptions): string { - const body = tokensOf(template, options) - .map(t => tokenRegex(t, options?.masks ?? [], COMPACT_WILDCARD)) - .join(' '); + const mask = maskRegex(COMPACT_WILDCARD, ' ', options); + const body = joinTokens( + tokensOf(template, options), + t => tokenRegex(t, options?.masks ?? [], COMPACT_WILDCARD, mask), + ' ', + ' ?', + options, + ); return `${COMPACT_START}${body}${COMPACT_END}`; } @@ -155,8 +214,14 @@ export function buildCompactPatternPredicate( ): string | null { if (template.length > MAX_PREDICATE_TEMPLATE_LENGTH) return null; const delimiters = options?.extraDelimiters ?? []; + // The miner keeps masks whole, so their brackets don't count. + const masks = (options?.masks ?? []).map(m => `<${m}>`); const splitsToken = tokensOf(template, options).some( - t => t !== PATTERN_WILDCARD && [...t].some(c => delimiters.includes(c)), + t => + t !== PATTERN_WILDCARD && + [...masks.reduce((rest, m) => rest.split(m).join(''), t)].some(c => + delimiters.includes(c), + ), ); if (splitsToken) return null; const separatorRun = `[${separatorClass(options)}]+`; diff --git a/packages/common-utils/src/drain/template-miner.ts b/packages/common-utils/src/drain/template-miner.ts index 76e731dd46..1844452f3b 100644 --- a/packages/common-utils/src/drain/template-miner.ts +++ b/packages/common-utils/src/drain/template-miner.ts @@ -40,6 +40,8 @@ export class TemplateMiner { cfg.drainExtraDelimiters, paramStr, cfg.parametrizeNumericTokens, + // A mask stays one token when the delimiters would split its brackets. + this.masker.maskNames.map(n => cfg.maskPrefix + n + cfg.maskSuffix), ); this.extractionCache = new LruCache(cfg.parameterExtractionCacheCapacity); From bf11c063ab19685d54b4a4a5d4aba0753cdda8e3 Mon Sep 17 00:00:00 2001 From: Mike Shi Date: Sun, 22 Nov 2026 19:26:34 +0000 Subject: [PATCH 2/2] fix(patterns): match only dates at a in drill-down With punctuation delimiters, matched any one to three runs and the separators beside it were optional, so a drill-down matched lines with no date (`ts <*> msg done` matched `tsunami 5 msg done`). A mask now matches up to three date parts: digits, or month and weekday names. The separator beside it is optional only where the masker leaves none: after a klog severity letter (I1104) and before a T time (2026-11-04T06). --- .../src/mcp/tools/query/patternDrilldown.ts | 5 +- .../src/__tests__/pattern-predicate.test.ts | 24 ++- packages/common-utils/src/drain/config.ts | 4 +- .../src/drain/pattern-predicate.ts | 137 ++++++++++++------ 4 files changed, 121 insertions(+), 49 deletions(-) diff --git a/packages/api/src/mcp/tools/query/patternDrilldown.ts b/packages/api/src/mcp/tools/query/patternDrilldown.ts index f7c1e147b6..944764067a 100644 --- a/packages/api/src/mcp/tools/query/patternDrilldown.ts +++ b/packages/api/src/mcp/tools/query/patternDrilldown.ts @@ -10,8 +10,9 @@ import { substituteVariables } from '@hyperdx/common-utils/dist/variables'; export const PATTERN_MATCH_SEMANTICS = 'Tokens are separated by whitespace and ASCII punctuation. whereSnippet matches values ' + 'with the same token count as the template, the same literal tokens (case-sensitive) in ' + - `the same positions, exactly one token at each <*>, and a date of up to three tokens at each ${DATE_TOKEN} ` + - `(also inside a token, e.g. backup_${DATE_TOKEN}.tar). ` + + `the same positions, exactly one token at each <*>, and at each ${DATE_TOKEN} a date of up to ` + + 'three parts (digits, month or weekday names), which may touch a klog severity letter ' + + 'before it (I1104) or a T time after it (2026-11-04T06). ' + 'Every sampled member of the cluster matches. ' + 'It can also match unsampled events whose shape fits, including ones Drain would have ' + 'put in a more specific cluster, so the drill-down is a superset of cluster membership.'; diff --git a/packages/common-utils/src/__tests__/pattern-predicate.test.ts b/packages/common-utils/src/__tests__/pattern-predicate.test.ts index 660f320caa..2fc2fc8785 100644 --- a/packages/common-utils/src/__tests__/pattern-predicate.test.ts +++ b/packages/common-utils/src/__tests__/pattern-predicate.test.ts @@ -428,14 +428,30 @@ describe('templateToRegex with masks', () => { expect(matches(' <*> INFO x', '2026-11-04 INFO x')).toBe(false); }); - it('with delimiters, a mask matches a date of up to three runs', () => { + it('with delimiters, a mask matches a date of up to three parts', () => { const m = (template: string, value: string) => matches(template, value, PATTERN_REGEX_OPTIONS); - expect(m(' T06 started', '2026-11-04T06 started')).toBe(true); - expect(m(' <*> started', '2026-11-04T06 started')).toBe(true); + expect(m(' started', '2026-11-04 started')).toBe(true); expect(m('access 12', 'access [04/Nov/2026:12]')).toBe(true); + expect(m(' up', 'Wed, Nov 4 up')).toBe(true); expect(m(' started', '2026-11-04-01 started')).toBe(false); - expect(m(' started', 'boot started')).toBe(true); + expect(m(' started', 'boot started')).toBe(false); + expect(m(' started', 'job-42-x started')).toBe(false); + }); + + it('with delimiters, a mask touches only a severity letter or a T time', () => { + const m = (template: string, value: string) => + matches(template, value, PATTERN_REGEX_OPTIONS); + expect(m(' T06 started', '2026-11-04T06 started')).toBe(true); + expect(m(' <*> started', '2026-11-04T06 started')).toBe(true); + expect(m(' <*> started', '2026-11-04 boot started')).toBe(true); + expect(m('I <*> done', 'I1104 06 done')).toBe(true); + expect(m('<*> <*> done', 'E1104 06 done')).toBe(true); + expect(m('<*> <*> done', 'job 2026-11-04 06 done')).toBe(true); + expect(m('ts <*> msg done', 'tsunami 5 msg done')).toBe(false); + expect(m('ts <*> msg done', 'ts 2026-11-04 5 msg done')).toBe(true); + expect(m(' started', '2026-11-04x started')).toBe(false); + expect(m('x started', 'x2026-11-04 started')).toBe(false); expect( buildCompactPatternPredicate( 'Body', diff --git a/packages/common-utils/src/drain/config.ts b/packages/common-utils/src/drain/config.ts index c2668599b8..b0795b8f02 100644 --- a/packages/common-utils/src/drain/config.ts +++ b/packages/common-utils/src/drain/config.ts @@ -5,8 +5,8 @@ export interface MaskingInstructionConfig { perWord?: boolean; } -const MONTH = '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'; -const WEEKDAY = '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)'; +export const MONTH = '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'; +export const WEEKDAY = '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)'; const DAY = '(?:0?[1-9]|[12]\\d|3[01])'; const TIME = '\\d{1,2}:\\d{2}:\\d{2}'; const NOT_WORD_BEFORE = '(?'; /** @@ -30,8 +32,10 @@ export type PatternRegexOptions = { * * With extra delimiters the miner makes each mask a token of its own while * the delimiters split the raw date (`2026-11-04T06` mines as ` T06`). - * So a mask matches up to three runs joined by one separator, and the - * separator beside it is optional. parsePatternPredicate reads none of + * So `` matches up to three date parts (digits, or month and weekday + * names) joined by one separator. The separator beside it is optional only + * where the masker leaves none: after a klog severity letter (`I1104`) and + * before a `T` time (`2026-11-04T06`). parsePatternPredicate reads none of * these back. */ masks?: string[]; @@ -91,58 +95,93 @@ function tokensOf(template: string, options?: PatternRegexOptions): string[] { return template.split(split).filter(t => t.length > 0); } +// How one form of the regex spells separators and runs between them. +type Separators = { + /** One separator character. */ + one: string; + /** A run of separators between two tokens. */ + run: string; + /** An optional run of separators. */ + optional: string; + /** One run of non-separators: a token. */ + token: string; + /** Zero or more non-separators. */ + rest: string; +}; + // A template token as a regex: `<*>` becomes `wildcard`, each mask becomes -// `mask`, the rest is literal. +// `mask(name)`, the rest is literal. function tokenRegex( word: string, masks: string[], wildcard: string, - mask: string, + mask: (name: string) => string, ): string { if (word === PATTERN_WILDCARD) return wildcard; if (masks.length === 0) return escapeRe2Literal(word); return word .split(`<${masks[0]}>`) .map(part => tokenRegex(part, masks.slice(1), wildcard, mask)) - .join(mask); + .join(mask(masks[0])); } -// A masked date spans at most three runs between delimiters: 2026-11-04, -// 04/Nov/2026, 04.11.2026. +// The parts of a masked date: 2026-11-04, 04/Nov/2026, Wed Nov 4 (one mask +// per word), the klog 1104. +const DATE_PART = `(?:[0-9]{1,4}|${MONTH}|${WEEKDAY})`; +// A masked date spans at most three runs between delimiters. const MAX_MASK_RUNS = 3; -// Joins token regexes with `separator`, or with `optionalSeparator` beside a -// mask token when the miner split masks off with extra delimiters. -function joinTokens( - tokens: string[], - toRegex: (token: string) => string, - separator: string, - optionalSeparator: string, +function maskRegex( + name: string, + seps: Separators, options?: PatternRegexOptions, ): string { - const maskTokens = new Set( - (options?.extraDelimiters ?? []).length === 0 - ? [] - : (options?.masks ?? []).map(m => `<${m}>`), - ); - return tokens - .map((t, i) => - i === 0 - ? toRegex(t) - : (maskTokens.has(t) || maskTokens.has(tokens[i - 1]) - ? optionalSeparator - : separator) + toRegex(t), - ) - .join(''); + if ((options?.extraDelimiters ?? []).length === 0) return seps.token; + const part = name === DATE_MASK ? DATE_PART : seps.token; + return `${part}(?:${seps.one}${part}){0,${MAX_MASK_RUNS - 1}}`; } -function maskRegex( - run: string, - separator: string, +// The masker glues a date to a klog severity letter before it (I1104) and to +// a time after it (2026-11-04T06); the miner then splits them into tokens. +const SEVERITY_LETTER = /^[IWEF]$/; +const GLUED_TIME = /^T[0-9]/; + +// Joins the token regexes with separator runs. With extra delimiters and +// date masks, the run beside is optional where the masker leaves no +// separator, and a <*> there can hold either a glued or a separate token. +function joinTokens( + tokens: string[], + toRegex: (token: string) => string, + seps: Separators, options?: PatternRegexOptions, ): string { - if ((options?.extraDelimiters ?? []).length === 0) return run; - return `${run}(?:${separator}${run}){0,${MAX_MASK_RUNS - 1}}`; + const glues = + (options?.extraDelimiters ?? []).length > 0 && + (options?.masks ?? []).includes(DATE_MASK); + const isDate = (t: string | undefined) => glues && t === DATE_TOKEN; + const parts: string[] = []; + tokens.forEach((t, i) => { + const prev = tokens[i - 1]; + const next = tokens[i + 1]; + let join = i === 0 ? '' : seps.run; + let regex = toRegex(t); + if (t === PATTERN_WILDCARD && isDate(prev)) { + join = ''; + regex = `(?:${seps.optional}T[0-9]${seps.rest}|${seps.run}${seps.token})`; + if (isDate(next)) regex += seps.run; + } else if (t === PATTERN_WILDCARD && isDate(next)) { + regex = `(?:${seps.token}${seps.run}|[IWEF]${seps.optional})`; + } else if (isDate(t) && prev === PATTERN_WILDCARD) { + join = ''; + } else if ( + (isDate(prev) && GLUED_TIME.test(t)) || + (isDate(t) && prev != null && SEVERITY_LETTER.test(prev)) + ) { + join = seps.optional; + } + parts.push(join + regex); + }); + return parts.join(''); } /** Anchored RE2 regex that a value matches when it fits the Drain template. */ @@ -153,12 +192,20 @@ export function templateToRegex( const separators = separatorClass(options); const separator = `[${separators}]`; const nonSeparators = `[^${separators}]+`; - const mask = maskRegex(nonSeparators, separator, options); + const seps: Separators = { + one: separator, + run: `${separator}+`, + optional: `${separator}*`, + token: nonSeparators, + rest: `[^${separators}]*`, + }; const body = joinTokens( tokensOf(template, options), - t => tokenRegex(t, options?.masks ?? [], nonSeparators, mask), - `${separator}+`, - `${separator}*`, + t => + tokenRegex(t, options?.masks ?? [], nonSeparators, name => + maskRegex(name, seps, options), + ), + seps, options, ); return `^${separator}*${body}${separator}*$`; @@ -182,15 +229,23 @@ export function buildPatternPredicate( const COMPACT_START = '^ ?'; const COMPACT_END = ' ?$'; const COMPACT_WILDCARD = '[^ ]+'; +const COMPACT_SEPARATORS: Separators = { + one: ' ', + run: ' ', + optional: ' ?', + token: COMPACT_WILDCARD, + rest: '[^ ]*', +}; // Regex over a value whose separator runs were replaced by single spaces. function compactRegex(template: string, options?: PatternRegexOptions): string { - const mask = maskRegex(COMPACT_WILDCARD, ' ', options); const body = joinTokens( tokensOf(template, options), - t => tokenRegex(t, options?.masks ?? [], COMPACT_WILDCARD, mask), - ' ', - ' ?', + t => + tokenRegex(t, options?.masks ?? [], COMPACT_WILDCARD, name => + maskRegex(name, COMPACT_SEPARATORS, options), + ), + COMPACT_SEPARATORS, options, ); return `${COMPACT_START}${body}${COMPACT_END}`;