From 825302c9565943122944c63fee5ba6ac07564344 Mon Sep 17 00:00:00 2001 From: Drew Hammond <2405390+drewhammond@users.noreply.github.com> Date: Tue, 20 Oct 2026 23:49:11 -0400 Subject: [PATCH 1/4] perf(app): mine Event Patterns with the TypeScript Drain port instead of Pyodide Event Patterns loaded a 14 MB Python runtime and ran drain3 in it on the main thread, freezing the page for up to 760 ms on first use (1.3 s on a 4x throttled CPU). The TypeScript port the CLI and MCP server already use gives the same clusters and templates and mines 10,000 lines in under 50 ms. The port masks dates by default since #3551, so the app clears the masks to match drain3's default config. With punctuation delimiters a masked date is one word where the log has three, which would misalign the pattern display, Denoise and pattern filters. mineEventPatterns.test.ts checks that dates stay unmasked. --- .../__tests__/mineEventPatterns.test.ts | 15 ++ .../components/Patterns/mineEventPatterns.ts | 18 +++ packages/app/src/hooks/usePatterns.tsx | 145 +++--------------- .../common-utils/src/drain/noisy-matcher.ts | 3 +- 4 files changed, 58 insertions(+), 123 deletions(-) create mode 100644 packages/app/src/components/Patterns/__tests__/mineEventPatterns.test.ts create mode 100644 packages/app/src/components/Patterns/mineEventPatterns.ts diff --git a/packages/app/src/components/Patterns/__tests__/mineEventPatterns.test.ts b/packages/app/src/components/Patterns/__tests__/mineEventPatterns.test.ts new file mode 100644 index 0000000000..dc54acfa24 --- /dev/null +++ b/packages/app/src/components/Patterns/__tests__/mineEventPatterns.test.ts @@ -0,0 +1,15 @@ +import { mineEventPatterns } from '@/components/Patterns/mineEventPatterns'; +import { reconstructTemplate } from '@/components/Patterns/reconstructTemplate'; + +describe('mineEventPatterns', () => { + it('leaves dates unmasked so the displayed pattern lines up with the log', () => { + const logs = [ + '2026-11-19T10:00:01Z INFO user 42 logged in from 10.0.0.1', + '2026-11-18T11:22:33Z INFO user 7 logged in from 10.0.0.2', + ]; + const { patterns } = mineEventPatterns(logs); + expect(reconstructTemplate(logs[1], patterns[1].templateMined)).toBe( + '2026-11-<*>:<*>:<*> INFO user <*> logged in from 10.0.0.<*>', + ); + }); +}); diff --git a/packages/app/src/components/Patterns/mineEventPatterns.ts b/packages/app/src/components/Patterns/mineEventPatterns.ts new file mode 100644 index 0000000000..2b01bc9520 --- /dev/null +++ b/packages/app/src/components/Patterns/mineEventPatterns.ts @@ -0,0 +1,18 @@ +import { + TemplateMiner, + TemplateMinerConfig, +} from '@hyperdx/common-utils/dist/drain'; + +import { DRAIN_EXTRA_DELIMITERS } from '@/components/Patterns/drainDelimiters'; + +export function mineEventPatterns(logs: string[]) { + const config = new TemplateMinerConfig(); + config.drainExtraDelimiters = DRAIN_EXTRA_DELIMITERS; + // Masked dates wouldn't line up word for word with the log + config.maskingInstructions = []; + const miner = new TemplateMiner(config); + const patterns = logs.map(log => miner.addLogMessage(log)); + const templates: Record = {}; + for (const p of patterns) templates[p.clusterId] = p.templateMined; + return { patterns, templates }; +} diff --git a/packages/app/src/hooks/usePatterns.tsx b/packages/app/src/hooks/usePatterns.tsx index baa34a6cc1..7c5278ad2e 100644 --- a/packages/app/src/hooks/usePatterns.tsx +++ b/packages/app/src/hooks/usePatterns.tsx @@ -6,101 +6,11 @@ import { useQuery } from '@tanstack/react-query'; import { timeBucketByGranularity, toStartOfInterval } from '@/ChartUtils'; import { useConfigWithAdditionalSelect } from '@/components/DBRowTable'; -import { DRAIN_EXTRA_DELIMITERS } from '@/components/Patterns/drainDelimiters'; +import { mineEventPatterns } from '@/components/Patterns/mineEventPatterns'; import { reconstructTemplate } from '@/components/Patterns/reconstructTemplate'; import { useQueriedChartConfig } from '@/hooks/useChartConfig'; import { getFirstTimestampValueExpression } from '@/source'; -// We don't want to load pyodide over and over again, use react query to cache the async instance -function usePyodide(options: { enabled: boolean }) { - return useQuery({ - queryKey: ['pyodide'], - queryFn: async () => { - // @ts-expect-error loadPyodide is injected by the pyodide script and not on the Window type - const pyodide = await window.loadPyodide(); - await pyodide.loadPackage('micropip'); - const micropip = pyodide.pyimport('micropip'); - - // Install jsonpickle first (drain3 dependency) - const jsonpickleUrl = new URL( - '/jsonpickle-4.1.1-py3-none-any.whl', - window.location.origin, - ); - await micropip.install(jsonpickleUrl.href); - - // Then install drain3 - const drain3Url = new URL( - '/drain3-0.9.11-py3-none-any.whl', - window.location.origin, - ); - await micropip.install(drain3Url.href); - - return pyodide; - }, - refetchOnWindowFocus: false, - refetchOnMount: false, - refetchInterval: false, - enabled: options.enabled, - }); -} - -class Miner { - private minerVariableName; - private id; - constructor(private pyodide: any) { - this.id = Math.random().toString(36).substring(2, 15); - this.minerVariableName = `m_${this.id}`; - } - - async init() { - await this.pyodide.runPythonAsync(` -import js -import json -from drain3 import TemplateMiner -from drain3.template_miner_config import TemplateMinerConfig - -_config = TemplateMinerConfig() -_config.drain_extra_delimiters = json.loads(${JSON.stringify(JSON.stringify(DRAIN_EXTRA_DELIMITERS))}) - -${this.minerVariableName} = TemplateMiner(None, _config) - `); - } - - async minePatterns(logs: string[]) { - const tempLogs = `temp_logs_${this.id}`; - const tempResults = `temp_results_${this.id}`; - this.pyodide.globals.set(tempLogs, logs); - return JSON.parse( - await this.pyodide.runPythonAsync(` - ${tempResults} = [] - for log in ${tempLogs}: - ${tempResults}.append(${this.minerVariableName}.add_log_message(log)) - json.dumps(${tempResults}) - `), - ); - } - - /** Final template of every cluster, keyed by cluster id. */ - async getTemplates(): Promise> { - return JSON.parse( - await this.pyodide.runPythonAsync(` - json.dumps({str(c.cluster_id): c.get_template() for c in ${this.minerVariableName}.drain.clusters}) - `), - ); - } -} - -async function mineEventPatterns(logs: string[], pyodide: any) { - const miner = new Miner(pyodide); - await miner.init(); - const patterns = await miner.minePatterns(logs); - return { - miner, - patterns, - templates: await miner.getTemplates(), - }; -} - export const PATTERN_COLUMN_ALIAS = '__hdx_pattern_field'; export const TIMESTAMP_COLUMN_ALIAS = '__hdx_timestamp'; export const SERVICE_NAME_COLUMN_ALIAS = '__hdx_service_name'; @@ -167,12 +77,6 @@ function usePatterns({ { enabled: configWithPrimaryAndPartitionKey != null && enabled }, ); - const { - data: pyodide, - isLoading: isLoadingPyodide, - error: pyodideError, - } = usePyodide({ enabled }); - const query = useQuery({ queryKey: ['patterns', config, bodyValueExpression], queryFn: () => { @@ -186,37 +90,35 @@ function usePatterns({ }) ?? []; // patternId -> count, {bucket:count}, pattern - return mineEventPatterns(logs, pyodide).then(response => { - const rowsWithPatternId = []; - const result = response.patterns; - for (let i = 0; i < result.length; i++) { - const r = result[i]; - const row = sampleRows?.data[i]; - rowsWithPatternId.push({ - ...row, - __hdx_patternId: r.cluster_id, - __hdx_pattern: r.template_mined, - }); - } + const response = mineEventPatterns(logs); + const rowsWithPatternId = []; + const result = response.patterns; + for (let i = 0; i < result.length; i++) { + const r = result[i]; + const row = sampleRows?.data[i]; + rowsWithPatternId.push({ + ...row, + __hdx_patternId: r.clusterId, + __hdx_pattern: r.templateMined, + }); + } - return { - ...sampleRows, - data: rowsWithPatternId, - additionalKeysLength: - configWithPrimaryAndPartitionKey.additionalKeysLength, - miner: response.miner, - clusterTemplates: response.templates, - }; - }); + return { + ...sampleRows, + data: rowsWithPatternId, + additionalKeysLength: + configWithPrimaryAndPartitionKey.additionalKeysLength, + clusterTemplates: response.templates, + }; }, refetchOnWindowFocus: false, - enabled: sampleRows != null && pyodide != null && enabled, + enabled: sampleRows != null && enabled, }); return { ...query, - error: sampleError || pyodideError || query.error, - isLoading: query.isLoading || isSampleLoading || isLoadingPyodide, + error: sampleError || query.error, + isLoading: query.isLoading || isSampleLoading, patternQueryConfig: configWithPrimaryAndPartitionKey, }; } @@ -337,7 +239,6 @@ export function useGroupedPatterns({ data: groupedResults, isLoading, error, - miner: results?.miner, clusterTemplates: results?.clusterTemplates, sampledRowCount, patternQueryConfig, diff --git a/packages/common-utils/src/drain/noisy-matcher.ts b/packages/common-utils/src/drain/noisy-matcher.ts index d96925fb8f..788bf24ab0 100644 --- a/packages/common-utils/src/drain/noisy-matcher.ts +++ b/packages/common-utils/src/drain/noisy-matcher.ts @@ -32,7 +32,8 @@ export function selectNoisyPatterns( * `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 is masked the same way. Leave it off for a miner without masks, such + * as the app's. */ export function buildNoisyBodyMatcher( templates: string[], From 6556015eda109f57122b4189fe757ec09d9f05ac Mon Sep 17 00:00:00 2001 From: Johan Gustafsson <10134898+karljohang@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:38:28 -0500 Subject: [PATCH 2/4] fix(app): split pattern filters where the TypeScript miner does Event Patterns now mines with the TypeScript Drain port, which splits on JS `\s`. Pattern filters still split on Python's str.split() whitespace, so an event with a BOM between words fell out of an include filter of its own pattern, and one with \x1e or NEL matched a pattern it was never mined into. Filters built before this change still filter the same and still read back as pattern filters. The filter options now sit next to the shared delimiter list in drainDelimiters.ts. The list was already shared, but the filter's whitespace was set on its own, so nothing moved it when the miner did. --- .../Patterns/__tests__/patternFilter.test.ts | 56 ++++++++++++++++++- .../components/Patterns/drainDelimiters.ts | 15 ++++- .../src/components/Patterns/patternFilter.ts | 25 ++++----- 3 files changed, 81 insertions(+), 15 deletions(-) diff --git a/packages/app/src/components/Patterns/__tests__/patternFilter.test.ts b/packages/app/src/components/Patterns/__tests__/patternFilter.test.ts index b98f30b678..11654fd483 100644 --- a/packages/app/src/components/Patterns/__tests__/patternFilter.test.ts +++ b/packages/app/src/components/Patterns/__tests__/patternFilter.test.ts @@ -1,5 +1,14 @@ +import { + buildCompactPatternPredicate, + parsePatternPredicate, +} from '@hyperdx/common-utils/dist/drain'; import type { ConditionFilter, Filter } from '@hyperdx/common-utils/dist/types'; +import { + LEGACY_PATTERN_REGEX_OPTIONS, + PATTERN_REGEX_OPTIONS, +} from '@/components/Patterns/drainDelimiters'; +import { mineEventPatterns } from '@/components/Patterns/mineEventPatterns'; import { buildPatternFilter, isPatternFilter, @@ -55,14 +64,30 @@ describe('pattern filters', () => { expect( fits(filter, '\x1b[32minfo\x1b[39m: request \x1b[1;31mdone\x1b[0m'), ).toBe(true); + // Separators that JS `\s` has and Python's str.split() lacks. + expect(fits(filter, 'info\ufeffrequest done')).toBe(true); // Separators that Python's str.split() has and JS `\s` lacks. - expect(fits(filter, 'info\x1erequest\x85done')).toBe(true); + expect(fits(filter, 'info\x1erequest\x85done')).toBe(false); expect(fits(filter, 'warn: request done')).toBe(false); expect( fits(exclude('info request done'), '\x1b[32minfo\x1b[39m request done'), ).toBe(false); }); + it('splits a body where the miner did', () => { + const lines = [ + 'info\ufeffrequest done', + 'info\x1erequest done', + 'info\x85request done', + ]; + const { templates } = mineEventPatterns(lines); + const wholeLine = (line: string) => + Object.values(templates).filter(t => fits(include(t), line)); + expect(wholeLine(lines[0])).toEqual(['info request done']); + expect(wholeLine(lines[1])).toEqual(['info\x1erequest done']); + expect(wholeLine(lines[2])).toEqual(['info\x85request done']); + }); + it('only reads back filters it built', () => { // The same predicate without the ANSI step is not a pattern filter. const condition = include('a <*>').condition.replace( @@ -99,6 +124,35 @@ describe('pattern filters', () => { ).toEqual([facet, include('a <*>')]); }); + it('reads back and replaces an include saved when the miner was drain3', () => { + const { valueExpression } = parsePatternPredicate( + include('a <*>').condition, + PATTERN_REGEX_OPTIONS, + )!; + const saved: ConditionFilter = { + type: 'sql', + condition: buildCompactPatternPredicate( + valueExpression, + 'a <*>', + LEGACY_PATTERN_REGEX_OPTIONS, + )!, + }; + expect(saved.condition).not.toBe(include('a <*>').condition); + expect(parsePatternFilter(saved)).toMatchObject({ + valueExpression: 'Body', + template: 'a <*>', + action: 'include', + }); + expect(withPatternFilter([facet, saved], include('b <*>'))).toEqual([ + facet, + include('b <*>'), + ]); + // The same pattern is rebuilt the way the miner splits today. + expect(withPatternFilter([saved], exclude('a <*>'))).toEqual([ + exclude('a <*>'), + ]); + }); + it('replaces an include on another column too', () => { const other = buildPatternFilter('Message', 'b <*>', 'include')!; expect(withPatternFilter([include('a <*>')], other)).toEqual([other]); diff --git a/packages/app/src/components/Patterns/drainDelimiters.ts b/packages/app/src/components/Patterns/drainDelimiters.ts index 69b421edf7..e2f4f7f77d 100644 --- a/packages/app/src/components/Patterns/drainDelimiters.ts +++ b/packages/app/src/components/Patterns/drainDelimiters.ts @@ -1,6 +1,19 @@ -import { ASCII_PUNCTUATION } from '@hyperdx/common-utils/dist/drain'; +import { + ASCII_PUNCTUATION, + type PatternRegexOptions, +} from '@hyperdx/common-utils/dist/drain'; // Python's string.punctuation, the extra delimiters of the app's miner. // Anything that splits bodies or templates the way the miner did (the denoise // matcher, pattern filters) must use the same list. export const DRAIN_EXTRA_DELIMITERS = ASCII_PUNCTUATION.split(''); + +export const PATTERN_REGEX_OPTIONS: PatternRegexOptions = { + extraDelimiters: DRAIN_EXTRA_DELIMITERS, +}; + +// For reading back filters saved under drain3, which split on str.split() +export const LEGACY_PATTERN_REGEX_OPTIONS: PatternRegexOptions = { + extraDelimiters: DRAIN_EXTRA_DELIMITERS, + whitespace: 'python', +}; diff --git a/packages/app/src/components/Patterns/patternFilter.ts b/packages/app/src/components/Patterns/patternFilter.ts index bc34453e45..16a2b5248d 100644 --- a/packages/app/src/components/Patterns/patternFilter.ts +++ b/packages/app/src/components/Patterns/patternFilter.ts @@ -2,11 +2,13 @@ import { escapeSqlString } from '@hyperdx/common-utils/dist/core/utils'; import { buildCompactPatternPredicate, parsePatternPredicate, - type PatternRegexOptions, } from '@hyperdx/common-utils/dist/drain'; import type { ConditionFilter, Filter } from '@hyperdx/common-utils/dist/types'; -import { DRAIN_EXTRA_DELIMITERS } from '@/components/Patterns/drainDelimiters'; +import { + LEGACY_PATTERN_REGEX_OPTIONS, + PATTERN_REGEX_OPTIONS, +} from '@/components/Patterns/drainDelimiters'; export type PatternFilterAction = 'include' | 'exclude'; @@ -17,12 +19,6 @@ export type PatternFilter = { action: PatternFilterAction; }; -// The templates come from the app's miner (Python Drain3), so the regex must -// split where it did. -const options: PatternRegexOptions = { - extraDelimiters: DRAIN_EXTRA_DELIMITERS, - whitespace: 'python', -}; const NOT = 'NOT '; // The miner strips ANSI escape codes before mining (usePatterns), so the @@ -44,7 +40,7 @@ export function buildPatternFilter( const predicate = buildCompactPatternPredicate( `${STRIP_ANSI_START}${valueExpression}${STRIP_ANSI_END}`, template, - options, + PATTERN_REGEX_OPTIONS, ); if (predicate == null) return null; return { @@ -57,10 +53,13 @@ export function buildPatternFilter( export function parsePatternFilter(filter: Filter): PatternFilter | null { if (filter.type !== 'sql') return null; const excluded = filter.condition.startsWith(NOT); - const parsed = parsePatternPredicate( - excluded ? filter.condition.slice(NOT.length) : filter.condition, - options, - ); + const predicate = excluded + ? filter.condition.slice(NOT.length) + : filter.condition; + // Also read back filters saved under drain3 + const parsed = + parsePatternPredicate(predicate, PATTERN_REGEX_OPTIONS) ?? + parsePatternPredicate(predicate, LEGACY_PATTERN_REGEX_OPTIONS); if (parsed == null) return null; const { valueExpression, template } = parsed; if ( From f2f0c7c31a70d50d4af907b140014cba0af1fb18 Mon Sep 17 00:00:00 2001 From: Johan Gustafsson <10134898+karljohang@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:55:38 -0500 Subject: [PATCH 3/4] test(app): pattern filters and Denoise match every line of a mined template patternFilter.test.ts mines two JSON lines and two that start with dates, and checks that every template's filter and Denoise matcher match every line mined into it. Putting back the default date masks fails both tests. --- .../Patterns/__tests__/patternFilter.test.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/packages/app/src/components/Patterns/__tests__/patternFilter.test.ts b/packages/app/src/components/Patterns/__tests__/patternFilter.test.ts index 11654fd483..32f736eaa6 100644 --- a/packages/app/src/components/Patterns/__tests__/patternFilter.test.ts +++ b/packages/app/src/components/Patterns/__tests__/patternFilter.test.ts @@ -1,10 +1,12 @@ import { buildCompactPatternPredicate, + buildNoisyBodyMatcher, parsePatternPredicate, } from '@hyperdx/common-utils/dist/drain'; import type { ConditionFilter, Filter } from '@hyperdx/common-utils/dist/types'; import { + DRAIN_EXTRA_DELIMITERS, LEGACY_PATTERN_REGEX_OPTIONS, PATTERN_REGEX_OPTIONS, } from '@/components/Patterns/drainDelimiters'; @@ -172,3 +174,33 @@ describe('pattern filters', () => { ]); }); }); + +describe('pattern filters and Denoise on mined templates', () => { + const lines = [ + '{"level":"info","msg":"order placed","orderId":"a1f3","total":12.50}', + '{"level":"info","msg":"order placed","orderId":"9c2e","total":3.75}', + '2026-11-19T10:00:01Z INFO user 42 logged in from 10.0.0.1', + '2026-11-18T11:22:33Z INFO user 7 logged in from 10.0.0.2', + ]; + const { patterns, templates } = mineEventPatterns(lines); + + it('match every event of the template they were built from', () => { + const misses = lines.filter((line, i) => { + const template = templates[patterns[i].clusterId]; + const filter = buildPatternFilter('Body', template, 'include'); + return filter == null || !fits(filter, line); + }); + expect(misses).toEqual([]); + }); + + it('let Denoise find every event of a noisy template', () => { + const misses = lines.filter((line, i) => { + const template = templates[patterns[i].clusterId]; + const isNoisy = buildNoisyBodyMatcher([template], new Set([template]), { + extraDelimiters: DRAIN_EXTRA_DELIMITERS, + }); + return !isNoisy(line); + }); + expect(misses).toEqual([]); + }); +}); From 1f272dfb4da571fdc2f9706d6e69adfedde37f19 Mon Sep 17 00:00:00 2001 From: Johan Gustafsson <10134898+karljohang@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:23:37 -0500 Subject: [PATCH 4/4] chore: add changeset for the Event Patterns Drain port --- .changeset/event-patterns-drain-ts.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .changeset/event-patterns-drain-ts.md diff --git a/.changeset/event-patterns-drain-ts.md b/.changeset/event-patterns-drain-ts.md new file mode 100644 index 0000000000..ad5ed1839b --- /dev/null +++ b/.changeset/event-patterns-drain-ts.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/app': patch +--- + +perf(app): Event Patterns mines with the TypeScript Drain port instead of +`drain3` in Pyodide, so opening it no longer downloads a 14 MB Python runtime +or freezes the page while mining. Saved pattern filters still apply.