Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/patterns-split-on-punctuation.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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(/(?<!\\)\\p([A-Z])/g, '\\p{$1}'),
.replace(/(?<!\\)\\p([A-Z])/g, '\\p{$1}')
.replace(/\[:punct:\]/g, '!-\\/:-@\\[-\\x60{-~'),
'u',
);
}
Expand Down Expand Up @@ -128,7 +130,7 @@ describe('templateToRegex', () => {
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);
Expand Down
3 changes: 2 additions & 1 deletion packages/api/src/mcp/tools/query/denoise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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];
Expand Down
9 changes: 5 additions & 4 deletions packages/api/src/mcp/tools/query/patternDrilldown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ 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} ` +
`(also inside a token, e.g. backup_${DATE_TOKEN}.tar). ` +
'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 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.';
Expand Down
10 changes: 6 additions & 4 deletions packages/api/src/mcp/tools/query/runEventPatterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);

Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/cli.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<number, { count: number; sample: string }>();
for (const row of rows) {
const raw = opts.bodyColumn
Expand Down
6 changes: 3 additions & 3 deletions packages/common-utils/src/__tests__/drain-masking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<DATE> and E<DATE> 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<DATE> <*> 1 main.go:42] sync failed',
'I<DATE> <*> 1 main.go:42] sync done',
'E <DATE> <*> <*> <*> 345678 1 main go 42 sync failed',
'I <DATE> <*> <*> <*> 345678 1 main go 42 sync done',
]);
});

Expand Down
49 changes: 48 additions & 1 deletion packages/common-utils/src/__tests__/drain.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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('[<DATE>T06:12:12Z] ok', delimiters, ['<DATE>']),
).toEqual(['<DATE>', 'T06', '12', '12Z', 'ok']);
expect(tokenizeContent('<DATE>T06 ok', [], ['<DATE>'])).toEqual([
'<DATE>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', () => {
Expand Down
22 changes: 22 additions & 0 deletions packages/common-utils/src/__tests__/mine-patterns.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <DATE> <*> <*> <*> msg done',
]);
});
});

describe('minePatterns template fidelity', () => {
// Deterministic PRNG so the fuzz input is stable across runs.
function lcg(seed: number) {
Expand Down
4 changes: 2 additions & 2 deletions packages/common-utils/src/__tests__/noisy-matcher.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { minePatterns } from '@/drain/mine-patterns';
import { minePatterns, PATTERN_EXTRA_DELIMITERS } from '@/drain/mine-patterns';
import {
buildNoisyBodyMatcher,
selectNoisyPatterns,
Expand Down Expand Up @@ -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);
Expand Down
45 changes: 39 additions & 6 deletions packages/common-utils/src/__tests__/pattern-predicate.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -428,6 +428,39 @@ describe('templateToRegex with masks', () => {
expect(matches('<DATE> <*> INFO x', '2026-11-04 INFO x')).toBe(false);
});

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('<DATE> started', '2026-11-04 started')).toBe(true);
expect(m('access <DATE> 12', 'access [04/Nov/2026:12]')).toBe(true);
expect(m('<DATE> <DATE> <DATE> up', 'Wed, Nov 4 up')).toBe(true);
expect(m('<DATE> started', '2026-11-04-01 started')).toBe(false);
expect(m('<DATE> started', 'boot started')).toBe(false);
expect(m('<DATE> 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('<DATE> T06 started', '2026-11-04T06 started')).toBe(true);
expect(m('<DATE> <*> started', '2026-11-04T06 started')).toBe(true);
expect(m('<DATE> <*> started', '2026-11-04 boot started')).toBe(true);
expect(m('I <DATE> <*> done', 'I1104 06 done')).toBe(true);
expect(m('<*> <DATE> <*> done', 'E1104 06 done')).toBe(true);
expect(m('<*> <DATE> <*> done', 'job 2026-11-04 06 done')).toBe(true);
expect(m('ts <DATE> <*> msg done', 'tsunami 5 msg done')).toBe(false);
expect(m('ts <DATE> <*> msg done', 'ts 2026-11-04 5 msg done')).toBe(true);
expect(m('<DATE> started', '2026-11-04x started')).toBe(false);
expect(m('x <DATE> started', 'x2026-11-04 started')).toBe(false);
expect(
buildCompactPatternPredicate(
'Body',
'<DATE> T06 x',
PATTERN_REGEX_OPTIONS,
),
).not.toBeNull();
});

it('keeps <DATE> literal without the option', () => {
const t = 'wrote backup_<DATE>.tar';
expect(matches(t, 'wrote backup_<DATE>.tar', {})).toBe(true);
Expand All @@ -449,7 +482,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);
Expand All @@ -464,14 +497,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 <DATE> 06:12:12',
'Started job at <DATE> <*> 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);
}
});
Expand Down
4 changes: 2 additions & 2 deletions packages/common-utils/src/drain/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '(?<![0-9A-Za-z])';
Expand Down
Loading
Loading