:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): pivot from a pattern to its matching logs (#68268)
Jon McCallum5dae2c451663
diff --git a/products/logs/backend/log_patterns.py b/products/logs/backend/log_patterns.pyindex 3720c277c16c..65497ed8b7e9 100644--- a/products/logs/backend/log_patterns.py+++ b/products/logs/backend/log_patterns.py@@ -24,6 +24,23 @@ _MASKING_INSTRUCTIONS = [_WHITESPACE_RE = re.compile(r"\s+")+# Raw-text regex fragment for each template placeholder, mirroring _MASKING_INSTRUCTIONS+# (what the mask consumed is what the fragment must match) plus Drain's `<*>` token+# wildcard. Fragments must stay RE2-safe — no lookaround, no backreferences — because the+# compiled predicate executes in ClickHouse's match().+_PLACEHOLDER_PATTERNS = {+ "<*>": r"\S+",+ "<num>": r"\d+",+ "<uuid>": r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",+ "<ip>": r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",+ "<hex>": r"(?:0x[0-9a-fA-F]+|[0-9a-fA-F]{16,})",+}+_PLACEHOLDER_RE = re.compile("|".join(re.escape(p) for p in _PLACEHOLDER_PATTERNS))++# Templates whose literal content is thinner than this compile to uselessly broad+# predicates (worst case "<*> <*> <*>" matches everything), so they get no regex.+_MIN_LITERAL_CHARS = 3+_T = TypeVar("_T", int, float)@@ -62,6 +79,11 @@ class MinedPattern:bucket_counts: list[int]# Raw sample counts keyed by lowercased severity_text.severity_counts: dict[str, int]+ # RE2-safe regex over raw bodies, self-validated against `examples`; None when the+ # template lacks literal content or validation failed. See compile_match_regex.+ match_regex: str | None+ # Longest literal run in the template — plain-text fallback when match_regex is None.+ match_literal: str | None@dataclass@@ -94,6 +116,61 @@ def _build_miner(sim_th: float, depth: int, max_clusters: int) -> tuple[LogMaskereturn masker, drain+def _escape_literal(text: str) -> str:+ # Template literals carry single spaces (bodies are whitespace-collapsed before mining),+ # but the raw lines this regex will run against may have arbitrary whitespace runs.+ return r"\s+".join(re.escape(token) for token in text.split(" "))+++def extract_match_literal(template: str) -> str | None:+ """Longest literal run in a template — the plain-text fallback predicate when the+ compiled regex fails validation. None when the template has no usable literal content."""+ longest = ""+ for literal in _PLACEHOLDER_RE.split(template):+ stripped = literal.strip()+ if len(stripped) > len(longest):+ longest = stripped+ return longest if len(longest) >= _MIN_LITERAL_CHARS else None+++def compile_match_regex(template: str, examples: list[LogSample], truncate: int) -> str | None:+ """Compile a mined template into an RE2-safe regex over raw log bodies, self-validated+ against the pattern's own examples.++ Returns None rather than an unvalidated predicate: Drain refines templates as rows merge,+ so an early-stored example can diverge from the final template — and a filter that+ silently matches the wrong logs is worse than no filter. Anchored at the start (leading+ whitespace was stripped before mining); the end anchor is dropped when any example hit+ the mining truncation cap, since the template then only covers a prefix of the raw line.+ """+ if not examples:+ return None+ literals = _PLACEHOLDER_RE.split(template)+ if not any(len(literal.strip()) >= _MIN_LITERAL_CHARS for literal in literals):+ return None++ parts = []+ pos = 0+ for match in _PLACEHOLDER_RE.finditer(template):+ parts.append(_escape_literal(template[pos : match.start()]))+ parts.append(_PLACEHOLDER_PATTERNS[match.group(0)])+ pos = match.end()+ parts.append(_escape_literal(template[pos:]))++ truncated = any(len(example.body) >= truncate for example in examples)+ candidate = r"^\s*" + "".join(parts) + ("" if truncated else r"\s*$")++ try:+ compiled = re.compile(candidate)+ except re.error:+ return None+ # Examples hold prepared bodies, which are valid instances of the raw form the regex+ # targets (collapsed runs still match \s+), so they double as the validation corpus.+ if not all(compiled.search(example.body) for example in examples):+ return None+ return candidate++def _bucket_index(buckets: list[tuple[dt.datetime, dt.datetime]], ts: dt.datetime) -> int | None:# Buckets are ordered, non-overlapping, half-open [start, end). bisect on starts finds# the only candidate; a timestamp can still fall in a gap between buckets (rows outside@@ -192,6 +269,8 @@ def mine_patterns(services=acc.services,bucket_counts=acc.bucket_counts,severity_counts=acc.severity_counts,+ match_regex=compile_match_regex(acc.template, acc.examples, truncate),+ match_literal=extract_match_literal(acc.template),)for acc in accumulators.values()]diff --git a/products/logs/backend/patterns_query_runner.py b/products/logs/backend/patterns_query_runner.pyindex 017b4a9d08e8..4c9e9ab2aa5a 100644--- a/products/logs/backend/patterns_query_runner.py+++ b/products/logs/backend/patterns_query_runner.py@@ -303,4 +303,6 @@ def _serialize(pattern: MinedPattern, *, total_count: int, scanned_count: int) -# Raw sample counts: severity dominance is a proportion, which is scale-invariant,# so extrapolating the map would add payload without changing what it says."severity_counts": pattern.severity_counts,+ "match_regex": pattern.match_regex,+ "match_literal": pattern.match_literal,}diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex f85d703b3d28..044434ae6b60 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -732,6 +732,22 @@ class _LogPatternSerializer(serializers.Serializer):"counts, not extrapolated — severity dominance is a proportion, so scaling would not change it."),)+ match_regex = serializers.CharField(+ allow_null=True,+ help_text=(+ "RE2-safe regex over raw log bodies that matches lines of this pattern, compiled from "+ "the template and validated against the pattern's own examples before being offered. "+ "Null when the template lacks literal content or validation failed — never trust an "+ "unvalidated predicate. Use with the message/regex log property filter."+ ),+ )+ match_literal = serializers.CharField(+ allow_null=True,+ help_text=(+ "Longest literal run in the template, for plain-text (icontains) filtering when "+ "`match_regex` is null. Null when the template has no usable literal content."+ ),+ )class _LogsPatternsSparklineBucketSerializer(serializers.Serializer):diff --git a/products/logs/backend/test/test_log_patterns.py b/products/logs/backend/test/test_log_patterns.pyindex 237b85a38557..12270f3cd573 100644--- a/products/logs/backend/test/test_log_patterns.py+++ b/products/logs/backend/test/test_log_patterns.py@@ -1,10 +1,11 @@+import reimport datetime as dtfrom unittest import TestCasefrom parameterized import parameterized-from products.logs.backend.log_patterns import LogSample, mine_patterns+from products.logs.backend.log_patterns import LogSample, compile_match_regex, extract_match_literal, mine_patternsdef _sample(@@ -137,3 +138,87 @@ class TestMinePatterns(TestCase):def test_empty_input_returns_empty(self) -> None:assert mine_patterns([]) == []++ def test_mined_patterns_carry_a_regex_that_matches_their_own_examples(self) -> None:+ # End-to-end self-consistency: whatever mining produced, the compiled predicate must+ # match the rows it came from — the invariant the whole "view matching logs" flow+ # rests on.+ samples = [_sample(f"User {name} not found in {i} ms") for i, name in enumerate(("alice", "bob", "carol"))]++ patterns = mine_patterns(samples)++ assert patterns[0].match_regex is not None+ compiled = re.compile(patterns[0].match_regex)+ for example in patterns[0].examples:+ assert compiled.search(example.body)+++class TestCompileMatchRegex(TestCase):+ @parameterized.expand(+ [+ # template, raw body that must match (arbitrary whitespace runs, live values)+ ("User <*> not found", "User dave not found"),+ ("User <*> not found", " User dave\tnot found "),+ ("took <num> ms", "took 12345 ms"),+ ("request <uuid> failed", "request 93fce79d-6926-4b08-8fa5-00ffd8e65f4e failed"),+ ("peer <ip> disconnected", "peer 10.32.243.94 disconnected"),+ ("token <hex> rejected", "token 0xdeadbeef rejected"),+ ("path /api/v1/users?id=<num> hit", "path /api/v1/users?id=42 hit"),+ ]+ )+ def test_compiled_regex_matches_raw_bodies(self, template: str, raw_body: str) -> None:+ regex = compile_match_regex(template, [_sample(raw_body.strip())], truncate=512)++ assert regex is not None+ assert re.search(regex, raw_body)++ @parameterized.expand(+ [+ # anchoring: a filter that matches unrelated lines is the failure mode this guards+ ("User <*> not found", "prefix junk User dave not found"),+ ("User <*> not found", "User dave not found trailing junk"),+ ]+ )+ def test_compiled_regex_is_anchored(self, template: str, non_matching_body: str) -> None:+ regex = compile_match_regex(template, [_sample("User dave not found")], truncate=512)++ assert regex is not None+ assert not re.search(regex, non_matching_body)++ def test_truncated_examples_drop_the_end_anchor(self) -> None:+ # A body that hit the mining truncation cap means the template only covers a prefix+ # of the raw line — the predicate must still match the full-length original.+ truncated_body = "prefix " + "x" * 505+ regex = compile_match_regex("prefix <*>", [_sample(truncated_body)], truncate=512)++ assert regex is not None+ assert re.search(regex, truncated_body + " continues beyond the cap")++ @parameterized.expand(+ [+ ("all_wildcards", "<*> <*> <*>"),+ ("literals_too_thin", "a <num> b"),+ ]+ )+ def test_templates_without_literal_content_get_no_regex(self, _name: str, template: str) -> None:+ assert compile_match_regex(template, [_sample("anything at all")], truncate=512) is None++ def test_diverged_example_fails_validation(self) -> None:+ # Drain refines templates as rows merge, so a stored example can stop matching the+ # final template. Shipping that regex would filter to the wrong logs — it must be+ # withheld instead.+ examples = [_sample("User dave not found"), _sample("something entirely different")]++ assert compile_match_regex("User <*> not found", examples, truncate=512) is None++ def test_no_examples_means_no_regex(self) -> None:+ assert compile_match_regex("User <*> not found", [], truncate=512) is None++ @parameterized.expand(+ [+ ("longest_run_wins", "at <uuid> failed to charge card for team <num>", "failed to charge card for team"),+ ("too_thin", "<*> ab <num>", None),+ ]+ )+ def test_extract_match_literal(self, _name: str, template: str, expected: str | None) -> None:+ assert extract_match_literal(template) == expecteddiff --git a/products/logs/backend/test/test_patterns_query_runner.py b/products/logs/backend/test/test_patterns_query_runner.pyindex 6043a19717d2..d3bfa92f18d7 100644--- a/products/logs/backend/test/test_patterns_query_runner.py+++ b/products/logs/backend/test/test_patterns_query_runner.py@@ -1,4 +1,5 @@import os+import reimport jsonimport datetime as dt@@ -75,6 +76,9 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert example["severity_text"] == "error"assert example["service_name"] == "auth"assert example["timestamp"].startswith("2026-06-23T12:00:00")+ # The pivot predicate ships validated: it must match the pattern's own examples.+ assert re.search(by_template["User <*> not found"]["match_regex"], example["body"])+ assert by_template["User <*> not found"]["match_literal"] == "not found"# Unsliced windows bucket uniformly; every sampled occurrence lands in some bucket.assert len(results["sparkline_buckets"]) == 24assert sum(by_template["User <*> not found"]["sparkline"]) == 3diff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsxindex 5341542a1e92..2747b20bc311 100644--- a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx@@ -1,6 +1,6 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'-import { LemonBanner, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'import type { LemonTableColumns } from '@posthog/lemon-ui'import { Sparkline } from 'lib/components/Sparkline'@@ -81,10 +81,33 @@ function PatternExampleRow({ example }: { example: _LogPatternExampleApi }): JSX)}-function PatternExpandedRow({ row }: { row: _LogPatternApi }): JSX.Element {+function PatternExpandedRow({+ row,+ onViewMatchingLogs,+}: {+ row: _LogPatternApi+ onViewMatchingLogs: (row: _LogPatternApi) => void+}): JSX.Element {return (<div className="px-2 py-2 flex flex-col gap-2" data-attr="logs-pattern-expanded">- <div>{renderPatternTemplate(row.pattern)}</div>+ <div className="flex items-center justify-between gap-2">+ <div>{renderPatternTemplate(row.pattern)}</div>+ {(row.match_regex || row.match_literal) && (+ <LemonButton+ type="secondary"+ size="xsmall"+ onClick={() => onViewMatchingLogs(row)}+ tooltip={+ row.match_regex+ ? 'Open the Logs view filtered to lines matching this pattern'+ : 'Open the Logs view filtered to lines containing this pattern’s literal text (pattern match unavailable)'+ }+ data-attr="logs-pattern-view-matching"+ >+ View matching logs+ </LemonButton>+ )}+ </div><div className="text-muted text-xs">First seen <TZLabel time={row.first_seen} /> · last seen <TZLabel time={row.last_seen} />{row.services.length ? <> · {row.services.join(', ')}</> : null}@@ -130,6 +153,7 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {const { patterns, patternsResponse, patternsResponseLoading, patternsError, sparklineLabels } = useValues(logsPatternsLogic({ id }))+ const { viewMatchingLogs } = useActions(logsPatternsLogic({ id }))const { sampled, scanned_count, total_count, sample_coverage_pct } = patternsResponse// Estimated counts are rounded (not exact-comma-formatted) and prefixed with "~" so a@@ -250,7 +274,7 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {dataSource={patterns}loading={patternsResponseLoading}expandable={{- expandedRowRender: (row) => <PatternExpandedRow row={row} />,+ expandedRowRender: (row) => <PatternExpandedRow row={row} onViewMatchingLogs={viewMatchingLogs} />,}}defaultSorting={{ columnKey: 'estimated_count', order: -1 }}emptyState={diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.tsindex 86e8e067e80c..4fc9abf4cca4 100644--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts@@ -3,6 +3,7 @@ import { expectLogic } from 'kea-test-utils'import { initKeaTests } from '~/test/init'import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'+import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'import { logsPatternsCreate } from 'products/logs/frontend/generated/api'import type { _LogsPatternsResponseApi } from 'products/logs/frontend/generated/api.schemas'@@ -30,9 +31,13 @@ const RESPONSE: _LogsPatternsResponseApi = {first_seen: '2026-06-23T12:00:00+00:00',last_seen: '2026-06-23T12:05:00+00:00',examples: [],- services: ['auth'],+ services: ['auth', 'api'],sparkline: [1, 2],- severity_counts: { error: 3 },+ severity_counts: { error: 2, warn: 1 },+ match_regex: '^\\s*User\\s+\\S+\\s+not\\s+found\\s*$',+ // The miner's `extract_match_literal` returns the longest run between `<*>` holes —+ // for 'User <*> not found' that's 'not found', not 'User'. Keep the fixture faithful.+ match_literal: 'not found',},],scanned_count: 3,@@ -73,6 +78,63 @@ describe('logsPatternsLogic', () => {)})+ it('viewMatchingLogs writes a visible message filter and switches to the Logs view', async () => {+ // The pivot's contract: the predicate must land in the shared, user-visible filterGroup+ // (removable like any filter, never hidden state) and the viewer must leave Patterns mode.+ const configLogic = logsViewerConfigLogic({ id: ID })+ configLogic.mount()+ configLogic.actions.setViewMode('patterns')+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPatternsSuccess'])++ logic.actions.viewMatchingLogs(RESPONSE.patterns[0])++ const inner = filtersLogic.values.filters.filterGroup.values[0] as UniversalFiltersGroup+ expect(inner.values).toContainEqual(+ expect.objectContaining({+ key: 'message',+ operator: PropertyOperator.Regex,+ type: PropertyFilterType.Log,+ value: RESPONSE.patterns[0].match_regex,+ })+ )+ // The pivot also scopes by everything the sample saw — service_name and severity+ // prune the scan the body regex can't, and multi-value IN filters narrow just as well.+ expect(filtersLogic.values.filters.serviceNames).toEqual(['auth', 'api'])+ expect(filtersLogic.values.filters.severityLevels).toEqual(['error', 'warn'])+ expect(configLogic.values.viewMode).toBe('logs')++ // A filter that could silently exclude matching lines must be withheld: a services+ // list at the miner's cap may be truncated, and a non-canonical severity ("notice")+ // can't be expressed as a severity filter. Both leave the previous values untouched.+ logic.actions.viewMatchingLogs({+ ...RESPONSE.patterns[0],+ services: ['auth', 'api', 'db', 'kafka'],+ severity_counts: { error: 2, notice: 1 },+ })+ expect(filtersLogic.values.filters.serviceNames).toEqual(['auth', 'api'])+ expect(filtersLogic.values.filters.severityLevels).toEqual(['error', 'warn'])+ })++ it('viewMatchingLogs falls back to an icontains literal filter when the regex was withheld', async () => {+ // Validation can withhold the regex (match_regex: null); the pivot must still scope the+ // Logs view using the template's longest literal run with icontains, not a regex match.+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPatternsSuccess'])++ logic.actions.viewMatchingLogs({ ...RESPONSE.patterns[0], match_regex: null })++ const inner = filtersLogic.values.filters.filterGroup.values[0] as UniversalFiltersGroup+ expect(inner.values).toContainEqual(+ expect.objectContaining({+ key: 'message',+ operator: PropertyOperator.IContains,+ type: PropertyFilterType.Log,+ value: RESPONSE.patterns[0].match_literal,+ })+ )+ })+it('surfaces a load failure as patternsError and clears it on the next success', async () => {// A failed mine (e.g. sampling query over budget) must not render as "no patterns".mockCreate.mockRejectedValueOnce(new Error('estimated query execution time is too long'))@@ -88,6 +150,10 @@ describe('logsPatternsLogic', () => {})it('reloads when a shared filter changes', async () => {+ // Mining only re-runs while Patterns is the active view (the logic is mounted only then).+ const configLogic = logsViewerConfigLogic({ id: ID })+ configLogic.mount()+ configLogic.actions.setViewMode('patterns')logic.mount()await expectLogic(logic).toDispatchActions(['loadPatternsSuccess'])mockCreate.mockClear()diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.tsindex f54c14544da3..b4aac937a293 100644--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts@@ -1,9 +1,19 @@-import { afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { dayjs } from 'lib/dayjs'import { teamLogic } from 'scenes/teamLogic'+import type { LogsQuery } from '~/queries/schema/schema-general'+import {+ FilterLogicalOperator,+ LogPropertyFilter,+ PropertyFilterType,+ PropertyOperator,+ UniversalFiltersGroup,+} from '~/types'++import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'import { logsPatternsCreate } from 'products/logs/frontend/generated/api'import type {@@ -18,6 +28,15 @@ export interface LogsPatternsLogicProps {id: string}+// The severity filter is an exact match on these six buckets; a sampled severity outside them+// (e.g. "notice") can't be expressed, so applying the filter would silently exclude those lines.+const CANONICAL_SEVERITIES = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']++// Mirrors the miner's LOGS_PATTERNS_MAX_SERVICES default: a services list this long may have+// been truncated at the cap, so filtering by it could exclude services the pattern also hits.+// severity_counts has no cap, so it never needs this guard.+const SERVICES_LIST_CAP = 4+const EMPTY_RESPONSE: _LogsPatternsResponseApi = {patterns: [],scanned_count: 0,@@ -41,6 +60,8 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([['currentTeamId'],logsViewerFiltersLogic({ id: props.id }),['filters', 'utcDateRange', 'queryFilterGroup'],+ logsViewerConfigLogic({ id: props.id }),+ ['viewMode'],],actions: [logsViewerFiltersLogic({ id: props.id }),@@ -54,9 +75,15 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>(['setFilterGroup','setPinnedFilters',],+ logsViewerConfigLogic({ id: props.id }),+ ['setViewMode'],],})),+ actions({+ viewMatchingLogs: (pattern: _LogPatternApi) => ({ pattern }),+ }),+loaders(({ values }) => ({patternsResponse: [EMPTY_RESPONSE,@@ -115,10 +142,17 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([],}),- listeners(({ actions }) => {+ listeners(({ actions, values }) => {// Debounced so a multi-filter change or search typing collapses into one request —- // kea's breakpoint cancels superseded loads before the fetch fires.- const reload = (): void => actions.loadPatterns(300)+ // kea's breakpoint cancels superseded loads before the fetch fires. Only mine while+ // Patterns is the active view: the pivot below flips to Logs mode before writing its+ // filter, so its own `setFilterGroup` (and any deferred unmount) can't queue a stray mine.+ const reload = (): void => {+ if (values.viewMode !== 'patterns') {+ return+ }+ actions.loadPatterns(300)+ }return {setDateRange: reload,zoomDateRange: reload,@@ -128,6 +162,65 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([setFilters: reload,setFilterGroup: reload,setPinnedFilters: reload,++ // Pivot to the Logs view scoped to this pattern. The predicate lands in the shared+ // filterGroup like any user-added filter — visible and removable in the filter bar,+ // never hidden state. Prefer the validated regex; fall back to plain-text matching+ // on the template's literal content when validation withheld it.+ viewMatchingLogs: ({ pattern }) => {+ const predicate: LogPropertyFilter | null = pattern.match_regex+ ? {+ key: 'message',+ value: pattern.match_regex,+ operator: PropertyOperator.Regex,+ type: PropertyFilterType.Log,+ }+ : pattern.match_literal+ ? {+ key: 'message',+ value: pattern.match_literal,+ operator: PropertyOperator.IContains,+ type: PropertyFilterType.Log,+ }+ : null+ if (!predicate) {+ return+ }+ const group = values.filters.filterGroup+ const inner = group.values[0] as UniversalFiltersGroup | undefined+ const newGroup: UniversalFiltersGroup =+ inner && Array.isArray(inner.values)+ ? {+ ...group,+ values: [+ { ...inner, values: [...inner.values, predicate] } as UniversalFiltersGroup,+ ...group.values.slice(1),+ ],+ }+ : {+ type: FilterLogicalOperator.And,+ values: [+ { type: FilterLogicalOperator.And, values: [predicate] } as UniversalFiltersGroup,+ ],+ }+ // Leave Patterns mode first so the filter writes below don't re-trigger a mine:+ // the `reload` guard sees Logs mode and bails on our own `setFilterGroup`.+ actions.setViewMode('logs')+ actions.setFilterGroup(newGroup, false)+ // Scope by every service and severity the sample saw: service_name is in the+ // table's sort key and severity is indexed, so these prune the scan the body regex+ // alone can't. Both are IN filters, so N values narrow just as validly as one, and+ // both land as visible chips the user can remove if the pattern exists beyond the+ // sample. Skipped only when the filter could silently exclude matching lines: a+ // cap-truncated services list, or a severity outside the canonical buckets.+ if (pattern.services.length > 0 && pattern.services.length < SERVICES_LIST_CAP) {+ actions.setServiceNames(pattern.services)+ }+ const severities = Object.keys(pattern.severity_counts)+ if (severities.length > 0 && severities.every((s) => CANONICAL_SEVERITIES.includes(s))) {+ actions.setSeverityLevels(severities as LogsQuery['severityLevels'])+ }+ },}}),diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 8de94f5c62ae..f0902356439a 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1112,6 +1112,16 @@ export interface _LogPatternApi {sparkline: number[]/** Sampled occurrences keyed by lowercased severity ("trace" through "fatal"). Raw sample counts, not extrapolated — severity dominance is a proportion, so scaling would not change it. */severity_counts: _LogPatternApiSeverityCounts+ /**+ * RE2-safe regex over raw log bodies that matches lines of this pattern, compiled from the template and validated against the pattern's own examples before being offered. Null when the template lacks literal content or validation failed — never trust an unvalidated predicate. Use with the message/regex log property filter.+ * @nullable+ */+ match_regex: string | null+ /**+ * Longest literal run in the template, for plain-text (icontains) filtering when `match_regex` is null. Null when the template has no usable literal content.+ * @nullable+ */+ match_literal: string | null}export interface _LogsPatternsSparklineBucketApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 617e363fc05b..ebe40c7c7e77 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -55395,6 +55395,16 @@ export namespace Schemas {sparkline: number[];/** Sampled occurrences keyed by lowercased severity ("trace" through "fatal"). Raw sample counts, not extrapolated — severity dominance is a proportion, so scaling would not change it. */severity_counts: _LogPatternSeverityCounts;+ /**+ * RE2-safe regex over raw log bodies that matches lines of this pattern, compiled from the template and validated against the pattern's own examples before being offered. Null when the template lacks literal content or validation failed — never trust an unvalidated predicate. Use with the message/regex log property filter.+ * @nullable+ */+ match_regex: string | null;+ /**+ * Longest literal run in the template, for plain-text (icontains) filtering when `match_regex` is null. Null when the template has no usable literal content.+ * @nullable+ */+ match_literal: string | null;}/**