: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): gate exact stored-pattern queries behind v2 flag (#96778)
Jon McCallum741b18422866
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 8a2a540eac3a..54ff96e6891f 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -587,6 +587,7 @@ SPECTACULAR_SETTINGS = {"ScannerProviderEnum": "products.replay_vision.backend.models.replay_scanner.ScannerProvider",# Matches replay_vision's VisionAlertState."LogsAlertConfigurationStateEnum": "products.logs.backend.models.LogsAlertConfiguration.State",+ "LogsPatternsSourceEnum": ["stored_patterns", "body_mining"],## The published name is already derived by a different choice set, so the# entry holds this one apart.diff --git a/products/logs/backend/log_patterns.py b/products/logs/backend/log_patterns.pyindex ac03e74f66fd..2472244293e0 100644--- a/products/logs/backend/log_patterns.py+++ b/products/logs/backend/log_patterns.py@@ -4,12 +4,20 @@ import jsonimport datetime as dtfrom bisect import bisect_rightfrom collections.abc import Callable-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom typing import TypeVar+from urllib.parse import quotefrom products.logs.backend.vendor.drain3 import Drain, LogMasker, MaskingInstructionERROR_SEVERITIES = {"error", "fatal"}+STORED_PATTERN_GROUP_MAX_MEMBERS = 50+STORED_PATTERN_GROUP_MAX_BYTES = 3072+++def encoded_pattern_member_size(pattern: str) -> int:+ return len(quote(json.dumps(pattern, ensure_ascii=False), safe="")) + 3+# Masking collapses high-cardinality variable tokens into named placeholders before# clustering, so templates stay readable ("<ip>", "<num>") instead of fragmenting into@@ -147,13 +155,12 @@ class MinedPattern:error_count: intfirst_seen: dt.datetimelast_seen: dt.datetime- # Sampled rows that produced this pattern; `body` is the prepared (whitespace-collapsed,- # truncated) form the miner saw, not the raw log line.+ # Prepared messages for body mining; bounded raw bodies for stored-pattern groups.examples: list[LogSample]services: list[str]- # Raw sample counts per caller-supplied time bucket (empty when no buckets given).+ # Sample or exact counts per caller-supplied time bucket (empty when no buckets given).bucket_counts: list[int]- # Raw sample counts keyed by lowercased severity_text.+ # Sample or exact counts keyed by lowercased severity_text.severity_counts: dict[str, int]# 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@@ -162,6 +169,8 @@ class MinedPattern:match_regex: str | None# Longest literal run in the template — plain-text fallback when match_regex is None.match_literal: str | None+ match_patterns: list[str] = field(default_factory=list)+ pattern_version: int | None = None@dataclass(frozen=False)@@ -405,7 +414,7 @@ def mine_patterns(max_services: int | None = None,buckets: list[tuple[dt.datetime, dt.datetime]] | None = None,) -> list[MinedPattern]:- """Cluster log bodies into templates via Drain3, aggregated per cluster.+ """Cluster masked log bodies into templates via Drain3.Pure function — no ClickHouse or Django. The caller (query runner) is responsiblefor sampling and for the `scanned_count` / `sampled` metadata.@@ -504,3 +513,53 @@ def mine_patterns(# Most frequent first; tie-break on template for deterministic ordering.patterns.sort(key=lambda p: (-p.count, p.pattern))return patterns[:max_patterns]+++def group_stored_patterns(patterns: list[MinedPattern], *, total_count: int) -> list[MinedPattern]:+ """Roll up exact canonical-pattern aggregates without masking or truncating their identities."""+ if not patterns:+ return []+ _, drain = _build_miner(+ _env("LOGS_PATTERNS_SIM_TH", 0.4, float),+ _env("LOGS_PATTERNS_DEPTH", 4, int),+ len(patterns),+ )+ groups: dict[int, MinedPattern] = {}+ group_bytes: dict[int, int] = {}+ max_services = _env("LOGS_PATTERNS_MAX_SERVICES", 4, int)+ for pattern in sorted(patterns, key=lambda pattern: (-pattern.count, pattern.pattern)):+ member_bytes = sum(encoded_pattern_member_size(member) for member in pattern.match_patterns)+ if member_bytes + 3 > STORED_PATTERN_GROUP_MAX_BYTES:+ continue+ cluster, _ = drain.add_log_message(pattern.pattern)+ previous = groups.get(cluster.cluster_id)+ if (len(previous.match_patterns) if previous else 0) + len(+ pattern.match_patterns+ ) > STORED_PATTERN_GROUP_MAX_MEMBERS or group_bytes.get(+ cluster.cluster_id, 3+ ) + member_bytes > STORED_PATTERN_GROUP_MAX_BYTES:+ continue+ group_bytes[cluster.cluster_id] = group_bytes.get(cluster.cluster_id, 3) + member_bytes+ if previous is None:+ groups[cluster.cluster_id] = replace(pattern, pattern=cluster.get_template())+ continue+ severities = previous.severity_counts.copy()+ for severity, count in pattern.severity_counts.items():+ severities[severity] = severities.get(severity, 0) + count+ groups[cluster.cluster_id] = replace(+ previous,+ pattern=cluster.get_template(),+ count=previous.count + pattern.count,+ error_count=previous.error_count + pattern.error_count,+ first_seen=min(previous.first_seen, pattern.first_seen),+ last_seen=max(previous.last_seen, pattern.last_seen),+ services=sorted(set(previous.services + pattern.services))[:max_services],+ bucket_counts=[left + right for left, right in zip(previous.bucket_counts, pattern.bucket_counts)],+ severity_counts=severities,+ match_patterns=previous.match_patterns + pattern.match_patterns,+ )+ ordered = sorted(groups.values(), key=lambda pattern: (-pattern.count, pattern.pattern))+ return [+ replace(pattern, volume_share_pct=round(pattern.count / total_count * 100, 2) if total_count else 0)+ for pattern in ordered[: _env("LOGS_PATTERNS_MAX_PATTERNS", 200, int)]+ ]diff --git a/products/logs/backend/pattern_diff.py b/products/logs/backend/pattern_diff.pyindex 83a4b4f8cb8d..eb34d48ee7c2 100644--- a/products/logs/backend/pattern_diff.py+++ b/products/logs/backend/pattern_diff.py@@ -166,6 +166,8 @@ def run_patterns_diff(team: "Team", query: LogsQuery, baseline_date_range: DateR)baseline_query = query.model_copy(update={"dateRange": baseline_date_range})baseline_runner = PatternsQueryRunner(team=team, query=baseline_query)+ current_runner.use_stored_patterns = False+ baseline_runner.use_stored_patterns = Falsebaseline_from = baseline_runner.query_date_range.date_from()baseline_to = baseline_runner.query_date_range.date_to()@@ -187,6 +189,9 @@ def run_patterns_diff(team: "Team", query: LogsQuery, baseline_date_range: DateRdef _window_meta(results: dict, date_from: dt.datetime, date_to: dt.datetime) -> dict:return {+ "source": results.get("source"),+ "pattern_version": results.get("pattern_version"),+ "fallback_reason": results.get("fallback_reason"),"scanned_count": results["scanned_count"],"total_count": results["total_count"],"sampled": results["sampled"],diff --git a/products/logs/backend/patterns_query_runner.py b/products/logs/backend/patterns_query_runner.pyindex 4a09326ccf1c..058915ca1584 100644--- a/products/logs/backend/patterns_query_runner.py+++ b/products/logs/backend/patterns_query_runner.py@@ -1,8 +1,12 @@import datetime as dt+from dataclasses import replacefrom functools import cached_propertyfrom math import ceil+from time import monotonicfrom typing import TYPE_CHECKING+import posthoganalytics+from posthog.schema import CachedLogsQueryResponse, LogsQueryfrom posthog.hogql import ast@@ -11,15 +15,26 @@ from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workload+from posthog.exceptions import ClickHouseQueryTimeOutfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner--from products.logs.backend.log_patterns import LogSample, MinedPattern, _env, mine_patterns+from posthog.utils import get_instance_region++from products.logs.backend.log_patterns import (+ ERROR_SEVERITIES,+ LogSample,+ MinedPattern,+ _env,+ encoded_pattern_member_size,+ group_stored_patterns,+ mine_patterns,+)from products.logs.backend.logs_query_runner import LogsQueryResponse, LogsQueryRunnerMixinif TYPE_CHECKING:from posthog.models import User_TimeSlice = tuple[dt.datetime, dt.datetime]+STORED_PATTERN_HEAD_MAX_BYTES = 65536class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):@@ -50,6 +65,8 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnquery: LogsQuerycached_response: CachedLogsQueryResponse+ use_stored_patterns: bool = True+ _query_deadline: float | None = None@cached_propertydef settings(self) -> HogQLGlobalSettings:@@ -89,8 +106,48 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnraise UserAccessControlError("logs", "viewer")def _calculate(self) -> LogsQueryResponse:- total = self._count()+ reason = "comparison" if not self.use_stored_patterns else "flag_disabled"+ if self.use_stored_patterns and self._stored_patterns_enabled:+ self._query_deadline = monotonic() + max(1, self.settings.max_execution_time or 60)+ versions = self._execute(+ parse_select(+ "SELECT pattern_version, count(), countIf(trim(pattern) != '') FROM logs WHERE {where} GROUP BY pattern_version",+ placeholders={"where": self._where_with_timestamp()},+ )+ ).results+ total = sum(int(row[1]) for row in versions)+ candidates = [(int(row[2]), int(row[0])) for row in versions if int(row[0]) > 0]+ covered, version = max(candidates, default=(0, 0))+ if total and covered * 100 >= total * 99:+ return self._calculate_stored_patterns(total, version, covered)+ reason = "insufficient_version_coverage" if total else "empty_window"+ else:+ total = self._count()+ return self._calculate_body_patterns(total, reason)++ @cached_property+ def _stored_patterns_enabled(self) -> bool:+ # only_evaluate_locally keeps this check off the network: it gates an interactive query, so+ # a flags-service round trip (plus its retry) would delay every patterns request. An+ # inconclusive local evaluation therefore means "off", which is body mining as before.+ # `group_properties` carries the organization id so an org-level rollout still resolves locally.+ team_id = str(self.team.pk)+ person_properties = {"team_id": team_id, "region": get_instance_region() or "DEV"}+ if self.user:+ person_properties["email"] = self.user.email+ return bool(+ posthoganalytics.feature_enabled(+ "logs_patterns_query_v2",+ str(self.user.distinct_id) if self.user else team_id,+ person_properties=person_properties,+ groups={"organization": str(self.team.organization_id)},+ group_properties={"organization": {"id": str(self.team.organization_id)}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ )+ def _calculate_body_patterns(self, total: int, reason: str) -> LogsQueryResponse:slices = _time_slices(self.query_date_range.date_from(),self.query_date_range.date_to(),@@ -136,9 +193,125 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn"sampled": scanned < total,"sample_coverage_pct": round(pool / total * 100, 2) if total else 100.0,"sparkline_buckets": [{"start": start.isoformat(), "end": end.isoformat()} for start, end in buckets],+ "source": "body_mining",+ "pattern_version": None,+ "fallback_reason": reason,+ "pattern_coverage_pct": None,+ "represented_count": None,+ "remainder_count": None,+ }+ )++ def _stored_where(self, version: int) -> ast.Expr:+ return parse_expr(+ "{where} AND pattern_version = {version} AND trim(pattern) != ''",+ placeholders={"where": self._where_with_timestamp(), "version": ast.Constant(value=version)},+ )++ def _calculate_stored_patterns(self, total: int, version: int, covered: int) -> LogsQueryResponse:+ head_limit = min(10000, max(1, _env("LOGS_PATTERNS_HEAD_LIMIT", 10000, int)))+ head = self._execute(+ parse_select(+ "SELECT topK({head_limit})(pattern) FROM logs WHERE {where}",+ placeholders={"head_limit": ast.Constant(value=head_limit), "where": self._stored_where(version)},+ )+ ).results[0][0]+ bounded_head = []+ head_bytes = 3+ for member in head:+ member_bytes = encoded_pattern_member_size(member)+ if head_bytes + member_bytes <= STORED_PATTERN_HEAD_MAX_BYTES:+ bounded_head.append(member)+ head_bytes += member_bytes+ buckets = _uniform_buckets(+ self.query_date_range.date_from(), self.query_date_range.date_to(), self._sparkline_bucket_count+ )+ placeholders: dict[str, ast.Expr] = {+ "where": self._stored_where(version),+ "head": ast.Constant(value=bounded_head),+ "services_limit": ast.Constant(value=_env("LOGS_PATTERNS_MAX_SERVICES", 4, int)),+ "head_limit": ast.Constant(value=head_limit),+ }+ bucket_sql = []+ for index, (start, end) in enumerate(buckets):+ placeholders[f"start_{index}"] = ast.Constant(value=start)+ placeholders[f"end_{index}"] = ast.Constant(value=end)+ bucket_sql.append(f"countIf(timestamp >= {{start_{index}}} AND timestamp < {{end_{index}}})")+ rows = self._execute(+ parse_select(+ "SELECT pattern, count(), min(timestamp), max(timestamp), "+ "sumMap([lower(severity_text)], [1]), "+ "groupUniqArrayArray({services_limit})([service_name]), "+ f"[{', '.join(bucket_sql)}] "+ "FROM logs WHERE {where} AND pattern IN {head} GROUP BY pattern "+ "ORDER BY count() DESC, pattern LIMIT {head_limit}",+ placeholders=placeholders,+ )+ ).results+ patterns = group_stored_patterns([_stamped_pattern(row, version) for row in rows], total_count=total)+ patterns = self._stored_examples(patterns, version)+ represented = sum(pattern.count for pattern in patterns)+ return LogsQueryResponse(+ results={+ "patterns": [_serialize(pattern, total_count=total, scanned_count=total) for pattern in patterns],+ "total_count": total,+ "scanned_count": total,+ "sampled": False,+ "sample_coverage_pct": 100.0,+ "sparkline_buckets": [{"start": start.isoformat(), "end": end.isoformat()} for start, end in buckets],+ "source": "stored_patterns",+ "pattern_version": version,+ "fallback_reason": None,+ "pattern_coverage_pct": round(covered / total * 100, 2),+ "represented_count": represented,+ "remainder_count": max(0, total - represented),})+ def _stored_examples(self, patterns: list[MinedPattern], version: int) -> list[MinedPattern]:+ if not patterns:+ return []+ max_examples = _env("LOGS_PATTERNS_MAX_EXAMPLES", 10, int)+ if max_examples <= 0:+ return patterns+ member_groups = {+ member: group_id for group_id, pattern in enumerate(patterns, start=1) for member in pattern.match_patterns+ }+ # `LIMIT n BY` caps rows, not distinct bodies, and the table's sort order puts the rows of a+ # repeated line next to each other, so one body can fill a group's whole quota. Read a+ # bounded multiple of the quota and keep the distinct bodies here. Grouping on `body` in the+ # query would decompress it for every matching row instead of stopping at the rows read+ # first, which is the cost this query is shaped to avoid.+ fetch_per_group = max_examples * 4+ rows = self._execute(+ parse_select(+ "SELECT transform(pattern, {patterns}, {group_ids}, 0) AS pattern_group, "+ "substringUTF8(body, 1, 4096), severity_text, service_name, timestamp "+ "FROM logs WHERE {where} AND pattern IN {patterns} "+ "LIMIT {fetch_per_group} BY pattern_group LIMIT {limit}",+ placeholders={+ "where": self._stored_where(version),+ "patterns": ast.Constant(value=list(member_groups)),+ "group_ids": ast.Constant(value=list(member_groups.values())),+ "fetch_per_group": ast.Constant(value=fetch_per_group),+ "limit": ast.Constant(value=len(patterns) * fetch_per_group),+ },+ )+ ).results+ examples: dict[int, list[LogSample]] = {}+ for row in rows:+ group = examples.setdefault(row[0], [])+ if len(group) >= max_examples or any(example.body == row[1] for example in group):+ continue+ group.append(+ LogSample(+ body=row[1], severity_text=row[2], service_name=row[3], timestamp=row[4].replace(tzinfo=dt.UTC)+ )+ )+ return [+ replace(pattern, examples=examples.get(group_id, [])) for group_id, pattern in enumerate(patterns, start=1)+ ]+def run(self, *args, **kwargs) -> LogsQueryResponse | CachedLogsQueryResponse:response = super().run(*args, **kwargs)assert isinstance(response, LogsQueryResponse | CachedLogsQueryResponse)@@ -150,7 +323,13 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnreturn self._sample_query(divisor=1, slices=None)def _execute(self, query: ast.SelectQuery | ast.SelectSetQuery):- return execute_hogql_query(+ settings = self.settings.model_copy()+ if self._query_deadline is not None:+ remaining = int(self._query_deadline - monotonic())+ if remaining < 1:+ raise ClickHouseQueryTimeOut()+ settings.max_execution_time = remaining+ response = execute_hogql_query(query_type="LogsQuery",query=query,modifiers=self.modifiers,@@ -158,8 +337,11 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnworkload=Workload.LOGS,timings=self.timings,limit_context=self.limit_context,- settings=self.settings,+ settings=settings,)+ if self._query_deadline is not None and monotonic() >= self._query_deadline:+ raise ClickHouseQueryTimeOut()+ return responsedef _count(self, slices: list[_TimeSlice] | None = None) -> int:response = self._execute(@@ -305,4 +487,26 @@ def _serialize(pattern: MinedPattern, *, total_count: int, scanned_count: int) -"severity_counts": pattern.severity_counts,"match_regex": pattern.match_regex,"match_literal": pattern.match_literal,+ "match_patterns": pattern.match_patterns,+ "pattern_version": pattern.pattern_version,}+++def _stamped_pattern(row: list, version: int) -> MinedPattern:+ severities = dict(zip(row[4][0], row[4][1]))+ return MinedPattern(+ pattern=row[0],+ count=int(row[1]),+ volume_share_pct=0,+ error_count=sum(count for severity, count in severities.items() if severity in ERROR_SEVERITIES),+ first_seen=row[2].replace(tzinfo=dt.UTC),+ last_seen=row[3].replace(tzinfo=dt.UTC),+ examples=[],+ services=sorted(service for service in row[5] if service),+ bucket_counts=row[6],+ severity_counts=severities,+ match_regex=None,+ match_literal=None,+ match_patterns=[row[0]],+ pattern_version=version,+ )diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex ab00c4336e94..1a42462fda64 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -173,7 +173,12 @@ class _DateRangeSerializer(serializers.Serializer):class _LogPropertyFilterSerializer(serializers.Serializer):key = serializers.CharField(- help_text='Attribute key. For type "log", use "message". For "log_attribute"/"log_resource_attribute", use the attribute key (e.g. "k8s.container.name").',+ help_text=(+ 'Attribute key. For type "log", use "message" for the body text, or a log column: '+ '"pattern" and "pattern_version" (the patterns pivot), "severity_level", "service_name", '+ '"trace_id", "span_id". For "log_attribute"/"log_resource_attribute", use the attribute '+ 'key (e.g. "k8s.container.name").'+ ),)type = serializers.ChoiceField(choices=_LOG_PROPERTY_TYPE_CHOICES,@@ -843,9 +848,9 @@ class _LogsPatternsRequestSerializer(serializers.Serializer):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, with the message field extracted from JSON bodies. This is not the "- "raw stored line."+ "Original-message example. Body mining normalizes whitespace, extracts JSON message fields "+ "and truncates to the mining cap. Stored-pattern aggregation returns the raw body prefix, "+ "limited to 4096 Unicode characters."),)severity_text = serializers.CharField(help_text='Severity of the sampled line, e.g. "info", "error".')@@ -856,8 +861,11 @@ class _LogPatternExampleSerializer(serializers.Serializer):class _LogPatternSerializer(serializers.Serializer):pattern = serializers.CharField(help_text=(- 'Mined log template with variable tokens masked, e.g. "Connected to <ip> in <num>ms". '- "Tokens: <timestamp>, <uuid>, <ip>, <hex>, <num>, plus <*> for word positions Drain found to vary."+ 'Log template with variable tokens masked, e.g. "Connected to <ip> in <num>ms". '+ "Body mining masks <timestamp>, <uuid>, <ip>, <hex>, <num>, plus <*> for word positions "+ "Drain found to vary. Stored patterns use the ingestion vocabulary instead: <N>, "+ "<TIMESTAMP>, <KLOGTIME>, <UUID>, <IP>, <HOST>, <HEX>, <ID>, <EMAIL>, <JSON_ARRAY>, and "+ "<JSON:keys> for a JSON body reduced to its key set."),)count = serializers.IntegerField(@@ -873,10 +881,16 @@ class _LogPatternSerializer(serializers.Serializer):),)volume_share_pct = serializers.FloatField(- help_text="Share of the sampled log volume this pattern represents (0–100).",+ help_text=(+ "Share of the log volume this pattern represents (0–100). Measured over the sample when "+ "`sampled` is true, over every matching row otherwise."+ ),)error_count = serializers.IntegerField(- help_text='Sampled occurrences at severity "error" or "fatal". Prefer `estimated_error_count` for display.',+ help_text=(+ 'Occurrences at severity "error" or "fatal". A sample count when `sampled` is true, so '+ "prefer `estimated_error_count` for display."+ ),)estimated_error_count = serializers.IntegerField(help_text=(@@ -884,8 +898,18 @@ class _LogPatternSerializer(serializers.Serializer):"Equals `error_count` when the window was not sampled."),)- first_seen = serializers.CharField(help_text="ISO 8601 timestamp of the earliest sampled occurrence.")- last_seen = serializers.CharField(help_text="ISO 8601 timestamp of the latest sampled occurrence.")+ first_seen = serializers.CharField(+ help_text=(+ "ISO 8601 timestamp of the earliest occurrence. Taken from the sample when `sampled` is "+ "true, from every matching row otherwise."+ )+ )+ last_seen = serializers.CharField(+ help_text=(+ "ISO 8601 timestamp of the latest occurrence. Taken from the sample when `sampled` is "+ "true, from every matching row otherwise."+ )+ )examples = _LogPatternExampleSerializer(many=True,help_text=(@@ -900,16 +924,18 @@ class _LogPatternSerializer(serializers.Serializer):sparkline = serializers.ListField(child=serializers.IntegerField(),help_text=(- "Estimated occurrences per time bucket, aligned index-for-index with the response's "- "`sparkline_buckets`. Extrapolated from the sample like `estimated_count`, so it shows "- "the volume shape over the window, not exact per-bucket tallies."+ "Occurrences per time bucket, aligned index-for-index with the response's "+ "`sparkline_buckets`. When `sampled` is true these are extrapolated like `estimated_count` "+ "and show the volume shape over the window rather than exact tallies. Otherwise they are "+ "exact per-bucket counts."),)severity_counts = serializers.DictField(child=serializers.IntegerField(),help_text=(- '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."+ 'Occurrences keyed by lowercased severity ("trace" through "fatal"). Never extrapolated, '+ "because severity dominance is a proportion that scaling would not change. Sample counts "+ "when `sampled` is true, counts over every matching row otherwise."),)match_regex = serializers.CharField(@@ -929,6 +955,16 @@ class _LogPatternSerializer(serializers.Serializer):"`match_regex` is null. Null when the template has no usable literal content."),)+ match_patterns = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Exact canonical members of a stored-pattern group. Filter pattern IN these values AND pattern_version equals this group's version. Empty for body mining.",+ )+ pattern_version = serializers.IntegerField(+ allow_null=True,+ required=False,+ help_text="Version required by match_patterns. Null for body mining.",+ )class _LogsPatternsSparklineBucketSerializer(serializers.Serializer):@@ -936,13 +972,47 @@ class _LogsPatternsSparklineBucketSerializer(serializers.Serializer):end = serializers.CharField(help_text="Bucket end (ISO 8601, exclusive).")-class _LogsPatternsResponseSerializer(serializers.Serializer):+class _LogsPatternsSourceSerializer(serializers.Serializer):+ source = serializers.ChoiceField( # type: ignore[assignment]+ choices=["stored_patterns", "body_mining"],+ required=False,+ help_text="Whether counts come from stored-pattern aggregation or body masking and Drain3 mining.",+ )+ pattern_version = serializers.IntegerField(+ allow_null=True,+ required=False,+ help_text="Stored pattern version used. Null for body mining.",+ )+ fallback_reason = serializers.ChoiceField(+ choices=["flag_disabled", "insufficient_version_coverage", "empty_window", "comparison"],+ allow_null=True,+ required=False,+ help_text="Why body mining was used. Null for stored-pattern aggregation.",+ )+ pattern_coverage_pct = serializers.FloatField(+ allow_null=True,+ required=False,+ help_text="Percentage of all matching rows with a nonempty pattern at the selected version. Null for body mining.",+ )+ represented_count = serializers.IntegerField(+ allow_null=True,+ required=False,+ help_text="Exact rows represented by the returned stored-pattern groups. Null for body mining.",+ )+ remainder_count = serializers.IntegerField(+ allow_null=True,+ required=False,+ help_text="Matching rows outside returned groups, including other versions, unstamped rows and the long tail. Null for body mining.",+ )+++class _LogsPatternsResponseSerializer(_LogsPatternsSourceSerializer):patterns = _LogPatternSerializer(many=True,- help_text="Mined patterns ordered by `count` descending.",+ help_text="Pattern groups ordered by count. Stored-pattern counts are exact; body-mining counts describe the sample.",)scanned_count = serializers.IntegerField(- help_text="Number of log rows fed to the miner (the sample size, capped at the sample limit).",+ help_text="Rows scanned: the sample size for body mining, or the full matching count for stored-pattern aggregation.",)total_count = serializers.IntegerField(help_text=(@@ -1031,7 +1101,7 @@ class _LogPatternDiffEntrySerializer(serializers.Serializer):)-class _LogsPatternsDiffWindowSerializer(serializers.Serializer):+class _LogsPatternsDiffWindowSerializer(_LogsPatternsSourceSerializer):scanned_count = serializers.IntegerField(help_text="Log rows fed to the miner for this window (sample size).")total_count = serializers.IntegerField(help_text="Total log rows matching the filters in this window.")sampled = serializers.BooleanField(@@ -1656,7 +1726,9 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):query = self._filtered_logs_query(query_data)- runner = PatternsQueryRunner(team=self.team, query=query)+ runner = PatternsQueryRunner(+ team=self.team, query=query, user=request.user if isinstance(request.user, User) else None+ )response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS,analytics_props=get_request_analytics_properties(request),@@ -1671,6 +1743,13 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):if isinstance(response.results, dict)else 0,"sampled": response.results.get("sampled") if isinstance(response.results, dict) else None,+ "source": response.results.get("source") if isinstance(response.results, dict) else None,+ "pattern_version": response.results.get("pattern_version")+ if isinstance(response.results, dict)+ else None,+ "fallback_reason": response.results.get("fallback_reason")+ if isinstance(response.results, dict)+ else None,"has_search_term": bool(query_data.get("searchTerm")),"severity_levels_count": len(query_data.get("severityLevels") or []),"service_names_count": len(query_data.get("serviceNames") or []),diff --git a/products/logs/backend/test/test_log_patterns.py b/products/logs/backend/test/test_log_patterns.pyindex 43b1f06404a4..3e7fecc9d066 100644--- a/products/logs/backend/test/test_log_patterns.py+++ b/products/logs/backend/test/test_log_patterns.py@@ -1,6 +1,8 @@import re+import jsonimport datetime as dtfrom itertools import zip_longest+from urllib.parse import quotefrom unittest import TestCase@@ -18,10 +20,12 @@ from products.logs.backend.log_patterns import (_PLACEHOLDER_PATTERNS,_WHITESPACE_RE,LogSample,+ MinedPattern,_prepare_body,_prepare_json_body,compile_match_regex,extract_match_literal,+ group_stored_patterns,mine_patterns,pattern_fingerprint,)@@ -102,6 +106,48 @@ def _sample()+class TestStoredPatternGroups(TestCase):+ @parameterized.expand([(51, "job"), (8, "🦔" * 100), (1, "🦔" * 1024)])+ def test_bounded_members_preserve_exact_aggregates(self, count: int, identifier: str) -> None:+ timestamp = dt.datetime(2026, 6, 23, 12, tzinfo=dt.UTC)+ canonical = [+ MinedPattern(+ pattern=f"Archive {identifier}{index} batch completed",+ count=index + 1,+ volume_share_pct=0,+ error_count=index + 1,+ first_seen=timestamp,+ last_seen=timestamp,+ examples=[],+ services=["api"],+ bucket_counts=[index + 1],+ severity_counts={"error": index + 1},+ match_regex=None,+ match_literal=None,+ match_patterns=[f"Archive {identifier}{index} batch completed"],+ pattern_version=5,+ )+ for index in range(count)+ ]+ total = sum(pattern.count for pattern in canonical)++ groups = group_stored_patterns(canonical, total_count=total)++ assert sum(group.count for group in groups) < total+ assert bool(groups) == (count > 1)+ counts = {pattern.pattern: pattern.count for pattern in canonical}+ for group in groups:+ assert len(group.match_patterns) <= 50+ assert (+ len(quote(json.dumps(group.match_patterns, ensure_ascii=False, separators=(",", ":")), safe="")) <= 3072+ )+ expected = sum(counts[member] for member in group.match_patterns)+ assert group.count == group.error_count == expected+ assert group.bucket_counts == [expected]+ assert group.severity_counts == {"error": expected}+ assert group.volume_share_pct == round(expected / total * 100, 2)++class TestMinePatterns(TestCase):def test_merges_messages_differing_by_one_word_into_one_template(self) -> None:samples = [@@ -527,6 +573,8 @@ class TestCompileMatchRegex(TestCase):[("longest_run_wins", "at <uuid> failed to charge card for team <num>", "failed to charge card for team"),("too_thin", "<*> ab <num>", None),+ ("ingestion_placeholders_are_literal", "At <ID> sent to <EMAIL>", "At <ID> sent to <EMAIL>"),+ ("ingestion_array_is_literal", "<JSON_ARRAY>", "<JSON_ARRAY>"),])def test_extract_match_literal(self, _name: str, template: str, expected: str | None) -> None:@@ -541,6 +589,23 @@ class TestCompileMatchRegex(TestCase):assert extract_match_literal("job done ok", ["job done\n\nok"]) is Noneassert extract_match_literal("Job Done OK", ["prefix job done ok suffix"]) == "Job Done OK"+ @parameterized.expand(+ [+ ("<ID>", "abc_123"),+ ("<TIMESTAMP>", "2026-09-01T12:00:00Z"),+ ("<HOST>", "worker.example.com"),+ ("<JSON_ARRAY>", "[1,2,3]"),+ ("<JSON:key>", '{"key":1}'),+ ]+ )+ def test_ingestion_tokens_are_literal_in_body_predicates(self, token: str, value: str) -> None:+ template = f"payload {token}"+ predicate = _compile_prose(template, [template])+ assert predicate is not None+ assert re.search(predicate, template)+ assert re.search(predicate, f"payload {value}") is None+ assert _compile_prose(template, [f"payload {value}"]) is None+class TestPrepareJsonBody(TestCase):@parameterized.expand(diff --git a/products/logs/backend/test/test_patterns_api.py b/products/logs/backend/test/test_patterns_api.pyindex 46328113f8ba..379d6fc897c8 100644--- a/products/logs/backend/test/test_patterns_api.py+++ b/products/logs/backend/test/test_patterns_api.py@@ -1,8 +1,11 @@+import osimport jsonimport time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import ANY, patch+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.clickhouse.client import sync_execute@@ -18,8 +21,9 @@ class TestPatternsAPI(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, expected_status)return response.json() if expected_status == status.HTTP_200_OK else response+ @parameterized.expand([(False, 10), (True, 10), (True, 2), (None, 10)])@time_machine.travel("2026-06-23T13:00:00Z", tick=False)- def test_patterns_endpoint_returns_mined_patterns(self) -> None:+ def test_patterns_endpoint_returns_mined_patterns(self, stored_patterns: bool | None, max_examples: int) -> None:self._insert([{@@ -27,18 +31,33 @@ class TestPatternsAPI(ClickhouseTestMixin, APIBaseTest):"body": f"User {name} not found","severity_text": "error","service_name": "auth",+ "pattern": f"User {name} not found",+ "pattern_version": 3,}for name in ("alice", "bob", "carol")])- body = self._request(- {- "dateRange": {"date_from": "2026-06-23T00:00:00Z", "date_to": "2026-06-23T13:00:00Z"},- "filterGroup": {"type": "AND", "values": [{"type": "AND", "values": []}]},- }- )+ with (+ patch("posthoganalytics.feature_enabled", return_value=stored_patterns) as feature_enabled,+ patch.dict(os.environ, {"LOGS_PATTERNS_MAX_EXAMPLES": str(max_examples)}),+ ):+ body = self._request(+ {+ "dateRange": {"date_from": "2026-06-23T00:00:00Z", "date_to": "2026-06-23T13:00:00Z"},+ "filterGroup": {"type": "AND", "values": [{"type": "AND", "values": []}]},+ }+ )+ feature_enabled.assert_any_call(+ "logs_patterns_query_v2",+ str(self.user.distinct_id),+ person_properties={"email": self.user.email, "team_id": str(self.team.pk), "region": ANY},+ groups={"organization": str(self.team.organization_id)},+ group_properties={"organization": {"id": str(self.team.organization_id)}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )assert body["scanned_count"] == 3assert body["total_count"] == 3assert body["sampled"] is False@@ -49,6 +68,17 @@ class TestPatternsAPI(ClickhouseTestMixin, APIBaseTest):assert pattern["error_count"] == 3assert pattern["estimated_error_count"] == 3assert pattern["services"] == ["auth"]+ examples = {example["body"] for example in pattern["examples"]}+ assert len(pattern["examples"]) == min(3, max_examples)+ assert examples <= {f"User {name} not found" for name in ("alice", "bob", "carol")}+ if max_examples >= 3:+ assert examples == {f"User {name} not found" for name in ("alice", "bob", "carol")}+ assert body["source"] == ("stored_patterns" if stored_patterns else "body_mining")+ assert body["pattern_version"] == (3 if stored_patterns else None)+ assert body["fallback_reason"] == (None if stored_patterns else "flag_disabled")+ assert pattern["match_patterns"] == (+ [f"User {name} not found" for name in ("alice", "bob", "carol")] if stored_patterns else []+ )@time_machine.travel("2026-06-23T13:00:00Z", tick=False)def test_patterns_endpoint_accepts_flat_filter_group(self) -> None:diff --git a/products/logs/backend/test/test_patterns_query_runner.py b/products/logs/backend/test/test_patterns_query_runner.pyindex 19841021e1f0..893c865b9b38 100644--- a/products/logs/backend/test/test_patterns_query_runner.py+++ b/products/logs/backend/test/test_patterns_query_runner.py@@ -11,7 +11,10 @@ from parameterized import parameterizedfrom posthog.schema import DateRange, FilterLogicalOperator, LogsQuery, PropertyGroupFilter+from posthog.hogql.query import execute_hogql_query+from posthog.clickhouse.client import sync_execute+from posthog.exceptions import ClickHouseQueryTimeOutfrom posthog.hogql_queries.query_runner import ExecutionModefrom products.logs.backend.patterns_query_runner import PatternsQueryRunner, _sample_divisor, _time_slices@@ -44,6 +47,198 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):response = PatternsQueryRunner(team=self.team, query=query).run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)return response.results+ @time_machine.travel(_FROZEN_NOW, tick=False)+ def test_mines_stored_patterns_and_retains_body_examples(self) -> None:+ self._insert(+ [+ {**self._log("Archive job run_A7c queued"), "pattern": "Archive job <ID> queued", "pattern_version": 5},+ {**self._log("Archive job run_B8d queued"), "pattern": "Archive job <ID> queued", "pattern_version": 5},+ {+ **self._log("Processed 12 records " + "🦔" * 4100),+ "pattern": "Processed <N> records",+ "pattern_version": 5,+ },+ ]+ )++ with patch("posthoganalytics.feature_enabled", return_value=True):+ results = self._run()+ patterns = {pattern["pattern"]: pattern for pattern in results["patterns"]}++ assert results["total_count"] == results["scanned_count"] == 3+ assert patterns["Archive job <ID> queued"]["count"] == 2+ assert {example["body"] for example in patterns["Archive job <ID> queued"]["examples"]} == {+ "Archive job run_A7c queued",+ "Archive job run_B8d queued",+ }+ assert patterns["Processed <N> records"]["count"] == 1+ assert len(patterns["Processed <N> records"]["examples"][0]["body"]) == 4096+ assert patterns["Processed <N> records"]["examples"][0]["body"].endswith("🦔")+ assert results["source"] == "stored_patterns"+ assert results["pattern_version"] == 5+ assert results["fallback_reason"] is None+ assert results["represented_count"] == 3+ assert results["remainder_count"] == 0+ assert results["sampled"] is False+ assert patterns["Archive job <ID> queued"]["match_patterns"] == ["Archive job <ID> queued"]+ assert patterns["Archive job <ID> queued"]["pattern_version"] == 5++ @time_machine.travel(_FROZEN_NOW, tick=False)+ def test_stored_examples_do_not_repeat_a_body(self) -> None:+ self._insert(+ [+ {**self._log("Retry 7 timed out"), "pattern": "Retry <N> timed out", "pattern_version": 5}+ for _ in range(12)+ ]+ + [+ {**self._log("Retry 8 timed out", minute=1), "pattern": "Retry <N> timed out", "pattern_version": 5},+ {**self._log("Retry 9 timed out", minute=2), "pattern": "Retry <N> timed out", "pattern_version": 5},+ ]+ )++ with patch("posthoganalytics.feature_enabled", return_value=True):+ results = self._run()++ pattern = results["patterns"][0]+ bodies = [example["body"] for example in pattern["examples"]]+ assert pattern["count"] == 14+ assert len(bodies) == len(set(bodies))+ assert set(bodies) == {"Retry 7 timed out", "Retry 8 timed out", "Retry 9 timed out"}++ @parameterized.expand([(False, 100, "flag_disabled"), (True, 98, "insufficient_version_coverage")])+ @time_machine.travel(_FROZEN_NOW, tick=False)+ def test_body_fallback_does_not_mix_stored_versions(self, enabled: bool, coverage: int, reason: str) -> None:+ self._insert(+ [+ {**self._log(f"Processed {index} records"), "pattern": "unrelated stored shape", "pattern_version": 3}+ for index in range(coverage)+ ]+ + [self._log("Processed 123 records") for _ in range(100 - coverage)]+ )+ with patch("posthoganalytics.feature_enabled", return_value=enabled):+ results = self._run()+ assert results["source"] == "body_mining"+ assert results["pattern_version"] is None+ assert results["fallback_reason"] == reason+ assert results["remainder_count"] is None+ assert results["patterns"][0]["pattern"] == "Processed <num> records"+ assert results["patterns"][0]["count"] == 100+ assert results["patterns"][0]["match_patterns"] == []++ @parameterized.expand([(0, "", False), (5, "Processed <N> records", False), (0, "", True)])+ @time_machine.travel(_FROZEN_NOW, tick=False)+ def test_dominant_version_aggregates_exact_counts_and_discloses_remainder(+ self, minority_version: int, minority_pattern: str, byte_limited: bool+ ) -> None:+ self._insert(+ [+ {+ **self._log("Processed 123 records", severity="ERROR", minute=1),+ "pattern": "Processed <N> records",+ "pattern_version": 3,+ }+ for _ in range(60)+ ]+ + [+ {**self._log("Archived 456 files", minute=2), "pattern": "Archived <N> files", "pattern_version": 3}+ for _ in range(39)+ ]+ + [{**self._log("Processed 789 records"), "pattern": minority_pattern, "pattern_version": minority_version}]+ )+ with (+ patch("posthoganalytics.feature_enabled", return_value=True),+ patch.dict(os.environ, {"LOGS_PATTERNS_HEAD_LIMIT": "10000" if byte_limited else "1"}),+ patch(+ "products.logs.backend.patterns_query_runner.STORED_PATTERN_HEAD_MAX_BYTES",+ 42 if byte_limited else 65536,+ ),+ ):+ results = self._run()+ assert results["source"] == "stored_patterns"+ assert results["pattern_version"] == 3+ assert results["pattern_coverage_pct"] == 99+ assert results["total_count"] == 100+ assert results["represented_count"] == 60+ assert results["remainder_count"] == 40+ pattern = results["patterns"][0]+ assert pattern["count"] == pattern["estimated_count"] == 60+ assert pattern["error_count"] == pattern["estimated_error_count"] == 60+ assert pattern["severity_counts"] == {"error": 60}+ assert sum(pattern["sparkline"]) == 60+ assert pattern["volume_share_pct"] == 60+ pivot = self._run(+ filterGroup={+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [+ {"key": "pattern", "value": pattern["match_patterns"], "operator": "exact", "type": "log"},+ {+ "key": "pattern_version",+ "value": pattern["pattern_version"],+ "operator": "exact",+ "type": "log",+ },+ ],+ }+ ],+ }+ )+ assert pivot["total_count"] == 60++ @parameterized.expand([(True, 5, [60, 50, 40, 30]), (True, 0, [60, 50]), (False, 5, [60, 60])])+ @time_machine.travel(_FROZEN_NOW, tick=False)+ def test_query_budget_covers_stored_queries_and_fallback(+ self, enabled: bool, version: int, expected_budgets: list[int]+ ) -> None:+ self._insert(+ [{**self._log("Processed 7 records"), "pattern": "Processed <N> records", "pattern_version": version}]+ )+ budgets = []+ with (+ patch("posthoganalytics.feature_enabled", return_value=enabled),+ patch("products.logs.backend.patterns_query_runner.monotonic", return_value=100.0) as clock,+ ):++ def execute_with_elapsed_time(*args, **kwargs):+ budgets.append(kwargs["settings"].max_execution_time)+ result = execute_hogql_query(*args, **kwargs)+ clock.return_value += 10+ return result++ with patch(+ "products.logs.backend.patterns_query_runner.execute_hogql_query", side_effect=execute_with_elapsed_time+ ):+ results = self._run()++ assert results["total_count"] == 1+ assert budgets == expected_budgets++ @parameterized.expand([30, 60])+ @time_machine.travel(_FROZEN_NOW, tick=False)+ def test_exhausted_query_budget_raises_instead_of_returning_partial_counts(self, elapsed: int) -> None:+ self._insert([{**self._log("Processed 7 records"), "pattern": "Processed <N> records", "pattern_version": 5}])+ with (+ patch("posthoganalytics.feature_enabled", return_value=True),+ patch("products.logs.backend.patterns_query_runner.monotonic", return_value=100.0) as clock,+ ):++ def execute_with_elapsed_time(*args, **kwargs):+ result = execute_hogql_query(*args, **kwargs)+ clock.return_value += elapsed+ return result++ with (+ patch(+ "products.logs.backend.patterns_query_runner.execute_hogql_query",+ side_effect=execute_with_elapsed_time,+ ) as execute,+ self.assertRaises(ClickHouseQueryTimeOut),+ ):+ self._run()+ assert execute.call_count == 60 // elapsed+@time_machine.travel(_FROZEN_NOW, tick=False)def test_mines_templates_from_clickhouse(self) -> None:self._insert(@@ -185,28 +380,38 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_sample_divisor_rounds_up_to_keep_sample_within_limit(self, total: int, expected: int) -> None:assert _sample_divisor(total, sample_limit=10) == expected+ @parameterized.expand([(False,), (True,)])@time_machine.travel(_FROZEN_NOW, tick=False)- def test_respects_service_filter(self) -> None:+ def test_respects_service_filter(self, stored_patterns: bool) -> None:self._insert(- [self._log("auth check passed", service="api") for _ in range(3)]+ [+ {**self._log("auth check passed", service="api"), "pattern": "auth check passed", "pattern_version": 3}+ for _ in range(3)+ ]+ [self._log("query took too long", service="db") for _ in range(2)])- results = self._run(serviceNames=["api"])+ with patch("posthoganalytics.feature_enabled", return_value=stored_patterns):+ results = self._run(serviceNames=["api"])assert results["scanned_count"] == 3assert results["sampled"] is Falseservices_seen = {svc for p in results["patterns"] for svc in p["services"]}assert services_seen == {"api"}+ assert results["source"] == ("stored_patterns" if stored_patterns else "body_mining")+ @parameterized.expand([(False,), (True,)])@time_machine.travel(_FROZEN_NOW, tick=False)- def test_empty_window_returns_no_patterns(self) -> None:- results = self._run()+ def test_empty_window_returns_no_patterns(self, enabled: bool) -> None:+ with patch("posthoganalytics.feature_enabled", return_value=enabled):+ results = self._run()assert results["patterns"] == []assert results["scanned_count"] == 0assert results["total_count"] == 0assert results["sampled"] is False+ assert results["source"] == "body_mining"+ assert results["fallback_reason"] == ("empty_window" if enabled else "flag_disabled")def test_blocks_generic_query_runner_access(self) -> None:from products.access_control.backend.facade.user_access_control import UserAccessControlErrordiff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.test.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.test.tsxnew file mode 100644index 000000000000..6418bf8f5dc1--- /dev/null+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.test.tsx@@ -0,0 +1,36 @@+import { render } from '@testing-library/react'++import { PatternTemplate } from './LogsPatterns'++describe('PatternTemplate', () => {+ it.each([+ ['literal tags', 'render <div> for <customer>', []],+ [+ 'body placeholders',+ 'at <timestamp> <klogtime> <uuid> <ip> <version> <host> <hex> <num> <*>',+ ['<timestamp>', '<klogtime>', '<uuid>', '<ip>', '<version>', '<host>', '<hex>', '<num>', '<*>'],+ ],+ [+ 'stored placeholders',+ '<N> <TIMESTAMP> <KLOGTIME> <UUID> <IP> <HOST> <HEX> <ID> <EMAIL> <JSON_ARRAY>',+ [+ '<N>',+ '<TIMESTAMP>',+ '<KLOGTIME>',+ '<UUID>',+ '<IP>',+ '<HOST>',+ '<HEX>',+ '<ID>',+ '<EMAIL>',+ '<JSON_ARRAY>',+ ],+ ],+ ['JSON key set', '<JSON:foo,bar,+2> and <JSON:>', ['<JSON:foo,bar,+2>', '<JSON:>']],+ ['masked JSON keys', 'keys <JSON:account_<ID>,<UUID>,name,+2> <div>', ['<JSON:account_<ID>,<UUID>,name,+2>']],+ ])('highlights only supported tokens: %s', (_name, pattern, expected) => {+ const { container } = render(<PatternTemplate pattern={pattern as string} />)+ expect(container.textContent).toBe(pattern)+ expect(Array.from(container.querySelectorAll('.text-accent'), (token) => token.textContent)).toEqual(expected)+ })+})diff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsxindex e2345a2aa18d..6bec6abd9b8d 100644--- a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx@@ -95,14 +95,16 @@ function PatternExpandedRow({return (<div className="px-2 py-2 flex flex-col gap-2" data-attr="logs-pattern-expanded"><div className="flex items-center justify-between gap-2">- <div>{renderPatternTemplate(row.pattern)}</div>- {(row.match_regex || row.match_literal) && (+ <div>+ <PatternTemplate pattern={row.pattern} />+ </div>+ {(row.match_patterns?.length || row.match_regex || row.match_literal) && (<LemonButtontype="secondary"size="xsmall"onClick={() => onViewMatchingLogs(row)}tooltip={- row.match_regex+ row.match_patterns?.length || 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)'}@@ -135,14 +137,13 @@ function PatternExpandedRow({)}-// Highlight Drain's `<*>` wildcard and the masking placeholders (`<ip>`, `<num>`, `<uuid>`,-// `<hex>`, …) the runner emits — see _MASKING_INSTRUCTIONS in-// products/logs/backend/log_patterns.py for the authoritative token vocabulary.-const PATTERN_TOKEN = String.raw`<\*>|<[a-z][a-z0-9]*>`+// Token vocabularies: backend/log_patterns.py and nodejs/src/logs/log-pattern-mask.ts.+const INGESTION_TOKEN = 'N|TIMESTAMP|KLOGTIME|UUID|IP|HOST|HEX|ID|EMAIL|JSON_ARRAY'+const PATTERN_TOKEN = String.raw`<(?:\*|num|timestamp|klogtime|uuid|ip|version|host|hex|${INGESTION_TOKEN})>|<JSON:(?:<(?:${INGESTION_TOKEN})>|[^<>])*>`const PATTERN_TOKEN_SPLIT = new RegExp(`(${PATTERN_TOKEN})`, 'g')const PATTERN_TOKEN_MATCH = new RegExp(`^(${PATTERN_TOKEN})$`)-function renderPatternTemplate(pattern: string): JSX.Element {+export function PatternTemplate({ pattern }: { pattern: string }): JSX.Element {return (<span className="font-mono text-xs break-all">{pattern.split(PATTERN_TOKEN_SPLIT).map((part, i) => (@@ -245,7 +246,7 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {{title: 'Pattern',dataIndex: 'pattern',- render: (_, row) => renderPatternTemplate(row.pattern),+ render: (_, row) => <PatternTemplate pattern={row.pattern} />,},{title: 'Trend',@@ -322,7 +323,7 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {{title: 'Pattern',key: 'pattern',- render: (_, entry) => renderPatternTemplate(entry.pattern.pattern),+ render: (_, entry) => <PatternTemplate pattern={entry.pattern.pattern} />,},{// For "gone" entries the pattern's stats come from the baseline window, so the@@ -359,6 +360,17 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {return (<div className="flex-1 min-h-0 overflow-auto" data-attr="logs-patterns">+ {!compareEnabled &&+ patternsResponse.source === 'stored_patterns' &&+ !patternsResponseLoading &&+ !patternsError && (+ <LemonBanner type="info" className="m-2" data-attr="logs-patterns-source-info">+ Using stored patterns v{patternsResponse.pattern_version}, grouped with Drain3. Counts are+ exact. {humanFriendlyLargeNumber(patternsResponse.represented_count ?? 0)} of{' '}+ {humanFriendlyLargeNumber(total_count)} matching lines appear in these groups;{' '}+ {humanFriendlyLargeNumber(patternsResponse.remainder_count ?? 0)} remain outside them.+ </LemonBanner>+ )}{!compareEnabled && sampled && !patternsResponseLoading && !patternsError && (<LemonBanner type="info" className="m-2" data-attr="logs-patterns-sample-info">Patterns are mined from a representative sample of {humanFriendlyNumber(scanned_count)} lines out ofdiff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.tsindex f201cecc5ef1..71c8f8d9de48 100644--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts@@ -178,6 +178,34 @@ describe('logsPatternsLogic', () => {)})+ it('viewMatchingLogs matches canonical members and version without narrowing by example facets', async () => {+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPatternsSuccess'])++ logic.actions.viewMatchingLogs({+ ...RESPONSE.patterns[0],+ match_patterns: ['User <N> not found', 'User <UUID> not found'],+ pattern_version: 3,+ match_regex: null,+ match_literal: null,+ })++ const inner = filtersLogic.values.filters.filterGroup.values[0] as UniversalFiltersGroup+ expect(inner.values).toEqual(+ expect.arrayContaining([+ {+ key: 'pattern',+ value: ['User <N> not found', 'User <UUID> not found'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Log,+ },+ { key: 'pattern_version', value: 3, operator: PropertyOperator.Exact, type: PropertyFilterType.Log },+ ])+ )+ expect(selectedServices()).toEqual([])+ expect(selectedLevels()).toEqual([])+ })+it('compare mode diffs with the same query body and switches loaders for filter reloads', async () => {// The diff must scope its windows with exactly the filters a plain mine uses — if the// two request bodies drift apart, compare mode silently answers a different questiondiff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.tsindex dbf33dfd9962..b94a7e464545 100644--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts@@ -430,24 +430,43 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([// 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+ const exactMatch = !!pattern.match_patterns?.length && pattern.pattern_version != null+ const predicate: LogPropertyFilter | null = exactMatch? {- key: 'message',- value: pattern.match_regex,- operator: PropertyOperator.Regex,+ key: 'pattern',+ value: pattern.match_patterns!,+ operator: PropertyOperator.Exact,type: PropertyFilterType.Log,}- : pattern.match_literal+ : pattern.match_regex? {key: 'message',- value: pattern.match_literal,- operator: PropertyOperator.IContains,+ value: pattern.match_regex,+ operator: PropertyOperator.Regex,type: PropertyFilterType.Log,}- : null+ : pattern.match_literal+ ? {+ key: 'message',+ value: pattern.match_literal,+ operator: PropertyOperator.IContains,+ type: PropertyFilterType.Log,+ }+ : nullif (!predicate) {return}+ const predicates: LogPropertyFilter[] = exactMatch+ ? [+ predicate,+ {+ key: 'pattern_version',+ value: pattern.pattern_version!,+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Log,+ },+ ]+ : [predicate]const group = values.filters.filterGroupconst inner = group.values[0] as UniversalFiltersGroup | undefinedconst newGroup: UniversalFiltersGroup =@@ -455,14 +474,14 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([? {...group,values: [- { ...inner, values: [...inner.values, predicate] } as UniversalFiltersGroup,+ { ...inner, values: [...inner.values, ...predicates] } as UniversalFiltersGroup,...group.values.slice(1),],}: {type: FilterLogicalOperator.And,values: [- { type: FilterLogicalOperator.And, values: [predicate] } as UniversalFiltersGroup,+ { type: FilterLogicalOperator.And, values: predicates } as UniversalFiltersGroup,],}// Leave Patterns mode first so the filter write below doesn't re-trigger a mine:@@ -476,11 +495,11 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([// cap-truncated services list, or a severity outside the canonical buckets. Written// into the same group as the pattern predicate so the drill-down is one filter change.let scopedGroup = newGroup- if (pattern.services.length > 0 && pattern.services.length < SERVICES_LIST_CAP) {+ if (!exactMatch && pattern.services.length > 0 && pattern.services.length < SERVICES_LIST_CAP) {scopedGroup = setFacetIncluded(scopedGroup, SERVICE_NAME_FILTER, pattern.services)}const severities = Object.keys(pattern.severity_counts)- if (severities.length > 0 && severities.every((s) => CANONICAL_SEVERITIES.includes(s))) {+ if (!exactMatch && severities.length > 0 && severities.every((s) => CANONICAL_SEVERITIES.includes(s))) {scopedGroup = setFacetIncluded(scopedGroup, SEVERITY_LEVEL_FILTER, severities)}actions.setFilterGroup(scopedGroup, false)diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 078824275143..0c4c17ba86aa 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1431,7 +1431,7 @@ export const _LogPropertyFilterOperatorEnumApi = {} as constexport interface _LogPropertyFilterApi {- /** Attribute key. For type "log", use "message". For "log_attribute"/"log_resource_attribute", use the attribute key (e.g. "k8s.container.name"). */+ /** Attribute key. For type "log", use "message" for the body text, or a log column: "pattern" and "pattern_version" (the patterns pivot), "severity_level", "service_name", "trace_id", "span_id". For "log_attribute"/"log_resource_attribute", use the attribute key (e.g. "k8s.container.name"). */key: string/** "log" filters the log body/message. "log_attribute" filters log-level attributes. "log_resource_attribute" filters resource-level attributes.*@@ -1928,8 +1928,34 @@ export interface _LogsPatternsRequestApi {query: _LogsPatternsBodyApi}+/**+ * * `stored_patterns` - stored_patterns+ * * `body_mining` - body_mining+ */+export type LogsPatternsSourceEnumApi = (typeof LogsPatternsSourceEnumApi)[keyof typeof LogsPatternsSourceEnumApi]++export const LogsPatternsSourceEnumApi = {+ StoredPatterns: 'stored_patterns',+ BodyMining: 'body_mining',+} as const++/**+ * * `flag_disabled` - flag_disabled+ * * `insufficient_version_coverage` - insufficient_version_coverage+ * * `empty_window` - empty_window+ * * `comparison` - comparison+ */+export type FallbackReasonEnumApi = (typeof FallbackReasonEnumApi)[keyof typeof FallbackReasonEnumApi]++export const FallbackReasonEnumApi = {+ FlagDisabled: 'flag_disabled',+ InsufficientVersionCoverage: 'insufficient_version_coverage',+ EmptyWindow: 'empty_window',+ Comparison: 'comparison',+} as const+export interface _LogPatternExampleApi {- /** 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. */+ /** Original-message example. Body mining normalizes whitespace, extracts JSON message fields and truncates to the mining cap. Stored-pattern aggregation returns the raw body prefix, limited to 4096 Unicode characters. */body: string/** Severity of the sampled line, e.g. "info", "error". */severity_text: string@@ -1940,34 +1966,34 @@ export interface _LogPatternExampleApi {}/**- * 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.+ * Occurrences keyed by lowercased severity ("trace" through "fatal"). Never extrapolated, because severity dominance is a proportion that scaling would not change. Sample counts when `sampled` is true, counts over every matching row otherwise.*/export type _LogPatternApiSeverityCounts = { [key: string]: number }export interface _LogPatternApi {- /** Mined log template with variable tokens masked, e.g. "Connected to <ip> in <num>ms". Tokens: <timestamp>, <uuid>, <ip>, <hex>, <num>, plus <*> for word positions Drain found to vary. */+ /** Log template with variable tokens masked, e.g. "Connected to <ip> in <num>ms". Body mining masks <timestamp>, <uuid>, <ip>, <hex>, <num>, plus <*> for word positions Drain found to vary. Stored patterns use the ingestion vocabulary instead: <N>, <TIMESTAMP>, <KLOGTIME>, <UUID>, <IP>, <HOST>, <HEX>, <ID>, <EMAIL>, <JSON_ARRAY>, and <JSON:keys> for a JSON body reduced to its key set. */pattern: string/** Occurrences of this pattern within the sample. When `sampled` is true this is a sample count, not the full-window total — prefer `estimated_count` for display. */count: number/** Estimated occurrences across the full window, extrapolated from the sample (`count / scanned_count * total_count`). Equals `count` when the window was not sampled. */estimated_count: number- /** Share of the sampled log volume this pattern represents (0–100). */+ /** Share of the log volume this pattern represents (0–100). Measured over the sample when `sampled` is true, over every matching row otherwise. */volume_share_pct: number- /** Sampled occurrences at severity "error" or "fatal". Prefer `estimated_error_count` for display. */+ /** Occurrences at severity "error" or "fatal". A sample count when `sampled` is true, so prefer `estimated_error_count` for display. */error_count: number/** Estimated error/fatal occurrences across the full window, extrapolated from the sample. Equals `error_count` when the window was not sampled. */estimated_error_count: number- /** ISO 8601 timestamp of the earliest sampled occurrence. */+ /** ISO 8601 timestamp of the earliest occurrence. Taken from the sample when `sampled` is true, from every matching row otherwise. */first_seen: string- /** ISO 8601 timestamp of the latest sampled occurrence. */+ /** ISO 8601 timestamp of the latest occurrence. Taken from the sample when `sampled` is true, from every matching row otherwise. */last_seen: string/** Up to 10 distinct sampled log lines that produced this pattern, with severity, service, and timestamp for display. */examples: _LogPatternExampleApi[]/** Up to 4 distinct service names this pattern was observed in. */services: string[]- /** Estimated occurrences per time bucket, aligned index-for-index with the response's `sparkline_buckets`. Extrapolated from the sample like `estimated_count`, so it shows the volume shape over the window, not exact per-bucket tallies. */+ /** Occurrences per time bucket, aligned index-for-index with the response's `sparkline_buckets`. When `sampled` is true these are extrapolated like `estimated_count` and show the volume shape over the window rather than exact tallies. Otherwise they are exact per-bucket counts. */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. */+ /** Occurrences keyed by lowercased severity ("trace" through "fatal"). Never extrapolated, because severity dominance is a proportion that scaling would not change. Sample counts when `sampled` is true, counts over every matching row otherwise. */severity_counts: _LogPatternApiSeverityCounts/*** 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.@@ -1979,6 +2005,13 @@ export interface _LogPatternApi {* @nullable*/match_literal: string | null+ /** Exact canonical members of a stored-pattern group. Filter pattern IN these values AND pattern_version equals this group's version. Empty for body mining. */+ match_patterns?: string[]+ /**+ * Version required by match_patterns. Null for body mining.+ * @nullable+ */+ pattern_version?: number | null}export interface _LogsPatternsSparklineBucketApi {@@ -1989,9 +2022,41 @@ export interface _LogsPatternsSparklineBucketApi {}export interface _LogsPatternsResponseApi {- /** Mined patterns ordered by `count` descending. */+ /** Whether counts come from stored-pattern aggregation or body masking and Drain3 mining.+ *+ * * `stored_patterns` - stored_patterns+ * * `body_mining` - body_mining */+ source?: LogsPatternsSourceEnumApi+ /**+ * Stored pattern version used. Null for body mining.+ * @nullable+ */+ pattern_version?: number | null+ /** Why body mining was used. Null for stored-pattern aggregation.+ *+ * * `flag_disabled` - flag_disabled+ * * `insufficient_version_coverage` - insufficient_version_coverage+ * * `empty_window` - empty_window+ * * `comparison` - comparison */+ fallback_reason?: FallbackReasonEnumApi | null+ /**+ * Percentage of all matching rows with a nonempty pattern at the selected version. Null for body mining.+ * @nullable+ */+ pattern_coverage_pct?: number | null+ /**+ * Exact rows represented by the returned stored-pattern groups. Null for body mining.+ * @nullable+ */+ represented_count?: number | null+ /**+ * Matching rows outside returned groups, including other versions, unstamped rows and the long tail. Null for body mining.+ * @nullable+ */+ remainder_count?: number | null+ /** Pattern groups ordered by count. Stored-pattern counts are exact; body-mining counts describe the sample. */patterns: _LogPatternApi[]- /** Number of log rows fed to the miner (the sample size, capped at the sample limit). */+ /** Rows scanned: the sample size for body mining, or the full matching count for stored-pattern aggregation. */scanned_count: number/** Total log rows matching the filters in the window, before sampling. Use with `scanned_count` to scale per-pattern counts when `sampled` is true. */total_count: number@@ -2054,6 +2119,38 @@ export interface _LogPatternDiffEntryApi {}export interface _LogsPatternsDiffWindowApi {+ /** Whether counts come from stored-pattern aggregation or body masking and Drain3 mining.+ *+ * * `stored_patterns` - stored_patterns+ * * `body_mining` - body_mining */+ source?: LogsPatternsSourceEnumApi+ /**+ * Stored pattern version used. Null for body mining.+ * @nullable+ */+ pattern_version?: number | null+ /** Why body mining was used. Null for stored-pattern aggregation.+ *+ * * `flag_disabled` - flag_disabled+ * * `insufficient_version_coverage` - insufficient_version_coverage+ * * `empty_window` - empty_window+ * * `comparison` - comparison */+ fallback_reason?: FallbackReasonEnumApi | null+ /**+ * Percentage of all matching rows with a nonempty pattern at the selected version. Null for body mining.+ * @nullable+ */+ pattern_coverage_pct?: number | null+ /**+ * Exact rows represented by the returned stored-pattern groups. Null for body mining.+ * @nullable+ */+ represented_count?: number | null+ /**+ * Matching rows outside returned groups, including other versions, unstamped rows and the long tail. Null for body mining.+ * @nullable+ */+ remainder_count?: number | null/** Log rows fed to the miner for this window (sample size). */scanned_count: number/** Total log rows matching the filters in this window. */diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex 5d94500a5245..d02f193a1e98 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -577,7 +577,7 @@ export const LogsCountCreateBody = /* @__PURE__ */ zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -682,7 +682,7 @@ export const LogsCountRangesCreateBody = /* @__PURE__ */ zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -816,7 +816,7 @@ export const LogsFacetValuesCreateBody = /* @__PURE__ */ zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -922,7 +922,7 @@ export const LogsGroupByCreateBody = /* @__PURE__ */ zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -1069,7 +1069,7 @@ export const LogsImpactCreateBody = /* @__PURE__ */ zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -1319,7 +1319,7 @@ export const LogsPatternsCreateBody = /* @__PURE__ */ zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -1417,7 +1417,7 @@ export const LogsPatternsDiffCreateBody = /* @__PURE__ */ zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -1549,7 +1549,7 @@ export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -1948,7 +1948,7 @@ export const LogsServicesCreateBody = /* @__PURE__ */ zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -2041,7 +2041,7 @@ export const LogsSparklineCreateBody = /* @__PURE__ */ zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])diff --git a/products/logs/mcp/prompts/logs-patterns.md b/products/logs/mcp/prompts/logs-patterns.mdindex 8e6655281386..b8174c882ede 100644--- a/products/logs/mcp/prompts/logs-patterns.md+++ b/products/logs/mcp/prompts/logs-patterns.md@@ -12,7 +12,7 @@ This is the fastest way to understand what a log stream is _saying_ without read- 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`.- To find what's new or dominant during an incident window: mine with `severityLevels: ["error", "fatal"]` and a `dateRange` covering the incident.-- 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`.+- As the entry point of a drill-down loop: mine → pick a suspicious pattern → filter logs to exactly its lines using `match_patterns`, or `match_regex` and `match_literal` when it is empty (see below) → read the raw rows with `query-logs`.- To quantify repetition before proposing log sampling or cleanup: `volume_share_pct` tells you how much of the stream one template accounts for.## Pick the right tool@@ -24,23 +24,28 @@ This is the fastest way to understand what a log stream is _saying_ without read# Reading the response-- `pattern` — the mined template. Masked tokens: `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied.+- `source` reports what was used: `stored_patterns` for exact stored-pattern aggregation followed by Drain3 grouping, or `body_mining` for body masking and Drain3. Include this distinction in your answer.+- `pattern_version` identifies the version used for stored patterns. `fallback_reason` explains body mining: flag disabled, insufficient version coverage, an empty window, or comparison mode.+- The `logs_patterns_query_v2` flag enables the stored-pattern path only when one version supplies nonempty patterns for at least 99% of **all** matching rows. This is the dominant version, not necessarily the newest.+- On the stored-pattern path, `represented_count` counts the rows in the returned groups. `remainder_count` accounts for other versions, unstamped rows, the long tail and groups outside the display limit. Report this remainder rather than implying the returned groups cover everything.+- `pattern` — the template. Body mining masks `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied. Stored patterns use the ingestion vocabulary instead: `<N>`, `<TIMESTAMP>`, `<KLOGTIME>`, `<UUID>`, `<IP>`, `<HOST>`, `<HEX>`, `<ID>`, `<EMAIL>`, `<JSON_ARRAY>`, and `<JSON:keys>` for a JSON body reduced to its key set.- `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.+- `severity_counts` — occurrences per severity, never extrapolated: sample counts when `sampled` is true, exact counts over every matching row otherwise. 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 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.+- `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. Always null on the stored-pattern path, which pivots with `match_patterns` instead, and null on the mining path 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. Also null on the stored-pattern path.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.## Pivoting to a pattern's raw lines-To fetch the lines behind a pattern, call `query-logs` with a message filter in `filterGroup`:+To fetch the lines behind a pattern, call `query-logs` with the appropriate filters in `filterGroup`:+- If `match_patterns` is nonempty, use **both** exact filters instead of a message predicate: `{ "key": "pattern", "value": ["<canonical member>", "..."], "operator": "exact", "type": "log" }` and `{ "key": "pattern_version", "value": 3, "operator": "exact", "type": "log" }`. Substitute the returned members and version, and combine the filters with AND. Keep the original time range and filters. Do not narrow these exact groups using example services or severities.- If `match_regex` is set: `{ "key": "message", "value": "<match_regex>", "operator": "regex", "type": "log" }`- Else if `match_literal` is set: `{ "key": "message", "value": "<match_literal>", "operator": "icontains", "type": "log" }`-Also 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.+For body-mined patterns, also 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.# Parametersdiff --git a/products/logs/mcp/prompts/query-logs.md b/products/logs/mcp/prompts/query-logs.mdindex fb35b6aba1ad..046f75dc77ae 100644--- a/products/logs/mcp/prompts/query-logs.md+++ b/products/logs/mcp/prompts/query-logs.md@@ -34,7 +34,7 @@ Use property filters via the `query.filterGroup` field to narrow results. Only iWhen using a property filter, you should:- **Choose the right type.** Log property types are:- - `log` — filters the log body/message. Use key "message" for this type.+ - `log` — filters the log body or a top-level log column. Use key "message" for the body text, or "pattern" and "pattern_version" (returned by `logs-patterns`), "severity_level", "service_name", "trace_id", "span_id".- `log_attribute` — filters log-level attributes (e.g. "k8s.container.name", "http.method").- `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).- **Use `logs-attributes-list` to discover available attribute keys** before building filters.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 58ab94fe1c3b..3dcc2a248b42 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7556,7 +7556,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\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\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\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```",+ "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\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\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\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_patterns`, or `match_regex` and `match_literal` when it is empty (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- `source` reports what was used: `stored_patterns` for exact stored-pattern aggregation followed by Drain3 grouping, or `body_mining` for body masking and Drain3. Include this distinction in your answer.\n- `pattern_version` identifies the version used for stored patterns. `fallback_reason` explains body mining: flag disabled, insufficient version coverage, an empty window, or comparison mode.\n- The `logs_patterns_query_v2` flag enables the stored-pattern path only when one version supplies nonempty patterns for at least 99% of **all** matching rows. This is the dominant version, not necessarily the newest.\n- On the stored-pattern path, `represented_count` counts the rows in the returned groups. `remainder_count` accounts for other versions, unstamped rows, the long tail and groups outside the display limit. Report this remainder rather than implying the returned groups cover everything.\n- `pattern` — the template. Body mining masks `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied. Stored patterns use the ingestion vocabulary instead: `<N>`, `<TIMESTAMP>`, `<KLOGTIME>`, `<UUID>`, `<IP>`, `<HOST>`, `<HEX>`, `<ID>`, `<EMAIL>`, `<JSON_ARRAY>`, and `<JSON:keys>` for a JSON body reduced to its key set.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — occurrences per severity, never extrapolated: sample counts when `sampled` is true, exact counts over every matching row otherwise. 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. Always null on the stored-pattern path, which pivots with `match_patterns` instead, and null on the mining path 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. Also null on the stored-pattern path.\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 the appropriate filters in `filterGroup`:\n\n- If `match_patterns` is nonempty, use **both** exact filters instead of a message predicate: `{ \"key\": \"pattern\", \"value\": [\"<canonical member>\", \"...\"], \"operator\": \"exact\", \"type\": \"log\" }` and `{ \"key\": \"pattern_version\", \"value\": 3, \"operator\": \"exact\", \"type\": \"log\" }`. Substitute the returned members and version, and combine the filters with AND. Keep the original time range and filters. Do not narrow these exact groups using example services or severities.\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\nFor body-mined patterns, also 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",@@ -9039,7 +9039,7 @@"system_prompt_hint": "LLM/AI trace listing and inspection"},"query-logs": {- "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key \"message\" for this type.\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `[\"posthogDistinctId\"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"posthogDistinctId\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.",+ "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body or a top-level log column. Use key \"message\" for the body text, or \"pattern\" and \"pattern_version\" (returned by `logs-patterns`), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\".\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `[\"posthogDistinctId\"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"posthogDistinctId\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.","category": "Logs","feature": "logs","summary": "Query logs",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex c4c726e35c96..1e8d82ed35ab 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7935,7 +7935,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\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\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\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```",+ "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\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\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\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_patterns`, or `match_regex` and `match_literal` when it is empty (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- `source` reports what was used: `stored_patterns` for exact stored-pattern aggregation followed by Drain3 grouping, or `body_mining` for body masking and Drain3. Include this distinction in your answer.\n- `pattern_version` identifies the version used for stored patterns. `fallback_reason` explains body mining: flag disabled, insufficient version coverage, an empty window, or comparison mode.\n- The `logs_patterns_query_v2` flag enables the stored-pattern path only when one version supplies nonempty patterns for at least 99% of **all** matching rows. This is the dominant version, not necessarily the newest.\n- On the stored-pattern path, `represented_count` counts the rows in the returned groups. `remainder_count` accounts for other versions, unstamped rows, the long tail and groups outside the display limit. Report this remainder rather than implying the returned groups cover everything.\n- `pattern` — the template. Body mining masks `<uuid>`, `<ip>`, `<hex>`, `<num>`, and `<*>` for any word position that varied. Stored patterns use the ingestion vocabulary instead: `<N>`, `<TIMESTAMP>`, `<KLOGTIME>`, `<UUID>`, `<IP>`, `<HOST>`, `<HEX>`, `<ID>`, `<EMAIL>`, `<JSON_ARRAY>`, and `<JSON:keys>` for a JSON body reduced to its key set.\n- `estimated_count` / `estimated_error_count` — occurrences extrapolated to the full window. When `sampled` is false these are exact.\n- `severity_counts` — occurrences per severity, never extrapolated: sample counts when `sampled` is true, exact counts over every matching row otherwise. 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. Always null on the stored-pattern path, which pivots with `match_patterns` instead, and null on the mining path 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. Also null on the stored-pattern path.\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 the appropriate filters in `filterGroup`:\n\n- If `match_patterns` is nonempty, use **both** exact filters instead of a message predicate: `{ \"key\": \"pattern\", \"value\": [\"<canonical member>\", \"...\"], \"operator\": \"exact\", \"type\": \"log\" }` and `{ \"key\": \"pattern_version\", \"value\": 3, \"operator\": \"exact\", \"type\": \"log\" }`. Substitute the returned members and version, and combine the filters with AND. Keep the original time range and filters. Do not narrow these exact groups using example services or severities.\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\nFor body-mined patterns, also 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",@@ -9597,7 +9597,7 @@"system_prompt_hint": "LLM/AI trace listing and inspection"},"query-logs": {- "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key \"message\" for this type.\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `[\"posthogDistinctId\"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"posthogDistinctId\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.",+ "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body or a top-level log column. Use key \"message\" for the body text, or \"pattern\" and \"pattern_version\" (returned by `logs-patterns`), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\".\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `[\"posthogDistinctId\"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"posthogDistinctId\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.","category": "Logs","feature": "logs","summary": "Query logs",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 480201a1928e..73c1870ef04d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -40520,6 +40520,22 @@ export namespace Schemas {Unknown: 'unknown',} as const;+ /**+ * * `flag_disabled` - flag_disabled+ * * `insufficient_version_coverage` - insufficient_version_coverage+ * * `empty_window` - empty_window+ * * `comparison` - comparison+ */+ export type FallbackReasonEnum = typeof FallbackReasonEnum[keyof typeof FallbackReasonEnum];+++ export const FallbackReasonEnum = {+ FlagDisabled: 'flag_disabled',+ InsufficientVersionCoverage: 'insufficient_version_coverage',+ EmptyWindow: 'empty_window',+ Comparison: 'comparison',+ } as const;+export type FeatureFlagFilters = { [key: string]: unknown };export type FeatureFlagSurveys = { [key: string]: unknown };@@ -50630,6 +50646,18 @@ export namespace Schemas {readonly updated_at: string | null;}+ /**+ * * `stored_patterns` - stored_patterns+ * * `body_mining` - body_mining+ */+ export type LogsPatternsSourceEnum = typeof LogsPatternsSourceEnum[keyof typeof LogsPatternsSourceEnum];+++ export const LogsPatternsSourceEnum = {+ StoredPatterns: 'stored_patterns',+ BodyMining: 'body_mining',+ } as const;+export interface LogsRetentionRule {/** Unique identifier for this retention rule. */readonly id: string;@@ -90811,12 +90839,12 @@ 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.+ * Occurrences keyed by lowercased severity ("trace" through "fatal"). Never extrapolated, because severity dominance is a proportion that scaling would not change. Sample counts when `sampled` is true, counts over every matching row otherwise.*/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, with the message field extracted from JSON bodies. This is not the raw stored line. */+ /** Original-message example. Body mining normalizes whitespace, extracts JSON message fields and truncates to the mining cap. Stored-pattern aggregation returns the raw body prefix, limited to 4096 Unicode characters. */body: string;/** Severity of the sampled line, e.g. "info", "error". */severity_text: string;@@ -90827,29 +90855,29 @@ export namespace Schemas {}export interface _LogPattern {- /** Mined log template with variable tokens masked, e.g. "Connected to <ip> in <num>ms". Tokens: <timestamp>, <uuid>, <ip>, <hex>, <num>, plus <*> for word positions Drain found to vary. */+ /** Log template with variable tokens masked, e.g. "Connected to <ip> in <num>ms". Body mining masks <timestamp>, <uuid>, <ip>, <hex>, <num>, plus <*> for word positions Drain found to vary. Stored patterns use the ingestion vocabulary instead: <N>, <TIMESTAMP>, <KLOGTIME>, <UUID>, <IP>, <HOST>, <HEX>, <ID>, <EMAIL>, <JSON_ARRAY>, and <JSON:keys> for a JSON body reduced to its key set. */pattern: string;/** Occurrences of this pattern within the sample. When `sampled` is true this is a sample count, not the full-window total — prefer `estimated_count` for display. */count: number;/** Estimated occurrences across the full window, extrapolated from the sample (`count / scanned_count * total_count`). Equals `count` when the window was not sampled. */estimated_count: number;- /** Share of the sampled log volume this pattern represents (0–100). */+ /** Share of the log volume this pattern represents (0–100). Measured over the sample when `sampled` is true, over every matching row otherwise. */volume_share_pct: number;- /** Sampled occurrences at severity "error" or "fatal". Prefer `estimated_error_count` for display. */+ /** Occurrences at severity "error" or "fatal". A sample count when `sampled` is true, so prefer `estimated_error_count` for display. */error_count: number;/** Estimated error/fatal occurrences across the full window, extrapolated from the sample. Equals `error_count` when the window was not sampled. */estimated_error_count: number;- /** ISO 8601 timestamp of the earliest sampled occurrence. */+ /** ISO 8601 timestamp of the earliest occurrence. Taken from the sample when `sampled` is true, from every matching row otherwise. */first_seen: string;- /** ISO 8601 timestamp of the latest sampled occurrence. */+ /** ISO 8601 timestamp of the latest occurrence. Taken from the sample when `sampled` is true, from every matching row otherwise. */last_seen: string;/** Up to 10 distinct sampled log lines that produced this pattern, with severity, service, and timestamp for display. */examples: _LogPatternExample[];/** Up to 4 distinct service names this pattern was observed in. */services: string[];- /** Estimated occurrences per time bucket, aligned index-for-index with the response's `sparkline_buckets`. Extrapolated from the sample like `estimated_count`, so it shows the volume shape over the window, not exact per-bucket tallies. */+ /** Occurrences per time bucket, aligned index-for-index with the response's `sparkline_buckets`. When `sampled` is true these are extrapolated like `estimated_count` and show the volume shape over the window rather than exact tallies. Otherwise they are exact per-bucket counts. */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. */+ /** Occurrences keyed by lowercased severity ("trace" through "fatal"). Never extrapolated, because severity dominance is a proportion that scaling would not change. Sample counts when `sampled` is true, counts over every matching row otherwise. */severity_counts: _LogPatternSeverityCounts;/*** 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.@@ -90861,6 +90889,13 @@ export namespace Schemas {* @nullable*/match_literal: string | null;+ /** Exact canonical members of a stored-pattern group. Filter pattern IN these values AND pattern_version equals this group's version. Empty for body mining. */+ match_patterns?: string[];+ /**+ * Version required by match_patterns. Null for body mining.+ * @nullable+ */+ pattern_version?: number | null;}/**@@ -90963,7 +90998,7 @@ export namespace Schemas {} as const;export interface _LogPropertyFilter {- /** Attribute key. For type "log", use "message". For "log_attribute"/"log_resource_attribute", use the attribute key (e.g. "k8s.container.name"). */+ /** Attribute key. For type "log", use "message" for the body text, or a log column: "pattern" and "pattern_version" (the patterns pivot), "severity_level", "service_name", "trace_id", "span_id". For "log_attribute"/"log_resource_attribute", use the attribute key (e.g. "k8s.container.name"). */key: string;/** "log" filters the log body/message. "log_attribute" filters log-level attributes. "log_resource_attribute" filters resource-level attributes.*@@ -91261,6 +91296,38 @@ export namespace Schemas {}export interface _LogsPatternsDiffWindow {+ /** Whether counts come from stored-pattern aggregation or body masking and Drain3 mining.+ *+ * * `stored_patterns` - stored_patterns+ * * `body_mining` - body_mining */+ source?: LogsPatternsSourceEnum;+ /**+ * Stored pattern version used. Null for body mining.+ * @nullable+ */+ pattern_version?: number | null;+ /** Why body mining was used. Null for stored-pattern aggregation.+ *+ * * `flag_disabled` - flag_disabled+ * * `insufficient_version_coverage` - insufficient_version_coverage+ * * `empty_window` - empty_window+ * * `comparison` - comparison */+ fallback_reason?: FallbackReasonEnum | null;+ /**+ * Percentage of all matching rows with a nonempty pattern at the selected version. Null for body mining.+ * @nullable+ */+ pattern_coverage_pct?: number | null;+ /**+ * Exact rows represented by the returned stored-pattern groups. Null for body mining.+ * @nullable+ */+ represented_count?: number | null;+ /**+ * Matching rows outside returned groups, including other versions, unstamped rows and the long tail. Null for body mining.+ * @nullable+ */+ remainder_count?: number | null;/** Log rows fed to the miner for this window (sample size). */scanned_count: number;/** Total log rows matching the filters in this window. */@@ -91297,9 +91364,41 @@ export namespace Schemas {}export interface _LogsPatternsResponse {- /** Mined patterns ordered by `count` descending. */+ /** Whether counts come from stored-pattern aggregation or body masking and Drain3 mining.+ *+ * * `stored_patterns` - stored_patterns+ * * `body_mining` - body_mining */+ source?: LogsPatternsSourceEnum;+ /**+ * Stored pattern version used. Null for body mining.+ * @nullable+ */+ pattern_version?: number | null;+ /** Why body mining was used. Null for stored-pattern aggregation.+ *+ * * `flag_disabled` - flag_disabled+ * * `insufficient_version_coverage` - insufficient_version_coverage+ * * `empty_window` - empty_window+ * * `comparison` - comparison */+ fallback_reason?: FallbackReasonEnum | null;+ /**+ * Percentage of all matching rows with a nonempty pattern at the selected version. Null for body mining.+ * @nullable+ */+ pattern_coverage_pct?: number | null;+ /**+ * Exact rows represented by the returned stored-pattern groups. Null for body mining.+ * @nullable+ */+ represented_count?: number | null;+ /**+ * Matching rows outside returned groups, including other versions, unstamped rows and the long tail. Null for body mining.+ * @nullable+ */+ remainder_count?: number | null;+ /** Pattern groups ordered by count. Stored-pattern counts are exact; body-mining counts describe the sample. */patterns: _LogPattern[];- /** Number of log rows fed to the miner (the sample size, capped at the sample limit). */+ /** Rows scanned: the sample size for body mining, or the full matching count for stored-pattern aggregation. */scanned_count: number;/** Total log rows matching the filters in the window, before sampling. Use with `scanned_count` to scale per-pattern counts when `sampled` is true. */total_count: number;diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.tsindex 38f14674b03b..7d924bfeb184 100644--- a/services/mcp/src/generated/logs/api.ts+++ b/services/mcp/src/generated/logs/api.ts@@ -5518,7 +5518,7 @@ export const LogsAttributesRetrieveQueryParams = () => zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -5632,7 +5632,7 @@ export const LogsCountCreateBody = () => zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -5745,7 +5745,7 @@ export const LogsCountRangesCreateBody = () => zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -5871,7 +5871,7 @@ export const LogsFacetValuesCreateBody = () => zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -5977,7 +5977,7 @@ export const LogsPatternsCreateBody = () => zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -6083,7 +6083,7 @@ export const LogsPatternsDiffCreateBody = () => zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -6223,7 +6223,7 @@ export const LogsQueryCreateBody = () => zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -6355,7 +6355,7 @@ export const LogsServicesCreateBody = () => zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -6456,7 +6456,7 @@ export const LogsSparklineCreateBody = () => zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])@@ -6571,7 +6571,7 @@ export const LogsValuesRetrieveQueryParams = () => zod.object({key: zod.string().describe(- 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'+ 'Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'),type: zod.enum(['log', 'log_attribute', 'log_resource_attribute'])diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attribute-values-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attribute-values-list.jsonindex ee8d4f3e6ffb..21c0ba91ed62 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attribute-values-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attribute-values-list.json@@ -40,7 +40,7 @@"items": {"properties": {"key": {- "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "description": "Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").","type": "string"},"operator": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attributes-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attributes-list.jsonindex 05d7deda0cd1..4de54d1ff0ec 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attributes-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-attributes-list.json@@ -40,7 +40,7 @@"items": {"properties": {"key": {- "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "description": "Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").","type": "string"},"operator": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-count-ranges.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-count-ranges.jsonindex 8fb6a069af30..a548b2a0abdd 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-count-ranges.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-count-ranges.json@@ -37,7 +37,7 @@"items": {"properties": {"key": {- "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "description": "Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").","type": "string"},"operator": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-count.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-count.jsonindex ce4f20c994c2..5dc6fe3d58dc 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-count.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-count.json@@ -37,7 +37,7 @@"items": {"properties": {"key": {- "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "description": "Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").","type": "string"},"operator": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-facet-values-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-facet-values-create.jsonindex becb21905b47..0fe20955fb5a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-facet-values-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-facet-values-create.json@@ -76,7 +76,7 @@"items": {"properties": {"key": {- "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "description": "Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").","type": "string"},"operator": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns-diff.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns-diff.jsonindex 13756f056284..96ea9a57c285 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns-diff.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns-diff.json@@ -65,7 +65,7 @@"items": {"properties": {"key": {- "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "description": "Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").","type": "string"},"operator": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns.jsonindex bf869cb0324a..8f33f45fe13f 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns.json@@ -37,7 +37,7 @@"items": {"properties": {"key": {- "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "description": "Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").","type": "string"},"operator": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-services-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-services-create.jsonindex e9c6a0f6c0c5..db01bea830ce 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-services-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-services-create.json@@ -37,7 +37,7 @@"items": {"properties": {"key": {- "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "description": "Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").","type": "string"},"operator": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.jsonindex bbcf70a06b2d..5572cec5a688 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.json@@ -38,7 +38,7 @@"items": {"properties": {"key": {- "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "description": "Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").","type": "string"},"operator": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.jsonindex 842314a67023..4f7b8b341949 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json@@ -55,7 +55,7 @@"items": {"properties": {"key": {- "description": "Attribute key. For type \"log\", use \"message\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").",+ "description": "Attribute key. For type \"log\", use \"message\" for the body text, or a log column: \"pattern\" and \"pattern_version\" (the patterns pivot), \"severity_level\", \"service_name\", \"trace_id\", \"span_id\". For \"log_attribute\"/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").","type": "string"},"operator": {