: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): pattern diff engine comparing two windows (#69694)
Jon McCallum71c3485ae914
diff --git a/products/logs/backend/log_patterns.py b/products/logs/backend/log_patterns.pyindex 65497ed8b7e9..eb71fd2fa9f7 100644--- a/products/logs/backend/log_patterns.py+++ b/products/logs/backend/log_patterns.py@@ -8,7 +8,7 @@ from typing import TypeVarfrom products.logs.backend.vendor.drain3 import Drain, LogMasker, MaskingInstruction-_ERROR_SEVERITIES = {"error", "fatal"}+ERROR_SEVERITIES = {"error", "fatal"}# Masking collapses high-cardinality variable tokens into named placeholders before# clustering, so templates stay readable ("<ip>", "<num>") instead of fragmenting into@@ -122,17 +122,36 @@ def _escape_literal(text: str) -> str:return r"\s+".join(re.escape(token) for token in text.split(" "))+def _literal_runs(template: str) -> list[str]:+ # Stripped, non-empty literal fragments between the template's placeholders.+ return [stripped for literal in _PLACEHOLDER_RE.split(template) if (stripped := literal.strip())]++def extract_match_literal(template: str) -> str | None:"""Longest literal run in a template — the plain-text fallback predicate when thecompiled regex fails validation. None when the template has no usable literal content."""longest = ""- for literal in _PLACEHOLDER_RE.split(template):- stripped = literal.strip()- if len(stripped) > len(longest):- longest = stripped+ for literal in _literal_runs(template):+ if len(literal) > len(longest):+ longest = literalreturn longest if len(longest) >= _MIN_LITERAL_CHARS else None+def pattern_fingerprint(template: str) -> str:+ """Cross-run identity key for a mined template.++ Drain templates are not stable across independent mining runs — sampling and row-order+ differences can widen a placeholder ("User <*> not found" vs "User <num> not found"), so+ matching on the raw template string would false-split the same message across windows.+ Keying on the sorted set of literal runs between placeholders survives that wobble:+ placeholder kind and position drop out, literal content remains. A placeholder inserted+ *inside* a literal run splits it and changes the fingerprint — that is content-level+ divergence, not wobble, so the two templates are correctly treated as different patterns.+ """+ literals = sorted(set(_literal_runs(template)))+ return "\x00".join(literals) if literals else template++def compile_match_regex(template: str, examples: list[LogSample], truncate: int) -> str | None:"""Compile a mined template into an RE2-safe regex over raw log bodies, self-validatedagainst the pattern's own examples.@@ -262,7 +281,7 @@ def mine_patterns(pattern=acc.template,count=acc.count,volume_share_pct=round(acc.count / total * 100, 2),- error_count=sum(acc.severity_counts.get(s, 0) for s in _ERROR_SEVERITIES),+ error_count=sum(acc.severity_counts.get(s, 0) for s in ERROR_SEVERITIES),first_seen=acc.first_seen,last_seen=acc.last_seen,examples=acc.examples,diff --git a/products/logs/backend/pattern_diff.py b/products/logs/backend/pattern_diff.pynew file mode 100644index 000000000000..83a4b4f8cb8d--- /dev/null+++ b/products/logs/backend/pattern_diff.py@@ -0,0 +1,196 @@+import datetime as dt+from typing import TYPE_CHECKING++from posthog.schema import DateRange, LogsQuery++from posthog.hogql_queries.query_runner import ExecutionMode++from products.logs.backend.log_patterns import ERROR_SEVERITIES, _env, pattern_fingerprint+from products.logs.backend.patterns_query_runner import PatternsQueryRunner++if TYPE_CHECKING:+ from posthog.models import Team++_BASELINE_OFFSET = dt.timedelta(days=7)+++def _rate(estimated_count: float, window: tuple[dt.datetime, dt.datetime]) -> float:+ seconds = (window[1] - window[0]).total_seconds()+ return estimated_count / seconds if seconds > 0 else 0.0+++def _has_error_severity(pattern: dict) -> bool:+ return any(severity in ERROR_SEVERITIES for severity in pattern.get("severity_counts", {}))+++def _group_by_fingerprint(patterns: list[dict]) -> dict[str, list[dict]]:+ grouped: dict[str, list[dict]] = {}+ for pattern in patterns:+ grouped.setdefault(pattern_fingerprint(pattern["pattern"]), []).append(pattern)+ return grouped+++def _representative(group: list[dict]) -> dict:+ return max(group, key=lambda p: p["estimated_count"])+++def _group_totals(group: list[dict]) -> tuple[int, int, float]:+ # (raw sample count, estimated count, volume share) summed across templates that share a+ # fingerprint — template wobble can split one message across clusters within a single run too.+ return (+ sum(p["count"] for p in group),+ sum(p["estimated_count"] for p in group),+ round(sum(p["volume_share_pct"] for p in group), 2),+ )+++def diff_patterns(+ current: list[dict],+ baseline: list[dict],+ *,+ current_window: tuple[dt.datetime, dt.datetime],+ baseline_window: tuple[dt.datetime, dt.datetime],+) -> list[dict]:+ """Classify serialized mined patterns from a current window against a baseline window.++ Classifications:+ * ``new`` — in current only, above the novelty floor (volume share, or any error/fatal line).+ Sampled mining cannot see arbitrarily rare templates, so below the floor absence from the+ baseline is not evidence of novelty and the entry stays ``unchanged``.+ * ``rate_shift`` — on both sides with the window-length-normalized rate changed by at least+ the shift ratio, and enough raw samples on both sides to trust the estimates.+ * ``gone`` — in baseline only, above the same floor. Below-floor disappearances are dropped+ entirely (nothing useful to show).+ * ``unchanged`` — everything else; "no confident claim", not "provably identical".+ """+ new_min_share = _env("LOGS_PATTERNS_DIFF_NEW_MIN_SHARE", 1.0, float)+ shift_ratio = _env("LOGS_PATTERNS_DIFF_SHIFT_RATIO", 2.0, float)+ min_samples = _env("LOGS_PATTERNS_DIFF_MIN_SAMPLES", 5, int)+ if shift_ratio <= 1:+ # A ratio at or below 1 is meaningless (everything or nothing shifts) and 0 would+ # divide by zero below — treat a misconfigured env var as the default.+ shift_ratio = 2.0++ current_groups = _group_by_fingerprint(current)+ baseline_groups = _group_by_fingerprint(baseline)++ def above_floor(share: float, group: list[dict]) -> bool:+ # Error severity is checked across every template in the group, not just the+ # representative: within-run fingerprint collision can bury a genuinely new+ # error-severity template behind a larger non-error one.+ return share >= new_min_share or any(_has_error_severity(p) for p in group)++ entries = []+ for fingerprint, group in current_groups.items():+ pattern = _representative(group)+ raw_count, estimated_count, share = _group_totals(group)+ baseline_group = baseline_groups.get(fingerprint)++ if baseline_group is None:+ entries.append(_entry("new" if above_floor(share, group) else "unchanged", pattern))+ continue++ base_raw, base_estimated, base_share = _group_totals(baseline_group)+ baseline_rate = _rate(base_estimated, baseline_window)+ current_rate = _rate(estimated_count, current_window)+ ratio = round(current_rate / baseline_rate, 2) if baseline_rate > 0 else None+ shifted = (+ ratio is not None+ and (ratio >= shift_ratio or ratio <= 1 / shift_ratio)+ and min(raw_count, base_raw) >= min_samples+ )+ entries.append(+ _entry(+ "rate_shift" if shifted else "unchanged",+ pattern,+ baseline_estimated=base_estimated,+ baseline_share=base_share,+ rate_ratio=ratio,+ )+ )++ for fingerprint, group in baseline_groups.items():+ if fingerprint in current_groups:+ continue+ pattern = _representative(group)+ _raw, base_estimated, base_share = _group_totals(group)+ if above_floor(base_share, group):+ entries.append(_entry("gone", pattern, baseline_estimated=base_estimated, baseline_share=base_share))++ order = {"new": 0, "rate_shift": 1, "gone": 2, "unchanged": 3}++ def magnitude(entry: dict) -> float:+ ratio = entry["rate_ratio"]+ if entry["classification"] == "rate_shift" and ratio is not None:+ # A ratio rounded down to 0.0 is the most extreme drop we can express, not "no shift".+ return max(ratio, 1 / ratio) if ratio > 0 else float("inf")+ return float(entry["pattern"]["estimated_count"])++ entries.sort(key=lambda e: (order[e["classification"]], -magnitude(e), e["pattern"]["pattern"]))+ return entries+++def _entry(+ classification: str,+ pattern: dict,+ *,+ baseline_estimated: int | None = None,+ baseline_share: float | None = None,+ rate_ratio: float | None = None,+) -> dict:+ return {+ "classification": classification,+ "rate_ratio": rate_ratio,+ "pattern": pattern,+ "baseline_estimated_count": baseline_estimated,+ "baseline_volume_share_pct": baseline_share,+ }+++def run_patterns_diff(team: "Team", query: LogsQuery, baseline_date_range: DateRange | None) -> dict:+ """Mine the query's window and a baseline window, and return classified diff entries.++ The baseline defaults to the same window shifted back one week — log streams have strong+ daily/weekly cycles, so last week's identical window is a fairer expectation than the+ preceding hour. The current window is resolved once and the baseline derived from the+ resolved bounds, so a relative ``date_from`` (e.g. ``-1h``) can't drift between the two runs.+ """+ current_runner = PatternsQueryRunner(team=team, query=query)+ current_from = current_runner.query_date_range.date_from()+ current_to = current_runner.query_date_range.date_to()++ if baseline_date_range is None:+ baseline_date_range = DateRange(+ date_from=(current_from - _BASELINE_OFFSET).isoformat(),+ date_to=(current_to - _BASELINE_OFFSET).isoformat(),+ )+ baseline_query = query.model_copy(update={"dateRange": baseline_date_range})+ baseline_runner = PatternsQueryRunner(team=team, query=baseline_query)+ baseline_from = baseline_runner.query_date_range.date_from()+ baseline_to = baseline_runner.query_date_range.date_to()++ current_results = current_runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS).results+ baseline_results = baseline_runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS).results++ entries = diff_patterns(+ current_results["patterns"],+ baseline_results["patterns"],+ current_window=(current_from, current_to),+ baseline_window=(baseline_from, baseline_to),+ )+ return {+ "entries": entries,+ "current": _window_meta(current_results, current_from, current_to),+ "baseline": _window_meta(baseline_results, baseline_from, baseline_to),+ }+++def _window_meta(results: dict, date_from: dt.datetime, date_to: dt.datetime) -> dict:+ return {+ "scanned_count": results["scanned_count"],+ "total_count": results["total_count"],+ "sampled": results["sampled"],+ "sample_coverage_pct": results["sample_coverage_pct"],+ "date_from": date_from.isoformat(),+ "date_to": date_to.isoformat(),+ }diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex e019b4003024..64c06bec22fc 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -14,6 +14,7 @@ from rest_framework.decorators import actionfrom rest_framework.exceptions import ParseErrorfrom rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework.throttling import BaseThrottlefrom posthog.schema import (DateRange,@@ -36,6 +37,7 @@ from posthog.event_usage import get_request_analytics_properties, report_user_acfrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.hogql_queries.utils.time_sliced_query import time_sliced_resultsfrom posthog.models import User+from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottlefrom posthog.tasks.exporter import export_assetfrom products.exports.backend.models.exported_asset import ExportedAsset@@ -63,6 +65,7 @@ from products.logs.backend.logs_query_runner import (LogsQueryResponse,LogsQueryRunner,)+from products.logs.backend.pattern_diff import run_patterns_difffrom products.logs.backend.patterns_query_runner import PatternsQueryRunnerfrom products.logs.backend.presentation.views.alerts_api import LogsAlertViewSetfrom products.logs.backend.presentation.views.explain import LogExplainViewSet@@ -827,6 +830,97 @@ class _LogsPatternsResponseSerializer(serializers.Serializer):)+class _LogsPatternsDiffRequestSerializer(serializers.Serializer):+ query = _LogsPatternsBodySerializer(+ help_text=(+ "The patterns query for the current (foreground) window: date range plus any "+ "severity/service/search/property filters. The same filters are applied to the baseline window."+ ),+ )+ baselineDateRange = _DateRangeSerializer(+ required=False,+ help_text=(+ "Baseline window to compare against. Omit to default to the current window shifted "+ "back exactly one week, which absorbs daily and weekly log-volume cycles. Pass an "+ "explicit range to compare against a specific period, e.g. pre-deploy or pre-incident."+ ),+ )+++class _LogPatternDiffEntrySerializer(serializers.Serializer):+ classification = serializers.ChoiceField(+ choices=["new", "rate_shift", "gone", "unchanged"],+ help_text=(+ '"new": appears only in the current window and clears the novelty floor (at least ~1% '+ 'volume share, or any error/fatal occurrences). "rate_shift": present in both windows '+ "with the per-second rate changed by at least 2x either way, backed by enough samples "+ 'on both sides to trust the estimates. "gone": cleared the floor in the baseline but '+ 'absent from the current window. "unchanged" means "no confident claim", not "provably '+ 'identical" — sampled mining cannot prove a below-floor template is genuinely new or gone.'+ ),+ )+ rate_ratio = serializers.FloatField(+ allow_null=True,+ help_text=(+ "Current-window rate divided by baseline rate, both normalized per second so windows "+ "of different lengths compare fairly. 4.0 means 4x faster now; 0.25 means quartered. "+ "Null when the pattern is missing from either window."+ ),+ )+ pattern = _LogPatternSerializer(+ help_text=(+ "The mined pattern with full stats. Taken from the current window, or from the "+ 'baseline window for "gone" entries. When template wobble split one message across '+ "several near-identical templates, this is the highest-volume representative and the "+ "entry's classification reflects their combined counts."+ ),+ )+ baseline_estimated_count = serializers.IntegerField(+ allow_null=True,+ help_text=(+ "Estimated occurrences across the baseline window (extrapolated like `estimated_count`). "+ "Null when the pattern was not seen in the baseline sample."+ ),+ )+ baseline_volume_share_pct = serializers.FloatField(+ allow_null=True,+ help_text="Share of the baseline sample this pattern represented (0-100). Null when absent from the baseline.",+ )+++class _LogsPatternsDiffWindowSerializer(serializers.Serializer):+ 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(+ help_text="True when this window's counts are extrapolated from a sample rather than exact.",+ )+ sample_coverage_pct = serializers.FloatField(+ help_text="Share of this window's rows eligible for sampling (0-100); below 100 the scan was time-slice bounded.",+ )+ date_from = serializers.CharField(help_text="Resolved window start (ISO 8601, inclusive).")+ date_to = serializers.CharField(help_text="Resolved window end (ISO 8601, exclusive).")+++class _LogsPatternsDiffResponseSerializer(serializers.Serializer):+ entries = _LogPatternDiffEntrySerializer(+ many=True,+ help_text=(+ 'Classified diff entries, most interesting first: "new" (by estimated count), then '+ '"rate_shift" (by shift magnitude), then "gone", then "unchanged". A pattern in the '+ "baseline is matched to the current window by literal-content fingerprint, so a "+ "placeholder widening between runs does not read as one pattern vanishing and another appearing."+ ),+ )+ current = _LogsPatternsDiffWindowSerializer(help_text="Mining metadata for the current window.")+ baseline = _LogsPatternsDiffWindowSerializer(+ help_text=(+ "Mining metadata for the baseline window. Check `total_count` before trusting a wall "+ 'of "new" entries: an empty or tiny baseline (e.g. logging only started this week) '+ "makes everything look new."+ ),+ )++class _LogsGroupByBodySerializer(serializers.Serializer):dateRange = _DateRangeSerializer(required=False,@@ -955,6 +1049,14 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):scope_object = "logs"serializer_class = _FallbackSerializer+ def get_throttles(self) -> list[BaseThrottle]:+ # patterns_diff mines two windows per request (current + baseline), roughly doubling the+ # ClickHouse work of a single patterns query, so it uses the tighter ClickHouse-specific+ # throttles rather than the default per-project request limits.+ if self.action == "patterns_diff":+ return [ClickHouseBurstRateThrottle(), ClickHouseSustainedRateThrottle()]+ return super().get_throttles()+@staticmethoddef _normalize_filter_group(filter_group: object) -> dict:"""Normalize a flat filter array (from MCP) to the nested PropertyGroupFilter structure."""@@ -966,6 +1068,19 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):return filter_groupreturn {"type": "AND", "values": []}+ def _filtered_logs_query(self, query_data: dict) -> LogsQuery:+ """The shared date-range + filters subset of LogsQuery used by aggregation actions."""+ date_range_data = query_data.get("dateRange")+ return LogsQuery(+ # The body serializers document dateRange as optional, so an absent range must+ # default rather than 400 (get_model rejects None).+ dateRange=self.get_model(date_range_data, DateRange) if date_range_data else DateRange(date_from="-1h"),+ severityLevels=query_data.get("severityLevels", []),+ serviceNames=query_data.get("serviceNames", []),+ searchTerm=query_data.get("searchTerm", None),+ filterGroup=self._normalize_filter_group(query_data.get("filterGroup", None)),+ )+@extend_schema(request=_LogsQueryRequestSerializer, responses={200: _LogsQueryResponseSerializer})@action(detail=False, methods=["POST"], required_scopes=["logs:read"])def query(self, request: Request, *args, **kwargs) -> Response:@@ -1309,13 +1424,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):tag_queries(product=Product.LOGS, feature=Feature.QUERY)query_data = request.data.get("query", {})- query = LogsQuery(- dateRange=self.get_model(query_data.get("dateRange"), DateRange),- severityLevels=query_data.get("severityLevels", []),- serviceNames=query_data.get("serviceNames", []),- searchTerm=query_data.get("searchTerm", None),- filterGroup=self._normalize_filter_group(query_data.get("filterGroup", None)),- )+ query = self._filtered_logs_query(query_data)runner = PatternsQueryRunner(team=self.team, query=query)response = runner.run(@@ -1342,19 +1451,45 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):return Response(response.results, status=status.HTTP_200_OK)+ @extend_schema(request=_LogsPatternsDiffRequestSerializer, responses={200: _LogsPatternsDiffResponseSerializer})+ @action(detail=False, methods=["POST"], required_scopes=["logs:read"], url_path="patterns_diff")+ def patterns_diff(self, request: Request, *args, **kwargs) -> Response:+ tag_queries(product=Product.LOGS, feature=Feature.QUERY)+ query_data = request.data.get("query", {})++ query = self._filtered_logs_query(query_data)+ baseline_date_range = (+ self.get_model(request.data["baselineDateRange"], DateRange)+ if request.data.get("baselineDateRange")+ else None+ )++ results = run_patterns_diff(self.team, query, baseline_date_range)++ report_user_action(+ request.user,+ "logs patterns diff queried",+ {+ "entries_count": len(results["entries"]),+ "changed_count": sum(1 for e in results["entries"] if e["classification"] != "unchanged"),+ "auto_baseline": baseline_date_range is None,+ "has_search_term": bool(query_data.get("searchTerm")),+ "severity_levels_count": len(query_data.get("severityLevels", [])),+ "service_names_count": len(query_data.get("serviceNames", [])),+ },+ team=self.team,+ request=request,+ )++ return Response(results, status=status.HTTP_200_OK)+@extend_schema(request=_LogsGroupByRequestSerializer, responses={200: _LogsGroupByResponseSerializer})@action(detail=False, methods=["POST"], required_scopes=["logs:read"], url_path="group-by")def group_by(self, request: Request, *args, **kwargs) -> Response:tag_queries(product=Product.LOGS, feature=Feature.QUERY)query_data = request.data.get("query", {})- query = LogsQuery(- dateRange=self.get_model(query_data.get("dateRange"), DateRange),- severityLevels=query_data.get("severityLevels", []),- serviceNames=query_data.get("serviceNames", []),- searchTerm=query_data.get("searchTerm", None),- filterGroup=self._normalize_filter_group(query_data.get("filterGroup", None)),- )+ query = self._filtered_logs_query(query_data)try:runner = LogsGroupByQueryRunner(diff --git a/products/logs/backend/test/test_pattern_diff.py b/products/logs/backend/test/test_pattern_diff.pynew file mode 100644index 000000000000..bffe7a0dda3e--- /dev/null+++ b/products/logs/backend/test/test_pattern_diff.py@@ -0,0 +1,231 @@+import json+import datetime as dt++from freezegun import freeze_time+from posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest import TestCase++from parameterized import parameterized++from posthog.schema import DateRange, FilterLogicalOperator, LogsQuery, PropertyGroupFilter++from posthog.clickhouse.client import sync_execute++from products.logs.backend.log_patterns import pattern_fingerprint+from products.logs.backend.pattern_diff import diff_patterns, run_patterns_diff++_HOUR = (dt.datetime(2026, 6, 23, 12, 0), dt.datetime(2026, 6, 23, 13, 0))+_BASELINE_HOUR = (dt.datetime(2026, 6, 16, 12, 0), dt.datetime(2026, 6, 16, 13, 0))+_BASELINE_TWO_HOURS = (dt.datetime(2026, 6, 16, 11, 0), dt.datetime(2026, 6, 16, 13, 0))+++def _pattern(template: str, *, count: int = 50, share: float = 10.0, severities: dict | None = None) -> dict:+ # Only the fields the diff reads; the runner's serializer owns the full shape.+ return {+ "pattern": template,+ "count": count,+ "estimated_count": count,+ "volume_share_pct": share,+ "severity_counts": severities if severities is not None else {"info": count},+ }+++class TestPatternFingerprint(TestCase):+ @parameterized.expand(+ [+ ("placeholder_kind_wobble", "User <*> not found", "User <num> not found", True),+ ("placeholder_widening_preserved_literals", "job <*> done in <num>ms", "job <hex> done in <*>ms", True),+ ("different_literals", "User <*> not found", "User <*> deleted", False),+ ("literal_split_changes_content", "User <*> not found", "User <*> not <*>", False),+ ]+ )+ def test_fingerprint_matches_across_template_wobble(self, _name, a, b, expected_equal) -> None:+ assert (pattern_fingerprint(a) == pattern_fingerprint(b)) is expected_equal++ def test_all_placeholder_template_falls_back_to_raw_template(self) -> None:+ assert pattern_fingerprint("<*> <num>") == "<*> <num>"+ assert pattern_fingerprint("<*> <num>") != pattern_fingerprint("<*> <ip>")+++class TestDiffPatterns(TestCase):+ def _diff(self, current, baseline, baseline_window=_BASELINE_HOUR):+ return diff_patterns(current, baseline, current_window=_HOUR, baseline_window=baseline_window)++ @parameterized.expand(+ [+ # (name, share, severities, expected_classification)+ ("above_share_floor", 5.0, {"info": 50}, "new"),+ ("below_floor_with_errors", 0.2, {"error": 2}, "new"),+ ("below_floor_info_no_claim", 0.2, {"info": 2}, "unchanged"),+ ]+ )+ def test_novelty_floor(self, _name, share, severities, expected) -> None:+ entries = self._diff([_pattern("fresh template here", count=2, share=share, severities=severities)], [])+ assert entries[0]["classification"] == expected++ @parameterized.expand(+ [+ # (name, current_count, baseline_count, expected_classification, expected_ratio)+ ("doubled", 100, 50, "rate_shift", 2.0),+ ("halved", 50, 100, "rate_shift", 0.5),+ ("within_band", 60, 50, "unchanged", 1.2),+ ]+ )+ def test_rate_shift_thresholds(self, _name, cur, base, expected, ratio) -> None:+ entries = self._diff([_pattern("api call took long", count=cur)], [_pattern("api call took long", count=base)])+ assert entries[0]["classification"] == expected+ assert entries[0]["rate_ratio"] == ratio+ assert entries[0]["baseline_estimated_count"] == base++ def test_shift_needs_enough_samples_on_both_sides(self) -> None:+ # A 4x ratio built on 4 baseline samples is sampling noise, not a claim.+ entries = self._diff([_pattern("rare thing", count=16)], [_pattern("rare thing", count=4)])+ assert entries[0]["classification"] == "unchanged"++ def test_rates_are_normalized_by_window_length(self) -> None:+ # Same estimated count over half the window time = 2x the rate: dropping the+ # normalization would make any unequal-window comparison misclassify.+ entries = self._diff(+ [_pattern("steady heartbeat msg", count=100)],+ [_pattern("steady heartbeat msg", count=100)],+ baseline_window=_BASELINE_TWO_HOURS,+ )+ assert entries[0]["classification"] == "rate_shift"+ assert entries[0]["rate_ratio"] == 2.0++ @parameterized.expand(+ [+ ("above_floor_reported", 5.0, {"info": 50}, ["gone"]),+ ("below_floor_dropped_entirely", 0.2, {"info": 2}, []),+ ]+ )+ def test_gone(self, _name, share, severities, expected_classifications) -> None:+ entries = self._diff([], [_pattern("old template gone", count=2, share=share, severities=severities)])+ assert [e["classification"] for e in entries] == expected_classifications++ def test_wobbled_templates_merge_via_fingerprint_instead_of_new_plus_gone(self) -> None:+ # The same message mined as different placeholder kinds across runs must compare as+ # one pattern — matching on raw template strings would report a false new+gone pair.+ entries = self._diff(+ [_pattern("User <*> not found", count=100)],+ [_pattern("User <num> not found", count=50)],+ )+ assert [e["classification"] for e in entries] == ["rate_shift"]++ def test_within_run_template_splits_are_aggregated_before_classification(self) -> None:+ # Two below-floor fragments of one message must combine (2 x 0.6% = 1.2% > floor)+ # into a single entry classified on their summed counts.+ entries = self._diff(+ [+ _pattern("connect to <ip> failed", count=3, share=0.6),+ _pattern("connect to <*> failed", count=2, share=0.6),+ ],+ [],+ )+ assert len(entries) == 1+ assert entries[0]["classification"] == "new"+ assert entries[0]["pattern"]["pattern"] == "connect to <ip> failed"++ def test_error_severity_on_a_non_representative_group_member_still_clears_the_floor(self) -> None:+ # A below-floor group whose largest (representative) template is info but which contains a+ # smaller error-severity template must surface as "new": the error line is the whole point.+ entries = self._diff(+ [+ _pattern("connect to <ip> failed", count=3, share=0.4, severities={"info": 3}),+ _pattern("connect to <*> failed", count=2, share=0.4, severities={"error": 2}),+ ],+ [],+ )+ assert len(entries) == 1+ assert entries[0]["classification"] == "new"++ def test_entries_ordered_by_interest(self) -> None:+ entries = self._diff(+ [+ _pattern("boring stable msg", count=50),+ _pattern("brand new failure", count=30, share=30.0),+ _pattern("spiking msg here", count=200),+ ],+ [+ _pattern("boring stable msg", count=50),+ _pattern("spiking msg here", count=50),+ _pattern("vanished template msg", count=50, share=50.0),+ ],+ )+ assert [e["classification"] for e in entries] == ["new", "rate_shift", "gone", "unchanged"]+++_FROZEN_NOW = "2026-06-23T13:00:00Z"+++class TestRunPatternsDiff(ClickhouseTestMixin, APIBaseTest):+ def _insert(self, rows: list[dict]) -> None:+ sql = "".join(json.dumps({"team_id": self.team.id, **r}) + "\n" for r in rows)+ sync_execute(f"INSERT INTO logs FORMAT JSONEachRow\n{sql}")++ def _log(self, body: str, *, day: int, severity: str = "info", service: str = "api", minute: int = 0) -> dict:+ return {+ "timestamp": f"2026-06-{day:02d} 12:{minute:02d}:00.000000",+ "body": body,+ "severity_text": severity,+ "service_name": service,+ }++ @freeze_time(_FROZEN_NOW)+ def test_auto_baseline_mines_the_same_window_a_week_earlier(self) -> None:+ # Wiring no pure test can catch: the baseline window must be the resolved current+ # window shifted -7d, with the query's filters carried over, and the whole diff+ # deterministic across reruns.+ current = [self._log(f"User {name} not found", day=23, severity="error") for name in ("alice", "bob", "carol")]+ baseline = [self._log(f"GET /api/orders/{i} ok", day=16) for i in range(3)]+ other_service = [+ self._log("ignore me entirely", day=23, service="db"),+ *[self._log("ignore me entirely", day=16, service="db") for _ in range(2)],+ ]+ self._insert(current + baseline + other_service)++ query = LogsQuery(+ dateRange=DateRange(date_from="2026-06-23T12:00:00Z", date_to="2026-06-23T13:00:00Z"),+ filterGroup=PropertyGroupFilter(type=FilterLogicalOperator.AND_, values=[]),+ severityLevels=[],+ serviceNames=["api"],+ searchTerm=None,+ )++ results = run_patterns_diff(self.team, query, None)++ by_classification = {e["classification"]: e for e in results["entries"]}+ assert by_classification["new"]["pattern"]["pattern"] == "User <*> not found"+ assert by_classification["gone"]["pattern"]["pattern"] == "GET /api/orders/<num> ok"+ # The serviceNames filter reached both windows: the "db" rows appear in neither.+ assert len(results["entries"]) == 2+ assert results["current"]["total_count"] == 3+ assert results["baseline"]["total_count"] == 3+ assert results["baseline"]["date_from"].startswith("2026-06-16T12:00:00")+ assert results["baseline"]["date_to"].startswith("2026-06-16T13:00:00")++ assert run_patterns_diff(self.team, query, None) == results++ @freeze_time(_FROZEN_NOW)+ def test_explicit_baseline_range_is_used_verbatim(self) -> None:+ self._insert(+ [+ self._log("deploy marker line", day=23),+ self._log("deploy marker line", day=20),+ self._log("other thing", day=20),+ ]+ )++ query = LogsQuery(+ dateRange=DateRange(date_from="2026-06-23T12:00:00Z", date_to="2026-06-23T13:00:00Z"),+ filterGroup=PropertyGroupFilter(type=FilterLogicalOperator.AND_, values=[]),+ severityLevels=[],+ serviceNames=[],+ searchTerm=None,+ )+ baseline = DateRange(date_from="2026-06-20T12:00:00Z", date_to="2026-06-20T13:00:00Z")++ results = run_patterns_diff(self.team, query, baseline)++ assert results["baseline"]["date_from"].startswith("2026-06-20T12:00:00")+ assert results["baseline"]["total_count"] == 2diff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsxindex 2747b20bc311..fbef1114d0cb 100644--- a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { LemonBanner, LemonButton, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonSelect, LemonSwitch, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'import type { LemonTableColumns } from '@posthog/lemon-ui'import { Sparkline } from 'lib/components/Sparkline'@@ -10,7 +10,11 @@ import { humanFriendlyLargeNumber, humanFriendlyNumber } from 'lib/utils/numbersimport type { LogMessage } from '~/queries/schema/schema-general'import { LogTag } from 'products/logs/frontend/components/LogTag'-import type { _LogPatternApi, _LogPatternExampleApi } from 'products/logs/frontend/generated/api.schemas'+import type {+ _LogPatternApi,+ _LogPatternDiffEntryApi,+ _LogPatternExampleApi,+} from 'products/logs/frontend/generated/api.schemas'import { logsPatternsLogic } from './logsPatternsLogic'@@ -149,11 +153,68 @@ function renderPatternTemplate(pattern: string): JSX.Element {)}-export function LogsPatterns({ id }: { id: string }): JSX.Element {- const { patterns, patternsResponse, patternsResponseLoading, patternsError, sparklineLabels } = useValues(- logsPatternsLogic({ id })+// Shared cell renderers for the plain and compare tables — the two tables have different row+// types (pattern vs. diff entry), so the columns can't be shared, but a divergence in how the+// same pattern fields render would be silently wrong.+function renderLevelCell(pattern: _LogPatternApi): JSX.Element {+ const severity = dominantSeverity(pattern.severity_counts)+ if (!severity) {+ return <span className="text-muted">-</span>+ }+ const canonical = canonicalSeverity(severity)+ return canonical ? <LogTag level={canonical} /> : <LemonTag>{severity}</LemonTag>+}++function renderServicesCell(pattern: _LogPatternApi): JSX.Element {+ return pattern.services.length ? (+ <span className="text-muted">{pattern.services.join(', ')}</span>+ ) : (+ <span className="text-muted">-</span>)- const { viewMatchingLogs } = useActions(logsPatternsLogic({ id }))+}++function patternsEmptyState(error: string | null, compareEnabled: boolean): string {+ if (error) {+ return `Pattern ${compareEnabled ? 'comparison' : 'analysis'} failed — try a shorter time range or narrower filters`+ }+ return compareEnabled+ ? 'No patterns found in either window for the current filters'+ : 'No patterns found for the current filters'+}++// The compare table's change badge: what happened to this pattern vs. the baseline window.+function ChangeBadge({ entry }: { entry: _LogPatternDiffEntryApi }): JSX.Element {+ if (entry.classification === 'new') {+ return <LemonTag type="success">New</LemonTag>+ }+ if (entry.classification === 'gone') {+ return <LemonTag type="muted">Gone</LemonTag>+ }+ if (entry.classification === 'rate_shift' && entry.rate_ratio !== null) {+ const up = entry.rate_ratio >= 1+ const magnitude = up ? entry.rate_ratio : entry.rate_ratio > 0 ? 1 / entry.rate_ratio : Infinity+ return (+ <LemonTag type={up ? 'warning' : 'default'}>+ {Number.isFinite(magnitude) ? `${magnitude.toFixed(1)}×` : '∞'} {up ? '↑' : '↓'}+ </LemonTag>+ )+ }+ return <span className="text-muted">—</span>+}++export function LogsPatterns({ id }: { id: string }): JSX.Element {+ const {+ patterns,+ patternsResponse,+ patternsResponseLoading,+ patternsError,+ sparklineLabels,+ compareEnabled,+ baselineMode,+ diffResponse,+ diffResponseLoading,+ } = useValues(logsPatternsLogic({ id }))+ const { viewMatchingLogs, setCompareEnabled, setBaselineMode } = useActions(logsPatternsLogic({ id }))const { sampled, scanned_count, total_count, sample_coverage_pct } = patternsResponse// Estimated counts are rounded (not exact-comma-formatted) and prefixed with "~" so a@@ -179,14 +240,7 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {title: 'Level',key: 'severity',width: 0,- render: (_, row) => {- const severity = dominantSeverity(row.severity_counts)- if (!severity) {- return <span className="text-muted">-</span>- }- const canonical = canonicalSeverity(severity)- return canonical ? <LogTag level={canonical} /> : <LemonTag>{severity}</LemonTag>- },+ render: (_, row) => renderLevelCell(row),},{title: 'Pattern',@@ -239,12 +293,7 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {{title: 'Services',key: 'services',- render: (_, row) =>- row.services.length ? (- <span className="text-muted">{row.services.join(', ')}</span>- ) : (- <span className="text-muted">-</span>- ),+ render: (_, row) => renderServicesCell(row),},{title: 'Last seen',@@ -254,9 +303,91 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {},]+ // Like renderEstimate, the "~" marks extrapolated counts — each compare column follows its+ // own window's sampled flag, so an exact count is never dressed up as an estimate.+ const renderWindowCount = (count: number, windowSampled: boolean): string =>+ windowSampled ? `~${humanFriendlyLargeNumber(count)}` : humanFriendlyNumber(count)++ // Compare mode renders diff entries: the pattern columns read from entry.pattern, plus a+ // change badge and both windows' counts. Row order comes from the backend (most+ // interesting first), so no default sort is applied.+ const compareColumns: LemonTableColumns<_LogPatternDiffEntryApi> = [+ {+ title: 'Change',+ key: 'change',+ width: 0,+ render: (_, entry) => <ChangeBadge entry={entry} />,+ },+ {+ title: 'Level',+ key: 'severity',+ width: 0,+ render: (_, entry) => renderLevelCell(entry.pattern),+ },+ {+ title: 'Pattern',+ key: 'pattern',+ render: (_, entry) => renderPatternTemplate(entry.pattern.pattern),+ },+ {+ // For "gone" entries the pattern's stats come from the baseline window, so the+ // current-window count is zero by definition, not pattern.estimated_count.+ title: 'Now',+ key: 'current_count',+ align: 'right',+ render: (_, entry) =>+ entry.classification === 'gone' ? (+ <span className="text-muted">0</span>+ ) : (+ renderWindowCount(entry.pattern.estimated_count, diffResponse?.current.sampled ?? false)+ ),+ },+ {+ title: 'Baseline',+ key: 'baseline_count',+ align: 'right',+ render: (_, entry) =>+ entry.baseline_estimated_count !== null ? (+ renderWindowCount(entry.baseline_estimated_count, diffResponse?.baseline.sampled ?? false)+ ) : (+ <span className="text-muted">0</span>+ ),+ },+ {+ title: 'Services',+ key: 'services',+ render: (_, entry) => renderServicesCell(entry.pattern),+ },+ ]++ const emptyState = patternsEmptyState(patternsError, compareEnabled)+return (<div className="flex-1 min-h-0 overflow-auto" data-attr="logs-patterns">- {sampled && !patternsResponseLoading && !patternsError && (+ <div className="flex items-center gap-2 m-2">+ <LemonSwitch+ checked={compareEnabled}+ onChange={setCompareEnabled}+ label="Compare"+ bordered+ size="small"+ data-attr="logs-patterns-compare-toggle"+ />+ {compareEnabled && (+ <LemonSelect+ size="small"+ loading={diffResponseLoading}+ value={baselineMode}+ onChange={setBaselineMode}+ options={[+ { value: 'lastWeek' as const, label: 'vs. same time last week' },+ { value: 'preceding' as const, label: 'vs. preceding period' },+ ]}+ data-attr="logs-patterns-baseline-mode"+ />+ )}+ </div>+ {!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 ofthe {humanFriendlyLargeNumber(total_count)} matching your filters@@ -269,22 +400,46 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {your filters (a service, a severity, or a shorter time range) to sharpen the sample.</LemonBanner>)}- <LemonTable- columns={columns}- dataSource={patterns}- loading={patternsResponseLoading}- expandable={{- expandedRowRender: (row) => <PatternExpandedRow row={row} onViewMatchingLogs={viewMatchingLogs} />,- }}- defaultSorting={{ columnKey: 'estimated_count', order: -1 }}- emptyState={- patternsError- ? 'Pattern analysis failed — try a shorter time range or narrower filters'- : 'No patterns found for the current filters'- }- rowKey="pattern"- size="small"- />+ {compareEnabled &&+ diffResponse &&+ !diffResponseLoading &&+ !patternsError &&+ diffResponse.baseline.total_count === 0 && (+ <LemonBanner type="warning" className="m-2" data-attr="logs-patterns-empty-baseline">+ The baseline window has no matching logs, so every pattern appears new. Pick a different+ baseline, or widen the filters if logging only started recently.+ </LemonBanner>+ )}+ {compareEnabled ? (+ <LemonTable+ columns={compareColumns}+ dataSource={diffResponse?.entries ?? []}+ loading={diffResponseLoading}+ expandable={{+ expandedRowRender: (entry) => (+ <PatternExpandedRow row={entry.pattern} onViewMatchingLogs={viewMatchingLogs} />+ ),+ }}+ emptyState={emptyState}+ rowKey={(entry) => `${entry.classification}:${entry.pattern.pattern}`}+ size="small"+ />+ ) : (+ <LemonTable+ columns={columns}+ dataSource={patterns}+ loading={patternsResponseLoading}+ expandable={{+ expandedRowRender: (row) => (+ <PatternExpandedRow row={row} onViewMatchingLogs={viewMatchingLogs} />+ ),+ }}+ defaultSorting={{ columnKey: 'estimated_count', order: -1 }}+ emptyState={emptyState}+ rowKey="pattern"+ size="small"+ />+ )}</div>)}diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.tsindex fa45349a355b..829508a2a3bc 100644--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts@@ -6,17 +6,22 @@ import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFimport { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'-import { logsPatternsCreate } from 'products/logs/frontend/generated/api'-import type { _LogsPatternsResponseApi } from 'products/logs/frontend/generated/api.schemas'+import { logsPatternsCreate, logsPatternsDiffCreate } from 'products/logs/frontend/generated/api'+import type {+ _LogsPatternsDiffResponseApi,+ _LogsPatternsResponseApi,+} from 'products/logs/frontend/generated/api.schemas'import { logsPatternsLogic } from './logsPatternsLogic'jest.mock('products/logs/frontend/generated/api', () => ({__esModule: true,logsPatternsCreate: jest.fn(),+ logsPatternsDiffCreate: jest.fn(),}))const mockCreate = logsPatternsCreate as jest.MockedFunction<typeof logsPatternsCreate>+const mockDiffCreate = logsPatternsDiffCreate as jest.MockedFunction<typeof logsPatternsDiffCreate>const ID = 'test-viewer'@@ -51,6 +56,34 @@ const RESPONSE: _LogsPatternsResponseApi = {],}+const DIFF_RESPONSE: _LogsPatternsDiffResponseApi = {+ entries: [+ {+ classification: 'new',+ rate_ratio: null,+ pattern: RESPONSE.patterns[0],+ baseline_estimated_count: null,+ baseline_volume_share_pct: null,+ },+ ],+ current: {+ scanned_count: 3,+ total_count: 3,+ sampled: false,+ sample_coverage_pct: 100,+ date_from: '2026-06-23T12:00:00+00:00',+ date_to: '2026-06-23T13:00:00+00:00',+ },+ baseline: {+ scanned_count: 0,+ total_count: 0,+ sampled: false,+ sample_coverage_pct: 100,+ date_from: '2026-06-16T12:00:00+00:00',+ date_to: '2026-06-16T13:00:00+00:00',+ },+}+describe('logsPatternsLogic', () => {afterEach(resumeKeaLoadersErrors)let logic: ReturnType<typeof logsPatternsLogic.build>@@ -137,6 +170,68 @@ describe('logsPatternsLogic', () => {)})+ 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 question+ // than the table next to it. And once compare is on, filter changes must reload the+ // diff, not the plain mine.+ mockDiffCreate.mockResolvedValue(DIFF_RESPONSE)+ const configLogic = logsViewerConfigLogic({ id: ID })+ configLogic.mount()+ configLogic.actions.setViewMode('patterns')+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPatternsSuccess'])+ const minedQuery = mockCreate.mock.calls[0][1].query++ await expectLogic(logic, () => {+ logic.actions.setCompareEnabled(true)+ }).toDispatchActions(['loadDiff', 'loadDiffSuccess'])++ expect(mockDiffCreate).toHaveBeenCalledWith(expect.any(String), {+ query: minedQuery,+ baselineDateRange: undefined, // 'lastWeek' delegates the -7d default to the backend+ })+ expect(logic.values.diffResponse).toEqual(DIFF_RESPONSE)++ mockDiffCreate.mockClear()+ await expectLogic(logic, () => {+ filtersLogic.actions.setServiceNames(['auth'])+ }).toDispatchActions(['loadDiffSuccess'])+ expect(mockDiffCreate).toHaveBeenCalledTimes(1)+ expect(mockCreate).toHaveBeenCalledTimes(1) // only the original mount load+ })++ it('preceding baseline is the same-length window ending where the current one starts', async () => {+ // Locks the window arithmetic: a drift here (wrong length, overlap, or gap) makes the+ // "vs. preceding period" comparison silently wrong while still returning results.+ mockDiffCreate.mockResolvedValue(DIFF_RESPONSE)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPatternsSuccess'])++ filtersLogic.actions.setDateRange({+ date_from: '2026-06-23T12:00:00.000Z',+ date_to: '2026-06-23T13:00:00.000Z',+ })+ logic.actions.setCompareEnabled(true)+ await expectLogic(logic).toDispatchActions(['loadDiffSuccess'])+ expect(mockDiffCreate).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({ baselineDateRange: undefined })+ )++ logic.actions.setBaselineMode('preceding')+ await expectLogic(logic).toDispatchActions(['loadDiffSuccess'])+ expect(mockDiffCreate).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({+ baselineDateRange: {+ date_from: '2026-06-23T11:00:00.000Z',+ date_to: '2026-06-23T12:00:00.000Z',+ },+ })+ )+ })+it('surfaces a load failure as patternsError and clears it on the next success', async () => {silenceKeaLoadersErrors()// A failed mine (e.g. sampling query over budget) must not render as "no patterns".diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.tsindex b4aac937a293..e2be104634ba 100644--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts@@ -2,6 +2,7 @@ import { actions, afterMount, connect, kea, key, listeners, path, props, reducerimport { loaders } from 'kea-loaders'import { dayjs } from 'lib/dayjs'+import { dateStringToDayJs } from 'lib/utils/dateFilters'import { teamLogic } from 'scenes/teamLogic'import type { LogsQuery } from '~/queries/schema/schema-general'@@ -15,10 +16,11 @@ import {import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'-import { logsPatternsCreate } from 'products/logs/frontend/generated/api'+import { logsPatternsCreate, logsPatternsDiffCreate } from 'products/logs/frontend/generated/api'import type {_LogPatternApi,_LogPropertyFilterApi,+ _LogsPatternsDiffResponseApi,_LogsPatternsResponseApi,} from 'products/logs/frontend/generated/api.schemas'@@ -28,6 +30,11 @@ export interface LogsPatternsLogicProps {id: string}+// 'lastWeek' omits baselineDateRange so the backend defaults to the same window one week+// earlier (absorbs daily/weekly cycles); 'preceding' compares against the window immediately+// before the current one (the post-deploy / incident-onset comparison).+export type PatternsBaselineMode = 'lastWeek' | 'preceding'+// The severity filter is an exact match on these six buckets; a sampled severity outside them// (e.g. "notice") can't be expressed, so applying the filter would silently exclude those lines.const CANONICAL_SEVERITIES = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']@@ -37,6 +44,24 @@ const CANONICAL_SEVERITIES = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'// severity_counts has no cap, so it never needs this guard.const SERVICES_LIST_CAP = 4+// Explicit baseline window for 'preceding' mode: the same-length window ending where the+// current one starts. Computed at request time (not memoized) because a relative range like+// "-1h" resolves against "now" — a cached computation would drift away from the current+// window the backend resolves at query time. 'lastWeek' sends no baseline: the backend's+// default is the current window shifted back one week, from its own resolved bounds.+export function precedingDateRange(utcDateRange: { date_from?: string | null; date_to?: string | null }): {+ date_from: string+ date_to: string+} {+ const from = dateStringToDayJs(utcDateRange.date_from ?? null) ?? dayjs().subtract(1, 'hour')+ const to = dateStringToDayJs(utcDateRange.date_to ?? null) ?? dayjs()+ const windowMs = Math.max(to.diff(from), 0)+ return {+ date_from: from.subtract(windowMs, 'millisecond').toISOString(),+ date_to: from.toISOString(),+ }+}+const EMPTY_RESPONSE: _LogsPatternsResponseApi = {patterns: [],scanned_count: 0,@@ -82,6 +107,8 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([actions({viewMatchingLogs: (pattern: _LogPatternApi) => ({ pattern }),+ setCompareEnabled: (enabled: boolean) => ({ enabled }),+ setBaselineMode: (mode: PatternsBaselineMode) => ({ mode }),}),loaders(({ values }) => ({@@ -90,18 +117,27 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([{loadPatterns: async (debounceMs: number = 0, breakpoint) => {await breakpoint(debounceMs)- return await logsPatternsCreate(String(values.currentTeamId), {- query: {- dateRange: values.utcDateRange,- severityLevels: values.filters.severityLevels,- serviceNames: values.filters.serviceNames,- searchTerm: values.filters.searchTerm || undefined,- // Scope mining to the same filters the Logs/sparkline queries use —- // `queryFilterGroup` folds in any pinned filters from an embedded viewer- // (person/trace logs), so a scoped viewer can't mine project-wide patterns.- filterGroup: values.queryFilterGroup as unknown as _LogPropertyFilterApi[],- },+ const response = await logsPatternsCreate(String(values.currentTeamId), {+ query: values.patternsQueryBody,})+ // A superseded call must not land its (stale) response after the newer one.+ breakpoint()+ return response+ },+ },+ ],+ diffResponse: [+ null as _LogsPatternsDiffResponseApi | null,+ {+ loadDiff: async (debounceMs: number = 0, breakpoint) => {+ await breakpoint(debounceMs)+ const response = await logsPatternsDiffCreate(String(values.currentTeamId), {+ query: values.patternsQueryBody,+ baselineDateRange:+ values.baselineMode === 'preceding' ? precedingDateRange(values.utcDateRange) : undefined,+ })+ breakpoint()+ return response},},],@@ -116,11 +152,42 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([loadPatterns: () => null,loadPatternsSuccess: () => null,loadPatternsFailure: (_, { error }) => error ?? 'Pattern analysis failed',+ loadDiff: () => null,+ loadDiffSuccess: () => null,+ loadDiffFailure: (_, { error }) => error ?? 'Pattern comparison failed',+ },+ ],+ compareEnabled: [+ false,+ {+ setCompareEnabled: (_, { enabled }) => enabled,+ },+ ],+ baselineMode: [+ 'lastWeek' as PatternsBaselineMode,+ {+ setBaselineMode: (_, { mode }) => mode,},],}),selectors({+ // The shared query body for both the mine and the diff — the diff must scope its two+ // windows with exactly the filters a plain mine would use, or compare mode would+ // silently answer a different question than the table next to it.+ patternsQueryBody: [+ (s) => [s.filters, s.utcDateRange, s.queryFilterGroup],+ (filters, utcDateRange, queryFilterGroup) => ({+ dateRange: utcDateRange,+ severityLevels: filters.severityLevels,+ serviceNames: filters.serviceNames,+ searchTerm: filters.searchTerm || undefined,+ // Scope mining to the same filters the Logs/sparkline queries use —+ // `queryFilterGroup` folds in any pinned filters from an embedded viewer+ // (person/trace logs), so a scoped viewer can't mine project-wide patterns.+ filterGroup: queryFilterGroup as unknown as _LogPropertyFilterApi[],+ }),+ ],patterns: [(s) => [s.patternsResponse],(response: _LogsPatternsResponseApi): _LogPatternApi[] => response.patterns,@@ -151,7 +218,11 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([if (values.viewMode !== 'patterns') {return}- actions.loadPatterns(300)+ if (values.compareEnabled) {+ actions.loadDiff(300)+ } else {+ actions.loadPatterns(300)+ }}return {setDateRange: reload,@@ -163,6 +234,21 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([setFilterGroup: reload,setPinnedFilters: reload,+ // Entering compare mode always diffs fresh; leaving it re-mines because the+ // filters may have changed while the plain response sat unused.+ setCompareEnabled: ({ enabled }) => {+ if (enabled) {+ actions.loadDiff()+ } else {+ actions.loadPatterns()+ }+ },+ setBaselineMode: () => {+ if (values.compareEnabled) {+ actions.loadDiff()+ }+ },+// Pivot to the Logs view scoped to this pattern. The predicate lands in the shared// filterGroup like any user-added filter — visible and removable in the filter bar,// never hidden state. Prefer the validated regex; fall back to plain-text matchingdiff --git a/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx b/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsxindex 630e4bac7a6d..aabb6d119dae 100644--- a/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx+++ b/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx@@ -135,7 +135,14 @@ export const LogsDisplayBar = ({* mounted while Patterns is active — mounting it in Logs mode would kick off the heavier patterns query.*/const PatternsCountIndicator = ({ id }: { id: string }): JSX.Element | null => {- const { patterns } = useValues(logsPatternsLogic({ id }))+ const { patterns, compareEnabled, diffResponse } = useValues(logsPatternsLogic({ id }))++ // In compare mode the table renders diff entries, not the plain mine — counting `patterns`+ // there would show a number from a different dataset than the rows on screen.+ if (compareEnabled) {+ const count = diffResponse?.entries.length ?? 0+ return count > 0 ? <span className="text-muted text-xs">{humanFriendlyNumber(count)} changes</span> : null+ }if (patterns.length === 0) {return nulldiff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 5cff1561f0bc..d87ddd8afe4f 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1241,6 +1241,79 @@ export interface _LogsPatternsResponseApi {sparkline_buckets: _LogsPatternsSparklineBucketApi[]}+export interface _LogsPatternsDiffRequestApi {+ /** The patterns query for the current (foreground) window: date range plus any severity/service/search/property filters. The same filters are applied to the baseline window. */+ query: _LogsPatternsBodyApi+ /** Baseline window to compare against. Omit to default to the current window shifted back exactly one week, which absorbs daily and weekly log-volume cycles. Pass an explicit range to compare against a specific period, e.g. pre-deploy or pre-incident. */+ baselineDateRange?: _DateRangeApi+}++/**+ * * `new` - new+ * * `rate_shift` - rate_shift+ * * `gone` - gone+ * * `unchanged` - unchanged+ */+export type ClassificationEnumApi = (typeof ClassificationEnumApi)[keyof typeof ClassificationEnumApi]++export const ClassificationEnumApi = {+ New: 'new',+ RateShift: 'rate_shift',+ Gone: 'gone',+ Unchanged: 'unchanged',+} as const++export interface _LogPatternDiffEntryApi {+ /** "new": appears only in the current window and clears the novelty floor (at least ~1% volume share, or any error/fatal occurrences). "rate_shift": present in both windows with the per-second rate changed by at least 2x either way, backed by enough samples on both sides to trust the estimates. "gone": cleared the floor in the baseline but absent from the current window. "unchanged" means "no confident claim", not "provably identical" — sampled mining cannot prove a below-floor template is genuinely new or gone.+ *+ * * `new` - new+ * * `rate_shift` - rate_shift+ * * `gone` - gone+ * * `unchanged` - unchanged */+ classification: ClassificationEnumApi+ /**+ * Current-window rate divided by baseline rate, both normalized per second so windows of different lengths compare fairly. 4.0 means 4x faster now; 0.25 means quartered. Null when the pattern is missing from either window.+ * @nullable+ */+ rate_ratio: number | null+ /** The mined pattern with full stats. Taken from the current window, or from the baseline window for "gone" entries. When template wobble split one message across several near-identical templates, this is the highest-volume representative and the entry's classification reflects their combined counts. */+ pattern: _LogPatternApi+ /**+ * Estimated occurrences across the baseline window (extrapolated like `estimated_count`). Null when the pattern was not seen in the baseline sample.+ * @nullable+ */+ baseline_estimated_count: number | null+ /**+ * Share of the baseline sample this pattern represented (0-100). Null when absent from the baseline.+ * @nullable+ */+ baseline_volume_share_pct: number | null+}++export interface _LogsPatternsDiffWindowApi {+ /** Log rows fed to the miner for this window (sample size). */+ scanned_count: number+ /** Total log rows matching the filters in this window. */+ total_count: number+ /** True when this window's counts are extrapolated from a sample rather than exact. */+ sampled: boolean+ /** Share of this window's rows eligible for sampling (0-100); below 100 the scan was time-slice bounded. */+ sample_coverage_pct: number+ /** Resolved window start (ISO 8601, inclusive). */+ date_from: string+ /** Resolved window end (ISO 8601, exclusive). */+ date_to: string+}++export interface _LogsPatternsDiffResponseApi {+ /** Classified diff entries, most interesting first: "new" (by estimated count), then "rate_shift" (by shift magnitude), then "gone", then "unchanged". A pattern in the baseline is matched to the current window by literal-content fingerprint, so a placeholder widening between runs does not read as one pattern vanishing and another appearing. */+ entries: _LogPatternDiffEntryApi[]+ /** Mining metadata for the current window. */+ current: _LogsPatternsDiffWindowApi+ /** Mining metadata for the baseline window. Check `total_count` before trusting a wall of "new" entries: an empty or tiny baseline (e.g. logging only started this week) makes everything look new. */+ baseline: _LogsPatternsDiffWindowApi+}+/*** * `latest` - latest* * `earliest` - earliestdiff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.tsindex 1e56084aa7d2..cbb6e024a245 100644--- a/products/logs/frontend/generated/api.ts+++ b/products/logs/frontend/generated/api.ts@@ -45,6 +45,8 @@ import type {_LogsFacetValuesResponseApi,_LogsGroupByRequestApi,_LogsGroupByResponseApi,+ _LogsPatternsDiffRequestApi,+ _LogsPatternsDiffResponseApi,_LogsPatternsRequestApi,_LogsPatternsResponseApi,_LogsQueryRequestApi,@@ -449,6 +451,23 @@ export const logsPatternsCreate = async (})}+export const getLogsPatternsDiffCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/logs/patterns_diff/`+}++export const logsPatternsDiffCreate = async (+ projectId: string,+ _logsPatternsDiffRequestApi: _LogsPatternsDiffRequestApi,+ options?: RequestInit+): Promise<_LogsPatternsDiffResponseApi> => {+ return apiMutator<_LogsPatternsDiffResponseApi>(getLogsPatternsDiffCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(_logsPatternsDiffRequestApi),+ })+}+export const getLogsQueryCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/logs/query/`}diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex 606de2e79a78..fce14d85ece0 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -903,6 +903,107 @@ export const LogsPatternsCreateBody = /* @__PURE__ */ zod.object({.describe('The patterns query to execute.'),})+export const LogsPatternsDiffCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .nullish()+ .describe(+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc.'+ ),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range. Same format as date_from. Omit or null for \"now\".'),+ })+ .optional()+ .describe('Date range to mine patterns from. Defaults to last hour.'),+ severityLevels: zod+ .array(+ zod+ .enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])+ .describe(+ '\* `trace` - trace\n\* `debug` - debug\n\* `info` - info\n\* `warn` - warn\n\* `error` - error\n\* `fatal` - fatal'+ )+ )+ .optional()+ .describe('Filter by log severity levels before mining.'),+ serviceNames: zod.array(zod.string()).optional().describe('Restrict mining to these service names.'),+ searchTerm: zod.string().optional().describe('Full-text search term to filter log bodies before mining.'),+ filterGroup: zod+ .array(+ 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\").'+ ),+ type: zod+ .enum(['log', 'log_attribute', 'log_resource_attribute'])+ .describe(+ '\* `log` - log\n\* `log_attribute` - log_attribute\n\* `log_resource_attribute` - log_resource_attribute'+ )+ .describe(+ '\"log\" filters the log body\/message. \"log_attribute\" filters log-level attributes. \"log_resource_attribute\" filters resource-level attributes.\n\n\* `log` - log\n\* `log_attribute` - log_attribute\n\* `log_resource_attribute` - log_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'lt',+ 'is_date_exact',+ 'is_date_before',+ 'is_date_after',+ 'is_set',+ 'is_not_set',+ ])+ .describe(+ '\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_date_exact` - is_date_exact\n\* `is_date_before` - is_date_before\n\* `is_date_after` - is_date_after\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'+ )+ .describe(+ 'Comparison operator.\n\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_date_exact` - is_date_exact\n\* `is_date_before` - is_date_before\n\* `is_date_after` - is_date_after\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ 'Value to compare against. String, number, or array of strings. Omit for is_set\/is_not_set operators.'+ ),+ })+ )+ .optional()+ .describe('Property filters applied before mining. Same shape as the query-logs endpoint.'),+ })+ .describe(+ 'The patterns query for the current (foreground) window: date range plus any severity\/service\/search\/property filters. The same filters are applied to the baseline window.'+ ),+ baselineDateRange: zod+ .object({+ date_from: zod+ .string()+ .nullish()+ .describe(+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc.'+ ),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range. Same format as date_from. Omit or null for \"now\".'),+ })+ .optional()+ .describe(+ 'Baseline window to compare against. Omit to default to the current window shifted back exactly one week, which absorbs daily and weekly log-volume cycles. Pass an explicit range to compare against a specific period, e.g. pre-deploy or pre-incident.'+ ),+})+export const logsQueryCreateBodyQueryOneSeverityLevelsDefault = []export const logsQueryCreateBodyQueryOneServiceNamesDefault = []export const logsQueryCreateBodyQueryOneFilterGroupDefault = []diff --git a/products/logs/mcp/prompts/logs-patterns-diff.md b/products/logs/mcp/prompts/logs-patterns-diff.mdnew file mode 100644index 000000000000..5bf7a782025f--- /dev/null+++ b/products/logs/mcp/prompts/logs-patterns-diff.md@@ -0,0 +1,76 @@+Compare the log patterns of two time windows and return what changed: templates that are **new**, templates whose rate **shifted** (with magnitude, e.g. 4x), and templates that are **gone**. This is the single most useful call for incident triage — "what is different about now vs. before it broke" in one round trip, instead of mining two windows yourself and hand-matching templates.++All parameters must be nested inside a `query` object, with an optional sibling `baselineDateRange`.++# When to use++- **Incident triage (the primary loop):** set `query.dateRange` to the incident window. Omit `baselineDateRange` (defaults to the same window one week earlier) or set it to a known-good window just before the incident. The `new` and biggest `rate_shift` entries are your suspects; pivot to their raw lines with `query-logs`.+- **Post-deploy check:** current window = since the deploy; `baselineDateRange` = the same-length window just before it. New error-severity templates right after a deploy are the classic regression signature.+- **"What changed this week?"** — current = `-1d`, baseline auto. Good periodic sweep for a service you own.++## Pick the right tool++- Just summarize one window's content → `logs-patterns`.+- Explain a _count_ change without needing message content → `logs-count-ranges` (cheaper).+- Use **this** tool when you need to know _which messages_ are new or behaving differently between two periods.++# Reading the response++Entries come sorted most-interesting-first: `new` (by volume), then `rate_shift` (by magnitude), then `gone`, then `unchanged`.++- `classification` — trust the labels; the thresholds already handle sampling honesty:+ - `new` requires clearing a novelty floor (~1% volume share, or any error/fatal lines). Below the floor, absence from the baseline sample is not evidence of novelty.+ - `rate_shift` requires ≥2x change in per-second rate (windows of different lengths are normalized) _and_ enough raw samples on both sides.+ - `unchanged` means "no confident claim", not "provably identical".+- `rate_ratio` — current rate / baseline rate. 4.0 = 4x faster now, 0.25 = quartered.+- `pattern` — full pattern stats including `match_regex` / `match_literal`, so you can pivot straight to the matching lines (same recipe as `logs-patterns`: message regex filter + the pattern's services/severities).+- **Check `baseline.total_count` before trusting a wall of `new` entries** — an empty or tiny baseline (logging only started recently, service didn't exist last week) makes everything look new.+- Both windows are mined from samples (`sampled: true`), so counts are estimates and templates rarer than ~1 in 10,000 rows may be invisible in either window.++Template identity across the two windows is fingerprint-based (literal content), so the miner rendering `User <*> not found` in one window and `User <num> not found` in the other still compares as one pattern rather than a false new+gone pair.++# Parameters++## query.dateRange++The current (foreground) window — the period you are investigating. Same format as `logs-patterns`.++## baselineDateRange++Optional, sibling of `query` (not inside it). The comparison window. Omit for the default: the current window shifted back exactly one week, which absorbs daily/weekly volume cycles. Provide explicitly to compare against a pre-deploy or pre-incident period. It does not need to be the same length as the current window — rates are normalized per second.++## query.severityLevels / query.serviceNames / query.searchTerm / query.filterGroup++Same as `logs-patterns`; applied to **both** windows. Scoping by service is recommended — it prunes both scans and focuses the sample budget.++# Examples++## What changed during the incident vs. just before it++```json+{+ "query": {+ "dateRange": { "date_from": "2026-07-07T09:30:00Z", "date_to": "2026-07-07T10:30:00Z" },+ "serviceNames": ["checkout"]+ },+ "baselineDateRange": { "date_from": "2026-07-07T08:00:00Z", "date_to": "2026-07-07T09:00:00Z" }+}+```++## What is new or different today vs. the same time last week++```json+{ "query": { "dateRange": { "date_from": "-1d" } } }+```++## Did the deploy change what the service logs?++```json+{+ "query": {+ "dateRange": { "date_from": "2026-07-07T14:00:00Z" },+ "serviceNames": ["api"]+ },+ "baselineDateRange": { "date_from": "2026-07-07T10:00:00Z", "date_to": "2026-07-07T14:00:00Z" }+}+```diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yamlindex 8e116fcc9f6c..e2e716cd7d23 100644--- a/products/logs/mcp/tools.yaml+++ b/products/logs/mcp/tools.yaml@@ -380,6 +380,24 @@ tools:- patterns.*.count- patterns.*.error_count- sparkline_buckets+ logs-patterns-diff:+ operation: logs_patterns_diff_create+ enabled: true+ scopes:+ - logs:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Diff log patterns between two windows+ description_file: ./prompts/logs-patterns-diff.md+ feature_flag: logs-patterns-view+ response:+ exclude:+ - entries.*.pattern.examples+ - entries.*.pattern.sparkline+ - entries.*.pattern.count+ - entries.*.pattern.error_countlogs-sampling-rules-create:operation: logs_sampling_rules_createenabled: falsediff --git a/pyproject.toml b/pyproject.tomlindex 33c45beec407..6b4b6fc28c6b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -552,6 +552,7 @@ ignore_imports = ["products.logs.backend.presentation.views.api -> products.logs.backend.log_facet_values_query_runner","products.logs.backend.presentation.views.api -> products.logs.backend.log_values_query_runner","products.logs.backend.presentation.views.api -> products.logs.backend.logs_query_runner",+ "products.logs.backend.presentation.views.api -> products.logs.backend.pattern_diff","products.logs.backend.presentation.views.api -> products.logs.backend.patterns_query_runner","products.logs.backend.presentation.views.api -> products.logs.backend.services_query_runner","products.logs.backend.presentation.views.api -> products.logs.backend.sparkline_query_runner",diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex ec52dbb14278..52a9f13001de 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5497,6 +5497,21 @@},"feature_flag": "logs-patterns-view"},+ "logs-patterns-diff": {+ "description": "Compare the log patterns of two time windows and return what changed: templates that are **new**, templates whose rate **shifted** (with magnitude, e.g. 4x), and templates that are **gone**. This is the single most useful call for incident triage — \"what is different about now vs. before it broke\" in one round trip, instead of mining two windows yourself and hand-matching templates.\n\nAll parameters must be nested inside a `query` object, with an optional sibling `baselineDateRange`.\n\n# When to use\n\n- **Incident triage (the primary loop):** set `query.dateRange` to the incident window. Omit `baselineDateRange` (defaults to the same window one week earlier) or set it to a known-good window just before the incident. The `new` and biggest `rate_shift` entries are your suspects; pivot to their raw lines with `query-logs`.\n- **Post-deploy check:** current window = since the deploy; `baselineDateRange` = the same-length window just before it. New error-severity templates right after a deploy are the classic regression signature.\n- **\"What changed this week?\"** — current = `-1d`, baseline auto. Good periodic sweep for a service you own.\n\n## Pick the right tool\n\n- Just summarize one window's content → `logs-patterns`.\n- Explain a _count_ change without needing message content → `logs-count-ranges` (cheaper).\n- Use **this** tool when you need to know _which messages_ are new or behaving differently between two periods.\n\n# Reading the response\n\nEntries come sorted most-interesting-first: `new` (by volume), then `rate_shift` (by magnitude), then `gone`, then `unchanged`.\n\n- `classification` — trust the labels; the thresholds already handle sampling honesty:\n - `new` requires clearing a novelty floor (~1% volume share, or any error/fatal lines). Below the floor, absence from the baseline sample is not evidence of novelty.\n - `rate_shift` requires ≥2x change in per-second rate (windows of different lengths are normalized) _and_ enough raw samples on both sides.\n - `unchanged` means \"no confident claim\", not \"provably identical\".\n- `rate_ratio` — current rate / baseline rate. 4.0 = 4x faster now, 0.25 = quartered.\n- `pattern` — full pattern stats including `match_regex` / `match_literal`, so you can pivot straight to the matching lines (same recipe as `logs-patterns`: message regex filter + the pattern's services/severities).\n- **Check `baseline.total_count` before trusting a wall of `new` entries** — an empty or tiny baseline (logging only started recently, service didn't exist last week) makes everything look new.\n- Both windows are mined from samples (`sampled: true`), so counts are estimates and templates rarer than ~1 in 10,000 rows may be invisible in either window.\n\nTemplate identity across the two windows is fingerprint-based (literal content), so the miner rendering `User <*> not found` in one window and `User <num> not found` in the other still compares as one pattern rather than a false new+gone pair.\n\n# Parameters\n\n## query.dateRange\n\nThe current (foreground) window — the period you are investigating. Same format as `logs-patterns`.\n\n## baselineDateRange\n\nOptional, sibling of `query` (not inside it). The comparison window. Omit for the default: the current window shifted back exactly one week, which absorbs daily/weekly volume cycles. Provide explicitly to compare against a pre-deploy or pre-incident period. It does not need to be the same length as the current window — rates are normalized per second.\n\n## query.severityLevels / query.serviceNames / query.searchTerm / query.filterGroup\n\nSame as `logs-patterns`; applied to **both** windows. Scoping by service is recommended — it prunes both scans and focuses the sample budget.\n\n# Examples\n\n## What changed during the incident vs. just before it\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T09:30:00Z\", \"date_to\": \"2026-07-07T10:30:00Z\" },\n \"serviceNames\": [\"checkout\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T08:00:00Z\", \"date_to\": \"2026-07-07T09:00:00Z\" }\n}\n```\n\n## What is new or different today vs. the same time last week\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1d\" } } }\n```\n\n## Did the deploy change what the service logs?\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T14:00:00Z\" },\n \"serviceNames\": [\"api\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T10:00:00Z\", \"date_to\": \"2026-07-07T14:00:00Z\" }\n}\n```",+ "category": "Logs",+ "feature": "logs",+ "summary": "Diff log patterns between two windows",+ "title": "Diff log patterns between two windows",+ "required_scopes": ["logs:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "logs-patterns-view"+ },"logs-services-create": {"description": "Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate, plus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on — high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walking attribute-values + per-service counts.","category": "Logs",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 1bbe6f2f1234..e30a4791a455 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5933,6 +5933,21 @@},"feature_flag": "logs-patterns-view"},+ "logs-patterns-diff": {+ "description": "Compare the log patterns of two time windows and return what changed: templates that are **new**, templates whose rate **shifted** (with magnitude, e.g. 4x), and templates that are **gone**. This is the single most useful call for incident triage — \"what is different about now vs. before it broke\" in one round trip, instead of mining two windows yourself and hand-matching templates.\n\nAll parameters must be nested inside a `query` object, with an optional sibling `baselineDateRange`.\n\n# When to use\n\n- **Incident triage (the primary loop):** set `query.dateRange` to the incident window. Omit `baselineDateRange` (defaults to the same window one week earlier) or set it to a known-good window just before the incident. The `new` and biggest `rate_shift` entries are your suspects; pivot to their raw lines with `query-logs`.\n- **Post-deploy check:** current window = since the deploy; `baselineDateRange` = the same-length window just before it. New error-severity templates right after a deploy are the classic regression signature.\n- **\"What changed this week?\"** — current = `-1d`, baseline auto. Good periodic sweep for a service you own.\n\n## Pick the right tool\n\n- Just summarize one window's content → `logs-patterns`.\n- Explain a _count_ change without needing message content → `logs-count-ranges` (cheaper).\n- Use **this** tool when you need to know _which messages_ are new or behaving differently between two periods.\n\n# Reading the response\n\nEntries come sorted most-interesting-first: `new` (by volume), then `rate_shift` (by magnitude), then `gone`, then `unchanged`.\n\n- `classification` — trust the labels; the thresholds already handle sampling honesty:\n - `new` requires clearing a novelty floor (~1% volume share, or any error/fatal lines). Below the floor, absence from the baseline sample is not evidence of novelty.\n - `rate_shift` requires ≥2x change in per-second rate (windows of different lengths are normalized) _and_ enough raw samples on both sides.\n - `unchanged` means \"no confident claim\", not \"provably identical\".\n- `rate_ratio` — current rate / baseline rate. 4.0 = 4x faster now, 0.25 = quartered.\n- `pattern` — full pattern stats including `match_regex` / `match_literal`, so you can pivot straight to the matching lines (same recipe as `logs-patterns`: message regex filter + the pattern's services/severities).\n- **Check `baseline.total_count` before trusting a wall of `new` entries** — an empty or tiny baseline (logging only started recently, service didn't exist last week) makes everything look new.\n- Both windows are mined from samples (`sampled: true`), so counts are estimates and templates rarer than ~1 in 10,000 rows may be invisible in either window.\n\nTemplate identity across the two windows is fingerprint-based (literal content), so the miner rendering `User <*> not found` in one window and `User <num> not found` in the other still compares as one pattern rather than a false new+gone pair.\n\n# Parameters\n\n## query.dateRange\n\nThe current (foreground) window — the period you are investigating. Same format as `logs-patterns`.\n\n## baselineDateRange\n\nOptional, sibling of `query` (not inside it). The comparison window. Omit for the default: the current window shifted back exactly one week, which absorbs daily/weekly volume cycles. Provide explicitly to compare against a pre-deploy or pre-incident period. It does not need to be the same length as the current window — rates are normalized per second.\n\n## query.severityLevels / query.serviceNames / query.searchTerm / query.filterGroup\n\nSame as `logs-patterns`; applied to **both** windows. Scoping by service is recommended — it prunes both scans and focuses the sample budget.\n\n# Examples\n\n## What changed during the incident vs. just before it\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T09:30:00Z\", \"date_to\": \"2026-07-07T10:30:00Z\" },\n \"serviceNames\": [\"checkout\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T08:00:00Z\", \"date_to\": \"2026-07-07T09:00:00Z\" }\n}\n```\n\n## What is new or different today vs. the same time last week\n\n```json\n{ \"query\": { \"dateRange\": { \"date_from\": \"-1d\" } } }\n```\n\n## Did the deploy change what the service logs?\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"2026-07-07T14:00:00Z\" },\n \"serviceNames\": [\"api\"]\n },\n \"baselineDateRange\": { \"date_from\": \"2026-07-07T10:00:00Z\", \"date_to\": \"2026-07-07T14:00:00Z\" }\n}\n```",+ "category": "Logs",+ "feature": "logs",+ "summary": "Diff log patterns between two windows",+ "title": "Diff log patterns between two windows",+ "required_scopes": ["logs:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "logs-patterns-view"+ },"logs-services-create": {"description": "Return the top-25 services by log volume in the window, each with log_count, error_count, and error_rate, plus a per-service sparkline. Use this as the entry point when triaging which services are worth alerting on — high volume × non-zero error_rate is the natural alert candidate. Far cheaper than walking attribute-values + per-service counts.","category": "Logs",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6943945f1f33..556c11af750b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12966,6 +12966,22 @@ export namespace Schemas {available: boolean;}+ /**+ * * `new` - new+ * * `rate_shift` - rate_shift+ * * `gone` - gone+ * * `unchanged` - unchanged+ */+ export type ClassificationEnum = typeof ClassificationEnum[keyof typeof ClassificationEnum];+++ export const ClassificationEnum = {+ New: 'new',+ RateShift: 'rate_shift',+ Gone: 'gone',+ Unchanged: 'unchanged',+ } as const;+/*** * `abandoned` - Abandoned* * `off-topic` - Off-topic@@ -58182,6 +58198,33 @@ export namespace Schemas {match_literal: string | null;}+ export interface _LogPatternDiffEntry {+ /** "new": appears only in the current window and clears the novelty floor (at least ~1% volume share, or any error/fatal occurrences). "rate_shift": present in both windows with the per-second rate changed by at least 2x either way, backed by enough samples on both sides to trust the estimates. "gone": cleared the floor in the baseline but absent from the current window. "unchanged" means "no confident claim", not "provably identical" — sampled mining cannot prove a below-floor template is genuinely new or gone.+ *+ * * `new` - new+ * * `rate_shift` - rate_shift+ * * `gone` - gone+ * * `unchanged` - unchanged */+ classification: ClassificationEnum;+ /**+ * Current-window rate divided by baseline rate, both normalized per second so windows of different lengths compare fairly. 4.0 means 4x faster now; 0.25 means quartered. Null when the pattern is missing from either window.+ * @nullable+ */+ rate_ratio: number | null;+ /** The mined pattern with full stats. Taken from the current window, or from the baseline window for "gone" entries. When template wobble split one message across several near-identical templates, this is the highest-volume representative and the entry's classification reflects their combined counts. */+ pattern: _LogPattern;+ /**+ * Estimated occurrences across the baseline window (extrapolated like `estimated_count`). Null when the pattern was not seen in the baseline sample.+ * @nullable+ */+ baseline_estimated_count: number | null;+ /**+ * Share of the baseline sample this pattern represented (0-100). Null when absent from the baseline.+ * @nullable+ */+ baseline_volume_share_pct: number | null;+ }+/*** * `log` - log* * `log_attribute` - log_attribute@@ -58437,6 +58480,37 @@ export namespace Schemas {filterGroup?: _LogPropertyFilter[];}+ export interface _LogsPatternsDiffRequest {+ /** The patterns query for the current (foreground) window: date range plus any severity/service/search/property filters. The same filters are applied to the baseline window. */+ query: _LogsPatternsBody;+ /** Baseline window to compare against. Omit to default to the current window shifted back exactly one week, which absorbs daily and weekly log-volume cycles. Pass an explicit range to compare against a specific period, e.g. pre-deploy or pre-incident. */+ baselineDateRange?: _DateRange;+ }++ export interface _LogsPatternsDiffWindow {+ /** Log rows fed to the miner for this window (sample size). */+ scanned_count: number;+ /** Total log rows matching the filters in this window. */+ total_count: number;+ /** True when this window's counts are extrapolated from a sample rather than exact. */+ sampled: boolean;+ /** Share of this window's rows eligible for sampling (0-100); below 100 the scan was time-slice bounded. */+ sample_coverage_pct: number;+ /** Resolved window start (ISO 8601, inclusive). */+ date_from: string;+ /** Resolved window end (ISO 8601, exclusive). */+ date_to: string;+ }++ export interface _LogsPatternsDiffResponse {+ /** Classified diff entries, most interesting first: "new" (by estimated count), then "rate_shift" (by shift magnitude), then "gone", then "unchanged". A pattern in the baseline is matched to the current window by literal-content fingerprint, so a placeholder widening between runs does not read as one pattern vanishing and another appearing. */+ entries: _LogPatternDiffEntry[];+ /** Mining metadata for the current window. */+ current: _LogsPatternsDiffWindow;+ /** Mining metadata for the baseline window. Check `total_count` before trusting a wall of "new" entries: an empty or tiny baseline (e.g. logging only started this week) makes everything look new. */+ baseline: _LogsPatternsDiffWindow;+ }+export interface _LogsPatternsRequest {/** The patterns query to execute. */query: _LogsPatternsBody;diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.tsindex 5d6f8e8f2ee2..3c8347ce3e54 100644--- a/services/mcp/src/generated/logs/api.ts+++ b/services/mcp/src/generated/logs/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 18 enabled ops+ * PostHog API - MCP 19 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -4250,6 +4250,115 @@ export const LogsPatternsCreateBody = /* @__PURE__ */ zod.object({.describe('The patterns query to execute.'),})+export const LogsPatternsDiffCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const LogsPatternsDiffCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ dateRange: zod+ .object({+ date_from: zod+ .string()+ .nullish()+ .describe(+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc.'+ ),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range. Same format as date_from. Omit or null for "now".'),+ })+ .optional()+ .describe('Date range to mine patterns from. Defaults to last hour.'),+ severityLevels: zod+ .array(+ zod+ .enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])+ .describe(+ '* `trace` - trace\n* `debug` - debug\n* `info` - info\n* `warn` - warn\n* `error` - error\n* `fatal` - fatal'+ )+ )+ .optional()+ .describe('Filter by log severity levels before mining.'),+ serviceNames: zod.array(zod.string()).optional().describe('Restrict mining to these service names.'),+ searchTerm: zod.string().optional().describe('Full-text search term to filter log bodies before mining.'),+ filterGroup: zod+ .array(+ 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").'+ ),+ type: zod+ .enum(['log', 'log_attribute', 'log_resource_attribute'])+ .describe(+ '* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute'+ )+ .describe(+ '"log" filters the log body/message. "log_attribute" filters log-level attributes. "log_resource_attribute" filters resource-level attributes.\n\n* `log` - log\n* `log_attribute` - log_attribute\n* `log_resource_attribute` - log_resource_attribute'+ ),+ operator: zod+ .enum([+ 'exact',+ 'is_not',+ 'icontains',+ 'not_icontains',+ 'regex',+ 'not_regex',+ 'gt',+ 'lt',+ 'is_date_exact',+ 'is_date_before',+ 'is_date_after',+ 'is_set',+ 'is_not_set',+ ])+ .describe(+ '* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_date_exact` - is_date_exact\n* `is_date_before` - is_date_before\n* `is_date_after` - is_date_after\n* `is_set` - is_set\n* `is_not_set` - is_not_set'+ )+ .describe(+ 'Comparison operator.\n\n* `exact` - exact\n* `is_not` - is_not\n* `icontains` - icontains\n* `not_icontains` - not_icontains\n* `regex` - regex\n* `not_regex` - not_regex\n* `gt` - gt\n* `lt` - lt\n* `is_date_exact` - is_date_exact\n* `is_date_before` - is_date_before\n* `is_date_after` - is_date_after\n* `is_set` - is_set\n* `is_not_set` - is_not_set'+ ),+ value: zod+ .unknown()+ .optional()+ .describe(+ 'Value to compare against. String, number, or array of strings. Omit for is_set/is_not_set operators.'+ ),+ })+ )+ .optional()+ .describe('Property filters applied before mining. Same shape as the query-logs endpoint.'),+ })+ .describe(+ 'The patterns query for the current (foreground) window: date range plus any severity/service/search/property filters. The same filters are applied to the baseline window.'+ ),+ baselineDateRange: zod+ .object({+ date_from: zod+ .string()+ .nullish()+ .describe(+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc.'+ ),+ date_to: zod+ .string()+ .nullish()+ .describe('End of the date range. Same format as date_from. Omit or null for "now".'),+ })+ .optional()+ .describe(+ 'Baseline window to compare against. Omit to default to the current window shifted back exactly one week, which absorbs daily and weekly log-volume cycles. Pass an explicit range to compare against a specific period, e.g. pre-deploy or pre-incident.'+ ),+})+export const LogsQueryCreateParams = /* @__PURE__ */ zod.object({project_id: zod.string()diff --git a/services/mcp/src/tools/generated/logs.ts b/services/mcp/src/tools/generated/logs.tsindex 4b4d0b56ea61..2ddf77e44915 100644--- a/services/mcp/src/tools/generated/logs.ts+++ b/services/mcp/src/tools/generated/logs.ts@@ -21,6 +21,7 @@ import {LogsCountRangesCreateBody,LogsFacetValuesCreateBody,LogsPatternsCreateBody,+ LogsPatternsDiffCreateBody,LogsQueryCreateBody,LogsServicesCreateBody,LogsSparklineCreateBody,@@ -554,6 +555,35 @@ const logsPatterns = (): ToolBase<typeof LogsPatternsSchema, Schemas._LogsPatter},})+const LogsPatternsDiffSchema = LogsPatternsDiffCreateBody++const logsPatternsDiff = (): ToolBase<typeof LogsPatternsDiffSchema, Schemas._LogsPatternsDiffResponse> => ({+ name: 'logs-patterns-diff',+ schema: LogsPatternsDiffSchema,+ handler: async (context: Context, params: z.infer<typeof LogsPatternsDiffSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.query !== undefined) {+ body['query'] = params.query+ }+ if (params.baselineDateRange !== undefined) {+ body['baselineDateRange'] = params.baselineDateRange+ }+ const result = await context.api.request<Schemas._LogsPatternsDiffResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/patterns_diff/`,+ body,+ })+ const filtered = omitResponseFields(result, [+ 'entries.*.pattern.examples',+ 'entries.*.pattern.sparkline',+ 'entries.*.pattern.count',+ 'entries.*.pattern.error_count',+ ]) as typeof result+ return filtered+ },+})+const LogsServicesCreateSchema = LogsServicesCreateBodyconst logsServicesCreate = (): ToolBase<typeof LogsServicesCreateSchema, Schemas._LogsServicesResponse> => ({@@ -633,6 +663,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'logs-count-ranges': logsCountRanges,'logs-facet-values-create': logsFacetValuesCreate,'logs-patterns': logsPatterns,+ 'logs-patterns-diff': logsPatternsDiff,'logs-services-create': logsServicesCreate,'logs-sparkline-query': logsSparklineQuery,'query-logs': queryLogs,