Skip to content

: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.

feat(logs): mine the message field of JSON log bodies (#69889)

Jon McCallum65443153b43b
diff --git a/posthog/test/dataclass_frozen_baseline.txt b/posthog/test/dataclass_frozen_baseline.txt
index b877e31fada8..a79a0d24a5fb 100644
--- a/posthog/test/dataclass_frozen_baseline.txt
+++ b/posthog/test/dataclass_frozen_baseline.txt
@@ -1447,7 +1447,6 @@
2 products/experiments/stats/shared/cuped.py
2 products/growth/backend/product_push/service.py
2 products/growth/dags/user_product_list.py
-2 products/logs/backend/log_patterns.py
2 products/managed_warehouse/backend/facade/contracts.py
2 products/managed_warehouse/backend/temporal/types.py
2 products/marketing_analytics/backend/demo/events.py
diff --git a/products/logs/backend/log_patterns.py b/products/logs/backend/log_patterns.py
index ebb3dbadeefc..ac03e74f66fd 100644
--- a/products/logs/backend/log_patterns.py
+++ b/products/logs/backend/log_patterns.py
@@ -1,5 +1,6 @@
import os
import re
+import json
import datetime as dt
from bisect import bisect_right
from collections.abc import Callable
@@ -138,7 +139,7 @@ class LogSample:
truncated: bool = False
-@dataclass
+@dataclass(frozen=True)
class MinedPattern:
pattern: str
count: int
@@ -154,14 +155,16 @@ 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.
+ # RE2-safe regex over raw bodies, self-validated against the raw bodies of the sampled
+ # example rows (not the prepared `examples` — raw lines are what the predicate executes
+ # against in ClickHouse); 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
+@dataclass(frozen=False)
class _Accumulator:
template: str
first_seen: dt.datetime
@@ -171,6 +174,15 @@ class _Accumulator:
# dropped before it lands there, and the end anchor must still come off.
truncated: bool = False
examples: list[LogSample] = field(default_factory=list)
+ # Raw bodies for the same sampled rows as `examples` — the validation corpus for the
+ # match predicates, which execute against raw lines in ClickHouse. Prepared bodies can't
+ # play that role once JSON reduction exists: an extracted message is a *substring* of its
+ # raw line, so a predicate can match every prepared example yet zero raw rows.
+ raw_examples: list[str] = field(default_factory=list)
+ # True only while every raw example above was mined from the message field of a JSON body,
+ # which is what licenses the unanchored predicate. One prose row merging into the cluster
+ # turns it off. See compile_match_regex.
+ raw_examples_from_json: bool = True
services: list[str] = field(default_factory=list)
bucket_counts: list[int] = field(default_factory=list)
severity_counts: dict[str, int] = field(default_factory=dict)
@@ -180,21 +192,79 @@ class _Accumulator:
class _PreparedBody:
text: str
truncated: bool
+ # True when `text` is a message field lifted out of a JSON body, so it is a substring of the
+ # raw line rather than the whole of it. Recorded here because the miner already parsed the
+ # body to find out — compile_match_regex needs the same answer, and re-deriving it there
+ # would parse every retained example a second time.
+ from_json: bool
+
+
+# Keys checked (in order) for the human-readable message inside a JSON body. Matches Loki's
+# pattern-ingester default list plus "event" (structlog's convention); Datadog's JSON
+# preprocessing remaps the same core keys (message/msg/log) to the log body.
+_JSON_MESSAGE_KEYS = ("message", "msg", "log", "msg_", "_msg", "content", "event")
+
+# Raw example bodies (the predicate validation corpus) are kept at a multiple of the mining
+# truncation cap: long enough that predicates over truncated templates still validate against
+# realistic raw lines, bounded so a pathological row can't blow up memory.
+_RAW_EXAMPLE_CAP_MULTIPLIER = 4
+
+
+def _prepare_json_body(body: str) -> str | None:
+ """Return the message-like field of a JSON log body, or None when there is no such field.
+
+ Drain tokenizes on spaces, so a raw JSON blob is punctuation-glued junk: values sit fused
+ to keys and braces where the masking regexes can't isolate them, and every value is
+ high-cardinality. The industry norm (Loki's pattern ingester, Datadog's JSON preprocessing,
+ Elastic's categorization) is to mine only the message-like field.
+
+ A body carrying no such field falls through to prose mining rather than being rewritten
+ into a canonical shape. Mining a rewritten body produces a template describing text that
+ appears nowhere in the raw row, so compile_match_regex and extract_match_literal must both
+ withhold a predicate, and the pattern cannot be pivoted to the logs behind it. An extracted
+ message is exempt because it is a literal substring of the raw row, which is what the
+ unanchored variant in compile_match_regex matches against.
+ """
+ # Shippers (Fluentd, Vector, Docker's json-file driver) sometimes deliver a BOM or
+ # leading whitespace before the object — that must not demote the body to prose mining.
+ body = body.lstrip(" \t\r\n")
+ if not body.startswith("{"):
+ return None
+ try:
+ parsed = json.loads(body)
+ # ValueError rather than JSONDecodeError, which subclasses it. A log producer controls the
+ # body, and an integer literal past sys.get_int_max_str_digits() raises a plain ValueError
+ # from the number parser, which would otherwise fail the whole patterns request with a 500.
+ except (ValueError, RecursionError):
+ return None
+ if not isinstance(parsed, dict):
+ return None
+
+ for key in _JSON_MESSAGE_KEYS:
+ value = parsed.get(key)
+ if isinstance(value, str) and value.strip():
+ return value
+
+ return None
def _prepare_body(body: str, truncate: int) -> _PreparedBody:
- # Collapse newlines / whitespace runs so multi-line bodies (stack traces) mine as a
- # single line, then bound length to keep Drain's parse tree and memory in check.
- collapsed = _WHITESPACE_RE.sub(" ", body).strip()
+ # A JSON body carrying a message field is reduced to it (see _prepare_json_body); every
+ # other body, JSON or prose, passes through unchanged.
+ # Then collapse newlines / whitespace runs so multi-line bodies (stack traces) mine as a
+ # single line, and bound length to keep Drain's parse tree and memory in check.
+ message = _prepare_json_body(body)
+ from_json = message is not None
+ collapsed = _WHITESPACE_RE.sub(" ", body if message is None else message).strip()
if len(collapsed) <= truncate:
- return _PreparedBody(collapsed, truncated=False)
+ return _PreparedBody(collapsed, truncated=False, from_json=from_json)
# Cut back to the last space inside the cap. Drain splits on whitespace, so a mid-word
# cut hands it a fragment ("(Macinto") that it treats as a literal token, and one long
# statement then fragments into a cluster per distinct cut point. A body with no space
# inside the cap has no boundary to cut at, so it still cuts hard.
head = collapsed[:truncate]
boundary = head.rfind(" ")
- return _PreparedBody(head[:boundary] if boundary > 0 else head, truncated=True)
+ return _PreparedBody(head[:boundary] if boundary > 0 else head, truncated=True, from_json=from_json)
def _build_miner(sim_th: float, depth: int, max_clusters: int) -> tuple[LogMasker, Drain]:
@@ -220,14 +290,22 @@ def _literal_runs(template: str) -> list[str]:
return [stripped for literal in _PLACEHOLDER_RE.split(template) if (stripped := literal.strip())]
-def extract_match_literal(template: str) -> str | None:
+def extract_match_literal(template: str, raw_examples: list[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."""
+ compiled regex fails validation. None when the template has no usable literal content,
+ or when the literal doesn't actually appear in the pattern's raw lines (an icontains
+ filter is executed against raw bodies, so a JSON-escaped or shape-token literal that
+ validated against prepared text would silently match nothing)."""
longest = ""
for literal in _literal_runs(template):
if len(literal) > len(longest):
longest = literal
- return longest if len(longest) >= _MIN_LITERAL_CHARS else None
+ if len(longest) < _MIN_LITERAL_CHARS:
+ return None
+ needle = longest.lower()
+ if not raw_examples or not all(needle in raw.lower() for raw in raw_examples):
+ return None
+ return longest
def pattern_fingerprint(template: str) -> str:
@@ -245,20 +323,35 @@ def pattern_fingerprint(template: str) -> str:
return "\x00".join(literals) if literals else template
-def compile_match_regex(template: str, examples: list[LogSample], *, truncated: bool | None = None) -> str | None:
+def compile_match_regex(
+ template: str,
+ examples: list[LogSample],
+ raw_examples: list[str],
+ *,
+ truncated: bool | None = None,
+ mined_from_json: bool = False,
+) -> str | None:
"""Compile a mined template into an RE2-safe regex over raw log bodies, self-validated
- against the pattern's own examples.
+ against the raw bodies of the pattern's own sampled rows.
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 the cluster held a
- truncated body, since the template then only covers a prefix of the raw line.
-
- Pass `truncated` from the cluster. Falling back to the retained examples under-reports it,
- because dedup and the example cap can both drop the truncated body.
+ silently matches the wrong logs is worse than no filter. Validation runs against *raw*
+ bodies because that is what the predicate executes against in ClickHouse. The anchored
+ form is tried first (start-anchored; end anchor dropped when the cluster held a truncated
+ body). An unanchored fallback applies only when `mined_from_json` holds, where the mined
+ message is a substring of its raw row so only the unanchored form can match — prose keeps
+ the strict anchoring guarantee, since an unanchored prose predicate would silently match
+ mid-line occurrences the anchored form was designed to exclude. A template whose content
+ never appears verbatim in the raw lines (canonicalized JSON shapes, messages with
+ JSON-escaped characters) fails validation and is withheld.
+
+ Pass `truncated` and `mined_from_json` from the cluster. Falling back to the retained
+ examples under-reports truncation, because dedup and the example cap can both drop the
+ truncated body, and the miner already knows which rows it extracted a message from, so
+ re-deriving that here would parse every retained raw example a second time.
"""
- if not examples:
+ if not examples or not raw_examples:
return None
literals = _PLACEHOLDER_RE.split(template)
if not any(len(literal.strip()) >= _MIN_LITERAL_CHARS for literal in literals):
@@ -271,20 +364,26 @@ def compile_match_regex(template: str, examples: list[LogSample], *, truncated:
parts.append(_PLACEHOLDER_PATTERNS[match.group(0)])
pos = match.end()
parts.append(_escape_literal(template[pos:]))
+ core = "".join(parts)
if truncated is None:
truncated = any(example.truncated for example in examples)
- candidate = r"^\s*" + "".join(parts) + ("" if truncated else r"\s*$")
-
+ anchored = r"^\s*" + core + ("" if truncated else r"\s*$")
try:
- compiled = re.compile(candidate)
+ anchored_re = re.compile(anchored)
+ core_re = re.compile(core)
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
+ if all(anchored_re.search(raw) for raw in raw_examples):
+ return anchored
+ # The unanchored form is only honest when every raw example is JSON, because the template is
+ # then a substring of each row by construction. A cluster mixing JSON and prose rows would
+ # otherwise get an unanchored predicate on the strength of one JSON row, and that predicate
+ # matches a prose line wherever the text appears, not just where the statement starts. When a
+ # mixed cluster cannot anchor, withholding is the correct outcome.
+ if mined_from_json and all(core_re.search(raw) for raw in raw_examples):
+ return core
+ return None
def _bucket_index(buckets: list[tuple[dt.datetime, dt.datetime]], ts: dt.datetime) -> int | None:
@@ -367,6 +466,10 @@ def mine_patterns(
truncated=prepared.truncated,
)
)
+ # A predicate needing content beyond the cap fails validation and is withheld,
+ # which is fail-safe.
+ acc.raw_examples.append(sample.body[: truncate * _RAW_EXAMPLE_CAP_MULTIPLIER])
+ acc.raw_examples_from_json = acc.raw_examples_from_json and prepared.from_json
if sample.service_name not in acc.services and len(acc.services) < max_services:
acc.services.append(sample.service_name)
if buckets:
@@ -387,8 +490,14 @@ 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, truncated=acc.truncated),
- match_literal=extract_match_literal(acc.template),
+ match_regex=compile_match_regex(
+ acc.template,
+ acc.examples,
+ acc.raw_examples,
+ truncated=acc.truncated,
+ mined_from_json=acc.raw_examples_from_json,
+ ),
+ match_literal=extract_match_literal(acc.template, acc.raw_examples),
)
for acc in accumulators.values()
]
diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.py
index ffed8e85d7a8..ab539edd9180 100644
--- a/products/logs/backend/presentation/views/api.py
+++ b/products/logs/backend/presentation/views/api.py
@@ -766,7 +766,8 @@ class _LogPatternExampleSerializer(serializers.Serializer):
body = serializers.CharField(
help_text=(
"Log body as the miner saw it: whitespace-collapsed and truncated to the mining "
- "length cap, not the raw stored line."
+ "length cap, with the message field extracted from JSON bodies. This is not the "
+ "raw stored line."
),
)
severity_text = serializers.CharField(help_text='Severity of the sampled line, e.g. "info", "error".')
@@ -837,9 +838,10 @@ class _LogPatternSerializer(serializers.Serializer):
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."
+ "the template and validated against the raw bodies of the pattern's own sampled rows "
+ "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(
diff --git a/products/logs/backend/test/test_log_patterns.py b/products/logs/backend/test/test_log_patterns.py
index e30190545632..43b1f06404a4 100644
--- a/products/logs/backend/test/test_log_patterns.py
+++ b/products/logs/backend/test/test_log_patterns.py
@@ -19,6 +19,7 @@ from products.logs.backend.log_patterns import (
_WHITESPACE_RE,
LogSample,
_prepare_body,
+ _prepare_json_body,
compile_match_regex,
extract_match_literal,
mine_patterns,
@@ -398,16 +399,17 @@ class TestMinePatterns(TestCase):
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"))]
+ # match the RAW rows it came from — raw lines are what the predicate executes against
+ # in ClickHouse, and a regex that only matches prepared bodies is exactly the broken
+ # predicate this invariant exists to prevent.
+ bodies = [f"User {name} not found in {i} ms" for i, name in enumerate(("alice", "bob", "carol"))]
- patterns = mine_patterns(samples)
+ patterns = mine_patterns([_sample(body) for body in bodies])
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)
+ for body in bodies:
+ assert compiled.search(body)
@parameterized.expand(
[
@@ -444,6 +446,12 @@ class TestMinePatterns(TestCase):
assert re.search(patterns[0].match_regex, "task_retrying at 2026-08-19T14:02:11.000001Z scheduled")
+def _compile_prose(template: str, bodies: list[str], truncated: bool = False) -> str | None:
+ # Prose logs: the prepared example and the raw line are the same text.
+ samples = [_sample(b, truncated=truncated) for b in bodies]
+ return compile_match_regex(template, samples, bodies, truncated=truncated)
+
+
class TestCompileMatchRegex(TestCase):
@parameterized.expand(
[
@@ -462,7 +470,7 @@ class TestCompileMatchRegex(TestCase):
]
)
def test_compiled_regex_matches_raw_bodies(self, template: str, raw_body: str) -> None:
- regex = compile_match_regex(template, [_sample(raw_body.strip())])
+ regex = _compile_prose(template, [raw_body.strip()])
assert regex is not None
assert re.search(regex, raw_body)
@@ -475,7 +483,7 @@ class TestCompileMatchRegex(TestCase):
]
)
def test_compiled_regex_is_anchored(self, template: str, non_matching_body: str) -> None:
- regex = compile_match_regex(template, [_sample("User dave not found")])
+ regex = _compile_prose(template, ["User dave not found"])
assert regex is not None
assert not re.search(regex, non_matching_body)
@@ -484,7 +492,7 @@ class TestCompileMatchRegex(TestCase):
# 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, truncated=True)])
+ regex = _compile_prose("prefix <*>", [truncated_body], truncated=True)
assert regex is not None
assert re.search(regex, truncated_body + " continues beyond the cap")
@@ -496,18 +504,24 @@ class TestCompileMatchRegex(TestCase):
]
)
def test_templates_without_literal_content_get_no_regex(self, _name: str, template: str) -> None:
- assert compile_match_regex(template, [_sample("anything at all")]) is None
+ assert _compile_prose(template, ["anything at all"]) 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_prose("User <*> not found", ["User dave not found", "something entirely different"]) is None
- assert compile_match_regex("User <*> not found", examples) is None
+ def test_prose_pattern_never_falls_back_to_an_unanchored_regex(self) -> None:
+ # The unanchored fallback exists solely for JSON-extracted messages (substrings of
+ # their raw rows). A prose raw line with surrounding context (e.g. a shipper-prepended
+ # syslog prefix) fails the anchored form and must be withheld — falling back would ship
+ # a predicate matching mid-line occurrences the anchoring guarantee exists to exclude.
+ raws = ["User dave not found", "<13>Jan 1 host app: User bob not found"]
+ assert _compile_prose("User <*> not found", raws) is None
def test_no_examples_means_no_regex(self) -> None:
- assert compile_match_regex("User <*> not found", []) is None
+ assert compile_match_regex("User <*> not found", [], []) is None
@parameterized.expand(
[
@@ -516,7 +530,103 @@ class TestCompileMatchRegex(TestCase):
]
)
def test_extract_match_literal(self, _name: str, template: str, expected: str | None) -> None:
- assert extract_match_literal(template) == expected
+ assert (
+ extract_match_literal(template, [template.replace("<uuid>", "x").replace("<num>", "1").replace("<*>", "y")])
+ == expected
+ )
+
+ def test_extract_match_literal_withheld_when_absent_from_raw_lines(self) -> None:
+ # The icontains filter runs against raw bodies; a literal that only exists in the
+ # prepared form (here: whitespace-collapsed) would silently match nothing.
+ assert extract_match_literal("job done ok", ["job done\n\nok"]) is None
+ assert extract_match_literal("Job Done OK", ["prefix job done ok suffix"]) == "Job Done OK"
+
+
+class TestPrepareJsonBody(TestCase):
+ @parameterized.expand(
+ [
+ ("message_key", '{"message": "User alice not found", "level": "error"}', "User alice not found"),
+ ("leading_whitespace_and_bom", '  {"message": "still json"}', "still json"),
+ ("msg_key", '{"msg": "connection reset", "attempt": 3}', "connection reset"),
+ ("log_key", '{"log": "line from docker", "stream": "stdout"}', "line from docker"),
+ ("event_key", '{"event": "payment failed", "order_id": 12}', "payment failed"),
+ ("priority_order", '{"event": "second choice", "message": "first choice"}', "first choice"),
+ ("not_json", "User alice not found", None),
+ ("json_array", '[{"message": "in a list"}]', None),
+ ("json_scalar_in_braces_invalid", "{not valid json}", None),
+ ("empty_message_is_not_a_message", '{"message": "", "a": 1}', None),
+ ("non_string_message_is_not_a_message", '{"message": 42}', None),
+ ("no_message_key", '{"user_id": 1, "ok": true}', None),
+ # A producer controls the body, and an integer past sys.get_int_max_str_digits()
+ # raises a bare ValueError from the number parser rather than a JSONDecodeError.
+ ("integer_past_the_digit_limit", '{"message": "hi", "n": ' + "9" * 5000 + "}", None),
+ ]
+ )
+ def test_json_body_reduction(self, _name: str, body: str, expected: str | None) -> None:
+ assert _prepare_json_body(body) == expected
+
+
+class TestJsonBodyMining(TestCase):
+ def test_json_bodies_cluster_by_message_and_regex_matches_the_raw_line(self) -> None:
+ # The end-to-end contract for structured logs: mining sees the extracted message (one
+ # template instead of punctuation fragments), while the shipped predicate still matches
+ # the raw JSON rows in ClickHouse — which requires the unanchored compile variant, since
+ # the message is a substring of the raw line.
+ raws = [
+ f'{{"level": "error", "message": "User {name} not found", "request_id": {i}}}'
+ for i, name in enumerate(("alice", "bob", "carol"))
+ ]
+ patterns = mine_patterns([_sample(raw) for raw in raws])
+
+ assert len(patterns) == 1
+ assert patterns[0].pattern == "User <*> not found"
+ assert patterns[0].match_regex is not None
+ compiled = re.compile(patterns[0].match_regex)
+ for raw in raws:
+ assert compiled.search(raw)
+ assert patterns[0].match_literal == "not found"
+
+ def test_a_cluster_mixing_json_and_prose_rows_withholds_the_unanchored_regex(self) -> None:
+ # The unanchored form is only honest when every raw row is JSON, where the template is a
+ # substring by construction. One JSON row among prose rows would otherwise buy the whole
+ # cluster a regex matching a prose line wherever the text appears, not where it starts.
+ rows = [_sample(f'{{"message": "cache miss for key {i}"}}') for i in range(5)]
+ rows += [_sample(f"cache miss for key {i}") for i in range(5, 10)]
+
+ patterns = mine_patterns(rows)
+
+ assert len(patterns) == 1
+ assert patterns[0].match_regex is None
+
+ def test_message_less_json_keeps_a_predicate_that_matches_the_raw_row(self) -> None:
+ # Rewriting these bodies into a canonical shape collapses them into one template, but
+ # that template then describes text absent from the raw row, so every predicate has to
+ # be withheld and the pattern loses the drill-down to its logs. Mining the body
+ # unchanged is what keeps the pivot working.
+ raws = ['{"user_id": 1, "ok": true}', '{"user_id": 22, "ok": true}', '{"user_id": 333, "ok": true}']
+ patterns = mine_patterns([_sample(raw) for raw in raws])
+
+ assert len(patterns) == 1
+ assert patterns[0].match_regex is not None
+ compiled = re.compile(patterns[0].match_regex)
+ for raw in raws:
+ assert compiled.search(raw)
+
+ def test_message_with_json_escaped_content_withholds_the_regex(self) -> None:
+ # The raw row stores the newline as a two-character escape (\n); the extracted message
+ # has a real newline. A predicate validated only against the prepared form would ship
+ # and silently match nothing — raw validation must withhold it.
+ raw = '{"message": "first line\\nsecond line of failure"}'
+ patterns = mine_patterns([_sample(raw)])
+
+ assert patterns[0].match_regex is None
+
+ def test_prose_bodies_are_untouched_by_json_handling(self) -> None:
+ patterns = mine_patterns([_sample("User alice not found"), _sample("User bob not found")])
+
+ assert patterns[0].pattern == "User <*> not found"
+ assert patterns[0].match_regex is not None
+ assert re.match(patterns[0].match_regex, "User carol not found")
_uuid_st = st.tuples(st.uuids(), st.booleans()).map(lambda t: str(t[0]).upper() if t[1] else str(t[0]))
@@ -838,7 +948,10 @@ class TestHostMaskProperties(TestCase):
def test_lines_differing_only_by_hostname_share_a_fingerprint(self, host_a: str, host_b: str) -> None:
# This is what the mask is for. The patterns diff and the pattern list both key on
# the fingerprint, so two hostnames that fingerprint apart show up as two templates.
- line = '{{"authority":"{}","upstream_cluster":"capture"}}'
+ # The host sits in the message field: a JSON body with no message-like field is
+ # canonicalized to its shape, which fingerprints identically whatever the host is and
+ # would let an over-narrow host mask through.
+ line = '{{"message":"upstream {} refused","upstream_cluster":"capture"}}'
a = mine_patterns([_sample(line.format(host_a))])
b = mine_patterns([_sample(line.format(host_b))])
@@ -914,7 +1027,9 @@ class TestTruncationProperties(TestCase):
@given(body=st.one_of(_log_body_st(), _long_log_body_st()), cap=st.integers(min_value=8, max_value=600))
@settings(max_examples=400, deadline=None)
def test_prepared_body_holds_only_whole_tokens(self, body: str, cap: int) -> None:
- collapsed = _WHITESPACE_RE.sub(" ", body).strip()
+ # A JSON body is reduced to its message-like field before collapsing, so the baseline
+ # the prefix is measured against is the reduced body, not the raw line.
+ collapsed = _WHITESPACE_RE.sub(" ", _prepare_json_body(body) or body).strip()
prepared = _prepare_body(body, cap)
diff --git a/products/logs/backend/test/test_log_patterns_pbt.py b/products/logs/backend/test/test_log_patterns_pbt.py
new file mode 100644
index 000000000000..228bd46984d5
--- /dev/null
+++ b/products/logs/backend/test/test_log_patterns_pbt.py
@@ -0,0 +1,96 @@
+import re
+import json
+import datetime as dt
+from typing import Literal
+
+from unittest import TestCase
+
+from hypothesis import (
+ HealthCheck,
+ example,
+ given,
+ settings,
+ strategies as st,
+)
+
+from products.logs.backend.log_patterns import LogSample, _prepare_json_body, mine_patterns
+
+# PostHog CI runs the backend suite with pytest-rerunfailures (--reruns 2). A rerun
+# re-instantiates the TestCase, so a genuinely-failing @given method is re-invoked from a
+# fresh instance, which trips hypothesis's differing_executors health check and masks the
+# real falsifying example. These tests are pure functions with no shared state, so
+# cross-instance reruns are benign - suppress the check so a regression surfaces its
+# falsifying example.
+_SUPPRESSED_HEALTH_CHECKS = [HealthCheck.differing_executors]
+
+_TS = dt.datetime(2026, 6, 23, 12, 0, 0, tzinfo=dt.UTC)
+
+
+def _samples(bodies: list[str]) -> list[LogSample]:
+ return [LogSample(body=body, severity_text="info", service_name="api", timestamp=_TS) for body in bodies]
+
+
+# Surrogates ("Cs") can't be UTF-8 encoded; exclude them explicitly to keep intent clear.
+# Annotated so mypy sees the literal category name rather than a widened `str`.
+_EXCLUDE_CATEGORIES: tuple[Literal["Cs"]] = ("Cs",)
+
+# Log bodies are arbitrary user-controlled text. Include the mining placeholder vocabulary
+# and regex metacharacters in the alphabet so generated bodies can collide with the miner's
+# own tokens ("<num>", "<*>") - the injection-shaped inputs example tables never enumerate.
+_body_text = st.text(
+ alphabet=st.one_of(
+ st.characters(codec="utf-8", exclude_categories=_EXCLUDE_CATEGORIES),
+ st.sampled_from(list('<>*nums."\\^$()[]{}+?|')),
+ ),
+ max_size=200,
+)
+
+_json_scalars = st.one_of(st.none(), st.booleans(), st.integers(), st.floats(allow_nan=False), st.text(max_size=30))
+_json_values = st.one_of(
+ _json_scalars,
+ st.lists(_json_scalars, max_size=3),
+ st.dictionaries(st.text(min_size=1, max_size=15), _json_scalars, max_size=3),
+)
+_json_objects = st.dictionaries(st.text(min_size=1, max_size=15), _json_values, min_size=1, max_size=6)
+
+
+class TestLogPatternsProperties(TestCase):
+ @given(bodies=st.lists(_body_text, min_size=1, max_size=8))
+ @settings(max_examples=200, deadline=None, suppress_health_check=_SUPPRESSED_HEALTH_CHECKS)
+ def test_mining_arbitrary_bodies_never_raises_and_respects_the_length_cap(self, bodies: list[str]) -> None:
+ patterns = mine_patterns(_samples(bodies), max_patterns=50)
+
+ assert len(patterns) <= 50
+ for pattern in patterns:
+ for kept in pattern.examples:
+ assert len(kept.body) <= 512
+
+ # Pinned adversarial inputs: log content that collides with the miner's own placeholder
+ # vocabulary must never yield a predicate that matches nothing (the template's "<num>" is
+ # compiled as \d+ while the raw line holds the literal text - validation must withhold it).
+ @example(bodies=["literal <num> in a log line", "literal <num> in a log line again"])
+ @example(bodies=["wildcard <*> live in body text"])
+ @example(bodies=['{"message": "user <uuid> said hi"}'])
+ @given(bodies=st.lists(_body_text, min_size=1, max_size=8))
+ @settings(max_examples=200, deadline=None, suppress_health_check=_SUPPRESSED_HEALTH_CHECKS)
+ def test_shipped_predicates_match_the_raw_bodies_they_were_mined_from(self, bodies: list[str]) -> None:
+ # The contract the "view matching logs" pivot rests on: a predicate is only offered if
+ # it matches the raw rows it came from, no matter what the bodies contain - including
+ # text that collides with the placeholder vocabulary or regex metacharacters. From
+ # outside we can't see which input rows fed which cluster, so the property asserts the
+ # implied form - some raw input matches; a shipped predicate matching zero inputs is
+ # exactly the "filters to nothing in ClickHouse" bug.
+ for pattern in mine_patterns(_samples(bodies)):
+ if pattern.match_regex is not None:
+ compiled = re.compile(pattern.match_regex)
+ assert any(compiled.search(body) for body in bodies)
+ if pattern.match_literal is not None:
+ needle = pattern.match_literal.lower()
+ assert any(needle in body.lower() for body in bodies)
+
+ @given(obj=_json_objects, message=st.text(min_size=1, max_size=100).filter(lambda s: s.strip()))
+ @settings(max_examples=200, deadline=None, suppress_health_check=_SUPPRESSED_HEALTH_CHECKS)
+ def test_message_extraction_returns_the_message_verbatim(self, obj: dict, message: str) -> None:
+ obj["message"] = message
+
+ assert _prepare_json_body(json.dumps(obj)) == message
diff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx
index de5423465779..a49a3167fafd 100644
--- a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx
+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx
@@ -124,7 +124,8 @@ function PatternExpandedRow({
))}
</div>
<div className="text-muted text-xs">
- Examples are sampled lines, shown as mined (whitespace-collapsed and truncated).
+ Examples are sampled lines, shown as mined: whitespace-collapsed and truncated, with the message
+ field extracted from JSON bodies.
</div>
</>
) : (
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index be1bc2642c3c..2b18aae2dc30 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1557,7 +1557,7 @@ export interface _LogsPatternsRequestApi {
}
export interface _LogPatternExampleApi {
- /** Log body as the miner saw it: whitespace-collapsed and truncated to the mining length cap, not the raw stored line. */
+ /** Log body as the miner saw it: whitespace-collapsed and truncated to the mining length cap, with the message field extracted from JSON bodies. This is not the raw stored line. */
body: string
/** Severity of the sampled line, e.g. "info", "error". */
severity_text: string
@@ -1598,7 +1598,7 @@ export interface _LogPatternApi {
/** 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.
+ * RE2-safe regex over raw log bodies that matches lines of this pattern, compiled from the template and validated against the raw bodies of the pattern's own sampled rows 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
diff --git a/products/logs/mcp/prompts/logs-patterns.md b/products/logs/mcp/prompts/logs-patterns.md
index ed8b6c0b8a13..9205b3a20293 100644
--- a/products/logs/mcp/prompts/logs-patterns.md
+++ b/products/logs/mcp/prompts/logs-patterns.md
@@ -24,7 +24,7 @@ All parameters must be nested inside a `query` object.
- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.
- `severity_counts` — sampled occurrences per severity. A template split across `info` and `error` often means the same code path logging both outcomes.
- `services` — up to 4 service names the pattern was seen in.
-- `match_regex` — a regex over raw log bodies that matches this pattern's lines, pre-validated against the pattern's own sampled lines. Null when no trustworthy regex could be compiled.
+- `match_regex` — a regex over raw log bodies that matches this pattern's lines, pre-validated against the raw bodies of the pattern's own sampled rows. Null when no trustworthy regex could be compiled. For JSON logs the pattern is mined from the extracted message field, so the regex may be unanchored, because the message is a substring of the raw line. It still targets the raw stored body.
- `match_literal` — longest literal run of the template, a plain-text fallback when `match_regex` is null.
Mining samples the window (`sampled: true` when it did): counts are estimates, and rare patterns (below roughly 1 in `scanned_count` of the volume) may be missing entirely. Narrow the `dateRange` or filters to mine a finer-grained sample.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 2e64c74db54e..fd3d9e21ee11 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6441,7 +6441,7 @@
}
},
"logs-patterns": {
- "description": "Mine recurring log templates (\"patterns\") from the logs matching a filter set, ordered by frequency. Each pattern is a message template with the variable parts masked — e.g. `Connected to <ip> in <num>ms` — plus occurrence estimates, severity mix, the services it appears in, and a ready-made predicate for fetching its matching lines.\n\nThis is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- To triage an unfamiliar or noisy stream: mine the last hour, scan the top templates by `estimated_count`, and look for anything with a non-zero error share in `severity_counts`.\n- To find what's new or dominant during an incident window: mine with `severityLevels: [\"error\", \"fatal\"]` and a `dateRange` covering the incident.\n- As the entry point of a drill-down loop: mine → pick a suspicious pattern → filter logs to exactly its lines using `match_regex` (see below) → read the raw rows with `query-logs`.\n- To quantify repetition before proposing log sampling or cleanup: `volume_share_pct` tells you how much of the stream one template accounts for.\n\n## Pick the right tool\n\n- Raw log lines matching a filter → `query-logs`.\n- A single number (how many logs match) → `logs-count`; per-time-bucket counts → `logs-count-ranges`.\n- Distribution of a dimension (which services emit the errors?) → `logs-facet-values-create`.\n- Use **this** tool to summarize message _content_ — what distinct things the logs say and how often.\n\n# Reading the response\n\n- `pattern` — the mined template. Masked tokens: `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — sampled occurrences per severity. A template split across `info` and `error` often means the same code path logging both outcomes.\n- `services` — up to 4 service names the pattern was seen in.\n- `match_regex` — a regex over raw log bodies that matches this pattern's lines, pre-validated against the pattern's own sampled lines. Null when no trustworthy regex could be compiled.\n- `match_literal` — longest literal run of the template, a plain-text fallback when `match_regex` is null.\n\nMining samples the window (`sampled: true` when it did): counts are estimates, and rare patterns (below roughly 1 in `scanned_count` of the volume) may be missing entirely. Narrow the `dateRange` or filters to mine a finer-grained sample.\n\n## Pivoting to a pattern's raw lines\n\nTo fetch the lines behind a pattern, call `query-logs` with a message filter in `filterGroup`:\n\n- If `match_regex` is set: `{ \"key\": \"message\", \"value\": \"<match_regex>\", \"operator\": \"regex\", \"type\": \"log\" }`\n- Else if `match_literal` is set: `{ \"key\": \"message\", \"value\": \"<match_literal>\", \"operator\": \"icontains\", \"type\": \"log\" }`\n\nAlso pass the pattern's `services` as `serviceNames` and (when every entry is one of trace/debug/info/warn/error/fatal) the keys of `severity_counts` as `severityLevels` — both make the query dramatically cheaper.\n\n# Parameters\n\n## query.dateRange\n\nDate range to mine. Defaults to the last hour (`-1h`).\n\n- `date_from`: ISO 8601 timestamp or relative format: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: Same format. Omit or null for \"now\".\n\n## query.severityLevels\n\nMine only these severities: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.serviceNames\n\nRestrict mining to these services. Recommended once you know the target service — it prunes the scan and spends the whole sample budget on one service's templates.\n\n## query.searchTerm\n\nFull-text search over log bodies applied before mining. Useful to mine only the sub-stream around a keyword (e.g. `timeout`).\n\n## query.filterGroup\n\nProperty filters applied before mining. Same format as `query-logs` filters.\n\n# Examples\n\n## What is this stream saying? (last hour, everything)\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n## Dominant error templates during an incident\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"2024-01-15T09:00:00Z\", \"date_to\": \"2024-01-15T11:00:00Z\" }\n }\n}\n```\n\n## Mine one service's logs around a keyword\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"checkout\"],\n \"searchTerm\": \"payment\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```",
+ "description": "Mine recurring log templates (\"patterns\") from the logs matching a filter set, ordered by frequency. Each pattern is a message template with the variable parts masked — e.g. `Connected to <ip> in <num>ms` — plus occurrence estimates, severity mix, the services it appears in, and a ready-made predicate for fetching its matching lines.\n\nThis is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- To triage an unfamiliar or noisy stream: mine the last hour, scan the top templates by `estimated_count`, and look for anything with a non-zero error share in `severity_counts`.\n- To find what's new or dominant during an incident window: mine with `severityLevels: [\"error\", \"fatal\"]` and a `dateRange` covering the incident.\n- As the entry point of a drill-down loop: mine → pick a suspicious pattern → filter logs to exactly its lines using `match_regex` (see below) → read the raw rows with `query-logs`.\n- To quantify repetition before proposing log sampling or cleanup: `volume_share_pct` tells you how much of the stream one template accounts for.\n\n## Pick the right tool\n\n- Raw log lines matching a filter → `query-logs`.\n- A single number (how many logs match) → `logs-count`; per-time-bucket counts → `logs-count-ranges`.\n- Distribution of a dimension (which services emit the errors?) → `logs-facet-values-create`.\n- Use **this** tool to summarize message _content_ — what distinct things the logs say and how often.\n\n# Reading the response\n\n- `pattern` — the mined template. Masked tokens: `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — sampled occurrences per severity. A template split across `info` and `error` often means the same code path logging both outcomes.\n- `services` — up to 4 service names the pattern was seen in.\n- `match_regex` — a regex over raw log bodies that matches this pattern's lines, pre-validated against the raw bodies of the pattern's own sampled rows. Null when no trustworthy regex could be compiled. For JSON logs the pattern is mined from the extracted message field, so the regex may be unanchored, because the message is a substring of the raw line. It still targets the raw stored body.\n- `match_literal` — longest literal run of the template, a plain-text fallback when `match_regex` is null.\n\nMining samples the window (`sampled: true` when it did): counts are estimates, and rare patterns (below roughly 1 in `scanned_count` of the volume) may be missing entirely. Narrow the `dateRange` or filters to mine a finer-grained sample.\n\n## Pivoting to a pattern's raw lines\n\nTo fetch the lines behind a pattern, call `query-logs` with a message filter in `filterGroup`:\n\n- If `match_regex` is set: `{ \"key\": \"message\", \"value\": \"<match_regex>\", \"operator\": \"regex\", \"type\": \"log\" }`\n- Else if `match_literal` is set: `{ \"key\": \"message\", \"value\": \"<match_literal>\", \"operator\": \"icontains\", \"type\": \"log\" }`\n\nAlso pass the pattern's `services` as `serviceNames` and (when every entry is one of trace/debug/info/warn/error/fatal) the keys of `severity_counts` as `severityLevels` — both make the query dramatically cheaper.\n\n# Parameters\n\n## query.dateRange\n\nDate range to mine. Defaults to the last hour (`-1h`).\n\n- `date_from`: ISO 8601 timestamp or relative format: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: Same format. Omit or null for \"now\".\n\n## query.severityLevels\n\nMine only these severities: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.serviceNames\n\nRestrict mining to these services. Recommended once you know the target service — it prunes the scan and spends the whole sample budget on one service's templates.\n\n## query.searchTerm\n\nFull-text search over log bodies applied before mining. Useful to mine only the sub-stream around a keyword (e.g. `timeout`).\n\n## query.filterGroup\n\nProperty filters applied before mining. Same format as `query-logs` filters.\n\n# Examples\n\n## What is this stream saying? (last hour, everything)\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n## Dominant error templates during an incident\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"2024-01-15T09:00:00Z\", \"date_to\": \"2024-01-15T11:00:00Z\" }\n }\n}\n```\n\n## Mine one service's logs around a keyword\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"checkout\"],\n \"searchTerm\": \"payment\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```",
"category": "Logs",
"feature": "logs",
"summary": "Mine log patterns",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 6c7801f5f58a..e6a104a24826 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6806,7 +6806,7 @@
}
},
"logs-patterns": {
- "description": "Mine recurring log templates (\"patterns\") from the logs matching a filter set, ordered by frequency. Each pattern is a message template with the variable parts masked — e.g. `Connected to <ip> in <num>ms` — plus occurrence estimates, severity mix, the services it appears in, and a ready-made predicate for fetching its matching lines.\n\nThis is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- To triage an unfamiliar or noisy stream: mine the last hour, scan the top templates by `estimated_count`, and look for anything with a non-zero error share in `severity_counts`.\n- To find what's new or dominant during an incident window: mine with `severityLevels: [\"error\", \"fatal\"]` and a `dateRange` covering the incident.\n- As the entry point of a drill-down loop: mine → pick a suspicious pattern → filter logs to exactly its lines using `match_regex` (see below) → read the raw rows with `query-logs`.\n- To quantify repetition before proposing log sampling or cleanup: `volume_share_pct` tells you how much of the stream one template accounts for.\n\n## Pick the right tool\n\n- Raw log lines matching a filter → `query-logs`.\n- A single number (how many logs match) → `logs-count`; per-time-bucket counts → `logs-count-ranges`.\n- Distribution of a dimension (which services emit the errors?) → `logs-facet-values-create`.\n- Use **this** tool to summarize message _content_ — what distinct things the logs say and how often.\n\n# Reading the response\n\n- `pattern` — the mined template. Masked tokens: `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — sampled occurrences per severity. A template split across `info` and `error` often means the same code path logging both outcomes.\n- `services` — up to 4 service names the pattern was seen in.\n- `match_regex` — a regex over raw log bodies that matches this pattern's lines, pre-validated against the pattern's own sampled lines. Null when no trustworthy regex could be compiled.\n- `match_literal` — longest literal run of the template, a plain-text fallback when `match_regex` is null.\n\nMining samples the window (`sampled: true` when it did): counts are estimates, and rare patterns (below roughly 1 in `scanned_count` of the volume) may be missing entirely. Narrow the `dateRange` or filters to mine a finer-grained sample.\n\n## Pivoting to a pattern's raw lines\n\nTo fetch the lines behind a pattern, call `query-logs` with a message filter in `filterGroup`:\n\n- If `match_regex` is set: `{ \"key\": \"message\", \"value\": \"<match_regex>\", \"operator\": \"regex\", \"type\": \"log\" }`\n- Else if `match_literal` is set: `{ \"key\": \"message\", \"value\": \"<match_literal>\", \"operator\": \"icontains\", \"type\": \"log\" }`\n\nAlso pass the pattern's `services` as `serviceNames` and (when every entry is one of trace/debug/info/warn/error/fatal) the keys of `severity_counts` as `severityLevels` — both make the query dramatically cheaper.\n\n# Parameters\n\n## query.dateRange\n\nDate range to mine. Defaults to the last hour (`-1h`).\n\n- `date_from`: ISO 8601 timestamp or relative format: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: Same format. Omit or null for \"now\".\n\n## query.severityLevels\n\nMine only these severities: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.serviceNames\n\nRestrict mining to these services. Recommended once you know the target service — it prunes the scan and spends the whole sample budget on one service's templates.\n\n## query.searchTerm\n\nFull-text search over log bodies applied before mining. Useful to mine only the sub-stream around a keyword (e.g. `timeout`).\n\n## query.filterGroup\n\nProperty filters applied before mining. Same format as `query-logs` filters.\n\n# Examples\n\n## What is this stream saying? (last hour, everything)\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n## Dominant error templates during an incident\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"2024-01-15T09:00:00Z\", \"date_to\": \"2024-01-15T11:00:00Z\" }\n }\n}\n```\n\n## Mine one service's logs around a keyword\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"checkout\"],\n \"searchTerm\": \"payment\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```",
+ "description": "Mine recurring log templates (\"patterns\") from the logs matching a filter set, ordered by frequency. Each pattern is a message template with the variable parts masked — e.g. `Connected to <ip> in <num>ms` — plus occurrence estimates, severity mix, the services it appears in, and a ready-made predicate for fetching its matching lines.\n\nThis is the fastest way to understand what a log stream is _saying_ without reading raw rows: one call summarizes millions of lines into at most 200 templates.\n\nAll parameters must be nested inside a `query` object.\n\n# When to use\n\n- To triage an unfamiliar or noisy stream: mine the last hour, scan the top templates by `estimated_count`, and look for anything with a non-zero error share in `severity_counts`.\n- To find what's new or dominant during an incident window: mine with `severityLevels: [\"error\", \"fatal\"]` and a `dateRange` covering the incident.\n- As the entry point of a drill-down loop: mine → pick a suspicious pattern → filter logs to exactly its lines using `match_regex` (see below) → read the raw rows with `query-logs`.\n- To quantify repetition before proposing log sampling or cleanup: `volume_share_pct` tells you how much of the stream one template accounts for.\n\n## Pick the right tool\n\n- Raw log lines matching a filter → `query-logs`.\n- A single number (how many logs match) → `logs-count`; per-time-bucket counts → `logs-count-ranges`.\n- Distribution of a dimension (which services emit the errors?) → `logs-facet-values-create`.\n- Use **this** tool to summarize message _content_ — what distinct things the logs say and how often.\n\n# Reading the response\n\n- `pattern` — the mined template. Masked tokens: `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — sampled occurrences per severity. A template split across `info` and `error` often means the same code path logging both outcomes.\n- `services` — up to 4 service names the pattern was seen in.\n- `match_regex` — a regex over raw log bodies that matches this pattern's lines, pre-validated against the raw bodies of the pattern's own sampled rows. Null when no trustworthy regex could be compiled. For JSON logs the pattern is mined from the extracted message field, so the regex may be unanchored, because the message is a substring of the raw line. It still targets the raw stored body.\n- `match_literal` — longest literal run of the template, a plain-text fallback when `match_regex` is null.\n\nMining samples the window (`sampled: true` when it did): counts are estimates, and rare patterns (below roughly 1 in `scanned_count` of the volume) may be missing entirely. Narrow the `dateRange` or filters to mine a finer-grained sample.\n\n## Pivoting to a pattern's raw lines\n\nTo fetch the lines behind a pattern, call `query-logs` with a message filter in `filterGroup`:\n\n- If `match_regex` is set: `{ \"key\": \"message\", \"value\": \"<match_regex>\", \"operator\": \"regex\", \"type\": \"log\" }`\n- Else if `match_literal` is set: `{ \"key\": \"message\", \"value\": \"<match_literal>\", \"operator\": \"icontains\", \"type\": \"log\" }`\n\nAlso pass the pattern's `services` as `serviceNames` and (when every entry is one of trace/debug/info/warn/error/fatal) the keys of `severity_counts` as `severityLevels` — both make the query dramatically cheaper.\n\n# Parameters\n\n## query.dateRange\n\nDate range to mine. Defaults to the last hour (`-1h`).\n\n- `date_from`: ISO 8601 timestamp or relative format: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: Same format. Omit or null for \"now\".\n\n## query.severityLevels\n\nMine only these severities: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\n## query.serviceNames\n\nRestrict mining to these services. Recommended once you know the target service — it prunes the scan and spends the whole sample budget on one service's templates.\n\n## query.searchTerm\n\nFull-text search over log bodies applied before mining. Useful to mine only the sub-stream around a keyword (e.g. `timeout`).\n\n## query.filterGroup\n\nProperty filters applied before mining. Same format as `query-logs` filters.\n\n# Examples\n\n## What is this stream saying? (last hour, everything)\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\n## Dominant error templates during an incident\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"dateRange\": { \"date_from\": \"2024-01-15T09:00:00Z\", \"date_to\": \"2024-01-15T11:00:00Z\" }\n }\n}\n```\n\n## Mine one service's logs around a keyword\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"checkout\"],\n \"searchTerm\": \"payment\",\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```",
"category": "Logs",
"feature": "logs",
"summary": "Mine log patterns",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 22abd31919c7..1340f786de4c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -80138,7 +80138,7 @@ export namespace Schemas {
export type _LogPatternSeverityCounts = {[key: string]: number};
export interface _LogPatternExample {
- /** Log body as the miner saw it: whitespace-collapsed and truncated to the mining length cap, not the raw stored line. */
+ /** Log body as the miner saw it: whitespace-collapsed and truncated to the mining length cap, with the message field extracted from JSON bodies. This is not the raw stored line. */
body: string;
/** Severity of the sampled line, e.g. "info", "error". */
severity_text: string;
@@ -80174,7 +80174,7 @@ export namespace Schemas {
/** 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.
+ * RE2-safe regex over raw log bodies that matches lines of this pattern, compiled from the template and validated against the raw bodies of the pattern's own sampled rows 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;