Skip to content

fix(patterns): split MCP and CLI bodies on punctuation, as the web app does - #3762

Open
MikeShi42 wants to merge 2 commits into
mainfrom
claude/patterns-split-on-punctuation
Open

MikeShi42 wants to merge 2 commits into
mainfrom
claude/patterns-split-on-punctuation

Conversation

@MikeShi42

@MikeShi42 MikeShi42 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

MCP (event_patterns, emerging_signals, search denoise) and the CLI pattern view split log bodies on whitespace only. The web app's Event patterns view (drain3 in Pyodide) splits on ASCII punctuation as well. On compact bodies like JSON, whitespace splitting leaves each line as a few huge tokens. Nearly every line becomes its own pattern, with templates like <*> completed"}, and MCP and the UI give different patterns for the same data.

This PR puts the web app's delimiters in a shared miner config (createPatternMinerConfig, PATTERN_REGEX_OPTIONS) that MCP and the CLI both use. The web app's miner is unchanged.

Date masks are kept (#3551 added them so emerging_signals stops reporting the same pattern as both emerging and disappeared across days). Under punctuation splitting, the < and > around a mask became separators, so templates held a bare DATE and the drill-down whereSnippet matched no dated line. Two changes fix that:

  • Mining: a mask is kept as a token of its own: 2026-11-04T06:12:12Z mines as <DATE> T06 12 12Z.
  • Drill-down: a mask matches a date of up to three runs (2026-11-04, 04/Nov/2026), and the separator beside it is optional.

Drain port fix: the TS port trimmed the line before turning delimiters into spaces, so a line starting or ending with a delimiter got an empty token. drain3 never produces one. This was latent, because nothing passed delimiters to the port until now.

Parity with drain3: with no masks, the TS port now gives the same cluster ids and templates as drain3 0.9.11, with whitespace or punctuation delimiters. Checked on two 10k-line synthetic corpora (JSON from pino, zap, logrus and structlog; logfmt and plain text from the hdx-eval generators) and 67k lines from a local ClickStack. The checks were one-off scripts and are not in this PR.

Effect on MCP/CLI patterns (number of patterns covering 90% of lines):

Data Before After
JSON corpus 757 24
logfmt/plain corpus 2049 58
Local ClickStack (mostly plain k8s text) 12 23

The ClickStack data gets worse: values whose punctuation varies split one pattern into several (kind-worker3 vs kind-control-plane, 4.5ms vs 45ms). The web app's drain3 has the same weakness there (21).

Known limit: if a date and a plain word appear in the same position on lines of the same length, Drain merges them into <*>, and drill-down misses the dated lines. Lines where the date is a prefix, the common case, are not affected.

How to reproduce

Starting point: yarn dev (MCP needs the API), with a log source whose bodies are compact JSON, e.g. {"level":"info","msg":"user 42 logged in","ts":"2026-11-04T06:12:12Z"}.

On main:

  1. Call the MCP query tool with displayType: "event_patterns" on that source.
  2. The JSON punctuation stays glued to the tokens: the template is {"level":"info","msg":"user <*> logged <*>. Any line whose key order or field count differs, or whose first value varies, becomes a separate pattern.

On this branch:

  1. Make the same call.
  2. Templates read level info msg user <*> logged in ts <DATE> <*> <*> <*>, and the lines group into a few patterns.
  3. Run a pattern's whereSnippet in clickstack_search. It returns that pattern's dated lines.

How to test on Vercel preview

N/A — non-UI change. The web app's miner is not touched.

References

🤖 Generated with Claude Code

…p 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.
@MikeShi42
MikeShi42 requested a review from a team as a code owner November 22, 2026 19:15
@vercel

vercel Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
hyperdx-oss Ready Ready Preview Nov 22, 2026 7:29pm UTC
hyperdx-storybook Ready Ready Preview Nov 22, 2026 7:29pm UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: bf11c06

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

This PR includes changesets to release 5 packages
Name Type
@hyperdx/common-utils Patch
@hyperdx/api Patch
@hyperdx/cli 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

@github-actions github-actions Bot added the review/tier-3 Standard — full human review required label Nov 22, 2026
@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

🟡 Tier 3 — Standard

Introduces new logic, modifies core functionality, or touches areas with non-trivial risk.

Why this tier:

  • Diff size: 297 production lines changed (Tier 2 max: < 250)
  • Cross-layer change: touches backend (packages/api) + shared utils (packages/common-utils)

Review process: Full human review — logic, architecture, edge cases.
SLA: First-pass feedback within 1 business day.

Stats
  • Production files changed: 11
  • Production lines changed: 297 (+ 136 in test files, excluded from tier calculation)
  • Branch: claude/patterns-split-on-punctuation
  • Author: MikeShi42

To override this classification, remove the review/tier-3 label and apply a different review/tier-* label. Manual overrides are preserved on subsequent pushes.

@github-actions

Copy link
Copy Markdown
Contributor

Duplicate code analysis

No new duplicate code introduced by this PR.


jscpd compared this branch against origin/main
across app, api and common-utils. Only new clones are listed; the codebase
currently holds 108 in total (1.13%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

.map((t, i) =>
i === 0
? toRegex(t)
: (maskTokens.has(t) || maskTokens.has(tokens[i - 1])

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.

🔴 P1 — With delimiters, <DATE> matches any 1–3 words, and the separators beside it are optional, so the drill-down whereSnippet matches lines without a date

The mask is [^sep]+(?:[sep][^sep]+){0,2} and both neighbours join with [sep]*. Nothing requires the value to look like a date, and a literal or <*> next to the mask can match part of a word. For example, the mined template ts <DATE> <*> msg done matches tsunami 5 msg done (ts + una + mi/5), and the new test locks in m('<DATE> started', 'boot started') === true. So PATTERN_MATCH_SEMANTICS (patternDrilldown.ts:92-94) is wrong when it promises "the same literal tokens in the same positions" and "a date of up to three tokens". Fix: make the mask regex date-shaped (for example, require a digit in the first run, or a month/weekday name). Make the separator optional only where the masker can glue a date to its neighbour: after a klog severity letter [IWEF] on the left, and before a T\d token on the right (see the lookaheads in config.ts:35,71). Everywhere else keep [sep]+. Flip the boot started assertion to false.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in bf11c06. <DATE> now matches up to three date parts (digits, or month and weekday names). The separator beside it is optional only after a klog severity letter and before a T time, which are the two places the masker leaves none. boot started, job-42-x started and tsunami 5 msg done no longer match, and PATTERN_MATCH_SEMANTICS is updated. In ClickHouse, every mined pattern's drill-down still matches all its sampled members: 0 misses over 6,979 samples from 723 patterns on two synthetic corpora and 67k real log lines.

@github-actions

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

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

No inline comments. 6 P3 folded at the bottom.

🔵 6 P3 — no action needed before merge
  • 🔵 P3 packages/common-utils/src/drain/pattern-predicate.ts:139 — Mask regex and keepTokens split assume all ASCII punctuation, but they run for any non-empty delimiter set → maskRegex and joinTokens switch to the multi-part DATE form whenever extraDelimiters is non-empty. tokenizeContent and TemplateMiner likewise split <DATE> away from the text beside it for any delimiters. Take extraDelimiters: ['='] with masks: the miner turns backup_2026-11-04.tar into backup_ <DATE> .tar. The predicate then needs a separator between backup_ and the date, and DATE_PART(?:[sep]DATE_PART){0,2} cannot match 2026-11-04 because - is not a separator, so the value matches nothing. Only use the new behaviour when the delimiters split a mask's brackets and the date's own separators (for example, when the set covers all of ASCII_PUNCTUATION), and keep the old whole-token behaviour otherwise. The other option is to reject that combination in separatorClass.
  • 🔵 P3 packages/common-utils/src/drain/mine-patterns.ts:22 — PATTERN_EXTRA_DELIMITERS duplicates the app's DRAIN_EXTRA_DELIMITERS → packages/app/src/components/Patterns/drainDelimiters.ts:6 already defines DRAIN_EXTRA_DELIMITERS = ASCII_PUNCTUATION.split('') as the web app miner's delimiters. The PR says MCP/CLI and the web app must tokenize the same way, so this creates two sources of truth that have to be kept equal by hand. Make drainDelimiters.ts re-export PATTERN_EXTRA_DELIMITERS (or alias it), or delete the app copy.
  • 🔵 P3 packages/common-utils/src/drain/noisy-matcher.ts:599 — The mask-token list is built twice, in noisy-matcher and in TemplateMiner → masker.maskNames.map(n => masker.maskPrefix + n + masker.maskSuffix) repeats the expression at template-miner.ts:44. Both must give the same keepTokens, or the denoise body tokens drift from the mined templates. Add one LogMasker getter (for example maskTokens) and use it in both places.
  • 🔵 P3 packages/api/src/mcp/tools/query/denoise.ts:233 — Callers must rebuild the miner's tokenization options by hand for buildNoisyBodyMatcher → To match minePatterns, the denoise path now has to pass both extraDelimiters: PATTERN_EXTRA_DELIMITERS and masked: true. If a call site leaves out either one, the matcher quietly tokenizes differently from the miner. PATTERN_REGEX_OPTIONS already exists for predicates; export a matching PATTERN_NOISY_MATCHER_OPTIONS from mine-patterns.ts next to it, so the miner config stays in one place.
  • 🔵 P3 packages/common-utils/src/drain/pattern-predicate.ts:272 — No caller uses the new mask handling in buildCompactPatternPredicate, and parsePatternPredicate cannot read its output back → The only production caller is packages/app/src/components/Patterns/patternFilter.ts, which passes no masks, so the new mask-stripping in splitsToken and the masked compact regex run only in a test. If a URL filter were ever built with masks, parseCompactPredicate would fail on the DATE alternation, and withPatternFilter would stop deduplicating that filter. Remove the masked compact path until there is a caller, or make parsePatternPredicate able to read it.
  • 🔵 P3 packages/api/src/mcp/tools/query/__tests__/patternDrilldown.test.ts:47 — The new <DATE> drill-down regex is tested only through a hand-written RE2→JS translation → The new DATE_PART/glue regex is checked only in JS, after toJsRegex rewrites [:punct:] by hand. The ClickHouse integration fixtures in packages/api/src/mcp/__tests__/queryTool.int.test.ts have no dated bodies. So the main promise of this PR, that a pattern's whereSnippet returns its dated lines, is never run against RE2. Add an integration case with bodies such as {"ts":"2026-11-04T06:12:12Z","msg":"done"} and klog I1104 06:12:12... lines that drills each pattern and expects exactly its sampleCount rows.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. The escaping chain for the SQL-embedded regexes is sound (a crafted log body cannot break out of the string literal — escapeSqlString runs over the whole generated regex as the final step), valueExpression provenance stays trusted, RE2 keeps matching linear, and the new behavior is well covered by the added drain, mine-patterns, pattern-predicate, and patternDrilldown tests. The two findings the standards pass raised against .claude/skills/refactor-component/SKILL.md were dropped: that eslint→oxlint edit already exists on main (#3731, #3732) and only shows in the diff because the review base predates those merges — it is not authored by this PR.

🟡 P2 — recommended

  • packages/common-utils/src/drain/pattern-predicate.ts:146 — The <DATE> drill-down regex hardcodes the klog severity letters ([IWEF]), the T-time glue, and MAX_MASK_RUNS to mirror the masking instructions in config.ts, but no test guards that cross-file contract, so a later masking-instruction edit (new severity letter, new date format) would silently narrow drill-down matching and make whereSnippet miss dated rows.
    • Fix: Add a contract/regression test that enumerates the severity letters and date shapes, or derive both the masker and the regex builder from one shared source, so a config.ts change fails loudly when pattern-predicate.ts is not updated.
    • maintainability
🔵 P3 nitpicks (3)
  • packages/common-utils/src/drain/mine-patterns.ts:22 — PATTERN_EXTRA_DELIMITERS is an exported mutable array that is aliased into PATTERN_REGEX_OPTIONS.extraDelimiters, so any consumer mutating the export corrupts every miner and regex path at once.
    • Fix: Freeze it and type it readonly (export const PATTERN_EXTRA_DELIMITERS: readonly string[] = Object.freeze(ASCII_PUNCTUATION.split(''))), and freeze PATTERN_REGEX_OPTIONS.
    • kieran-typescript, maintainability
  • packages/common-utils/src/drain/pattern-predicate.ts:146 — The klog letters [IWEF] and the T[0-9] time are each spelled twice — once in the detection regexes SEVERITY_LETTER/GLUED_TIME and again in the emitted regex inside joinTokens — so a change must touch both spots.
    • Fix: Define shared constants (e.g. SEVERITY_LETTERS = 'IWEF') and build both the detection RegExp and the emitted character class from them.
    • maintainability
  • packages/common-utils/src/drain/template-miner.ts:44 — The maskNames.map(n => maskPrefix + n + maskSuffix) mask-token construction is duplicated here and in noisy-matcher.ts; the two must stay in sync so mining and matching tokenize masks identically.
    • Fix: Expose a maskTokens getter on LogMasker and use it in both places.
    • maintainability

Reviewers (5): security, maintainability, performance, project-standards, kieran-typescript.

Testing gaps:

  • No test asserts that a log body containing ' and \ is fully neutralized by escapeSqlString in both buildPatternPredicate and buildCompactPatternPredicate.
  • No regression guard for the config.ts ↔ pattern-predicate.ts severity-letter / date-format coupling.
  • No end-to-end denoise latency check at the 10k-row sample size with the new 32-delimiter tokenizer (tokenizeContent now does ~33 string passes per line vs a single whitespace split; bounded and one-shot, but unbenchmarked).

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

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 473 passed • 1 skipped • 1096s

Status Count
✅ Passed 473
❌ Failed 0
⚠️ Flaky 11
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

With punctuation delimiters, <DATE> matched any one to three runs and the
separators beside it were optional, so a drill-down matched lines with no
date (`ts <DATE> <*> 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).
@MikeShi42

Copy link
Copy Markdown
Contributor Author

Re Deep Review: the .claude/skills/refactor-component/SKILL.md P3 is not part of this PR. That file changed on main (#3731, #3732) after this branch was cut, and it is not in this PR's diff. The other P3s from both reviews (a shared app/common-utils delimiter constant, a maskTokens getter, shared matcher options, freezing the exported delimiter array, a single-pass tokenizer) widen the change or touch files it does not, so they are left for follow-ups.

@MikeShi42

Copy link
Copy Markdown
Contributor Author

Re the second Claude review round: no P0–P2 left, so per AGENTS.md I am stopping on automated findings here. Two of the P3s are worth follow-ups rather than more changes in this PR:

  • The mask handling assumes the full ASCII punctuation set. The only caller with masks (createPatternMinerConfig) uses that set, so a partial set is not reachable today.
  • No ClickHouse integration test covers drill-down on dated bodies. I checked it by hand against RE2 (0 misses over 6,979 samples from 723 patterns), but that check is not in the suite.

Ready for a maintainer review.

@MikeShi42

Copy link
Copy Markdown
Contributor Author

Re Deep Review round 2: the P2 (the <DATE> drill-down regex repeats the klog letters and date shapes from the masks in config.ts, with no test tying them together) is a fair follow-up. A contract test that runs every masking instruction's example dates through the predicate would catch drift. It is not in this PR, per the two-round limit.

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — bf11c063 Deployed Nov 22, 2026 by vercel[bot]
Preview – hyperdx-storybook — bf11c063 Deployed Nov 22, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/tier-3 Standard — full human review required

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants