Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(logs): rank, describe and signal grouped logs alerts per group (#118168)

Jimmy Zhu836ff06913cf
diff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.py
index 61ad1ede8a09..29574c86602c 100644
--- a/products/logs/backend/alert_check_query.py
+++ b/products/logs/backend/alert_check_query.py
@@ -28,6 +28,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models import Team
+from products.logs.backend.alert_group_columns import GROUP_COLUMNS
from products.logs.backend.alert_utils import MAX_BYTES_TO_READ
from products.logs.backend.logs_query_runner import LIVE_LOGS_CHECKPOINT_QUERY, LogsFilterBuilder
@@ -597,11 +598,6 @@ class BatchedAlertCheckQuery:
)
-# The columns a grouped logs alert may split on. Both are low-cardinality columns of the logs table,
-# and `service_name` leads its primary key, so grouping on them stays cheap.
-GROUPABLE_LOGS_COLUMNS: frozenset[str] = frozenset({"service_name", "severity_text"})
-
-
@dataclass(frozen=True)
class GroupCounts:
labels: dict[str, str]
@@ -610,9 +606,11 @@ class GroupCounts:
@dataclass(frozen=True)
class GroupedRollingResult:
+ # When `truncated`, the last group is the row past the query's limit: the worst group it cut.
groups: list[GroupCounts]
period_starts: list[dt.datetime]
query_duration_ms: int
+ truncated: bool
def zero_counts(self) -> list[BucketedCount]:
"""The counts of a group with no matching log in any period, which returns no row."""
@@ -625,8 +623,10 @@ class GroupedAlertCheckQuery:
One query per alert rather than a column in `BatchedAlertCheckQuery`, because a batched cohort
reads one row per alert and a grouped alert needs one row per group.
- Rows come back with the open groups first and then worst first, and `limit` cuts the rest. An
- open group has to come back whatever its count, or a check could not resolve it.
+ Rows come back with the open groups first, then the groups that breach `datapoints_to_alarm`
+ of the periods, then worst first, and `limit` cuts the rest. An open group has to come back
+ whatever its count, or a check could not resolve it. The query reads one row past `limit` and
+ keeps it, so a caller can tell a cut result from one that fits and judge the worst group cut.
"""
def __init__(
@@ -639,13 +639,15 @@ class GroupedAlertCheckQuery:
group_by: Sequence[str],
open_groups: Sequence[dict[str, str]],
worst_is_highest: bool,
+ threshold_count: int,
+ datapoints_to_alarm: int,
limit: int,
max_execution_time: int,
ch_user: ClickHouseUser,
) -> None:
if alert.team_id != team.id:
raise ValueError(f"Alert {alert.id} belongs to team {alert.team_id}, not {team.id}")
- unknown = set(group_by) - GROUPABLE_LOGS_COLUMNS
+ unknown = set(group_by) - GROUP_COLUMNS.keys()
if not group_by or unknown:
raise ValueError(f"A logs alert cannot group by {sorted(unknown) or 'nothing'}")
self.team = team
@@ -653,6 +655,8 @@ class GroupedAlertCheckQuery:
self.group_by = tuple(group_by)
self.open_groups = list(open_groups)
self.worst_is_highest = worst_is_highest
+ self.threshold_count = threshold_count
+ self.datapoints_to_alarm = datapoints_to_alarm
self.limit = limit
self._ch_user = ch_user
self._settings = _bounded_settings(max_execution_time)
@@ -678,16 +682,45 @@ class GroupedAlertCheckQuery:
for row in response.results
]
return GroupedRollingResult(
- groups=groups, period_starts=[start for start, _ in ranges], query_duration_ms=duration_ms
+ groups=groups,
+ period_starts=[start for start, _ in ranges],
+ query_duration_ms=duration_ms,
+ truncated=len(groups) > self.limit,
)
def _build_query(self, ranges: list[tuple[dt.datetime, dt.datetime]]) -> ast.SelectQuery:
columns: list[ast.Expr] = [ast.Field(chain=[column]) for column in self.group_by]
periods = _period_count_columns(ranges)
+ breach_op = ast.CompareOperationOp.Gt if self.worst_is_highest else ast.CompareOperationOp.Lt
+ breached_periods = ast.Call(
+ name="arraySum",
+ args=[
+ ast.Array(
+ exprs=[
+ ast.CompareOperation(
+ op=breach_op,
+ left=ast.Field(chain=[f"period_{i}"]),
+ right=ast.Constant(value=self.threshold_count),
+ )
+ for i in range(len(ranges))
+ ]
+ )
+ ],
+ )
order_by = [
+ # Ranked by the N-of-M verdict before the worst count, so a steady breach the limit
+ # would otherwise cut is not displaced by groups that spiked once and do not breach.
+ ast.OrderExpr(
+ expr=ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=breached_periods,
+ right=ast.Constant(value=self.datapoints_to_alarm),
+ ),
+ order="DESC",
+ ),
ast.OrderExpr(
expr=ast.Field(chain=[f"period_{len(ranges) - 1}"]), order="DESC" if self.worst_is_highest else "ASC"
- )
+ ),
]
if self.open_groups:
group = ast.Tuple(exprs=[ast.Field(chain=[column]) for column in self.group_by])
@@ -705,7 +738,7 @@ class GroupedAlertCheckQuery:
where=self.where_expr,
group_by=[ast.Field(chain=[column]) for column in self.group_by],
order_by=order_by,
- limit=ast.Constant(value=self.limit),
+ limit=ast.Constant(value=self.limit + 1),
)
diff --git a/products/logs/backend/alert_group_columns.py b/products/logs/backend/alert_group_columns.py
new file mode 100644
index 000000000000..7864263b0434
--- /dev/null
+++ b/products/logs/backend/alert_group_columns.py
@@ -0,0 +1,26 @@
+"""The columns a grouped logs alert may split on.
+
+Kept apart from the query layer, because the platform wording imports it from `ready()`.
+"""
+
+from typing import Final
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class GroupColumn:
+ # The name a reader knows the column by.
+ label: str
+ # The logs scene filter that narrows a link to one group.
+ filter_key: str
+ # The `log` property filter key a `filterGroup` selects this column under.
+ filter_group_key: str
+
+
+# Both are low-cardinality columns of the logs table, and `service_name` leads its primary key, so
+# grouping on them stays cheap.
+GROUP_COLUMNS: Final[dict[str, GroupColumn]] = {
+ "service_name": GroupColumn(label="Service", filter_key="serviceNames", filter_group_key="service_name"),
+ "severity_text": GroupColumn(label="Severity", filter_key="severityLevels", filter_group_key="severity_level"),
+}
diff --git a/products/logs/backend/alert_signal_emitter.py b/products/logs/backend/alert_signal_emitter.py
index fd2b518b7fce..21fb65570bb5 100644
--- a/products/logs/backend/alert_signal_emitter.py
+++ b/products/logs/backend/alert_signal_emitter.py
@@ -50,6 +50,8 @@ class NotifiedAlert:
filters: dict
# Set by a caller that retries, so a repeated emission starts no second signal.
idempotency_key: str | None = None
+ # The group of a grouped alert that fired, by grouping column. Empty for an ungrouped alert.
+ group_labels: dict[str, str] = dataclasses.field(default_factory=dict)
_WEIGHT_BY_ACTION: dict[AlertSignalAction, float] = dict(_ACTION_WEIGHT.values())
@@ -67,6 +69,15 @@ class PlatformAlertSignal:
result_count: int | None
consecutive_failures: int
evaluation_key: str
+ # Empty for an ungrouped alert. Defaulted so a payload written before these fields still decodes.
+ grouping_key: str = ""
+ labels: dict[str, str] = dataclasses.field(default_factory=dict)
+
+ @property
+ def idempotency_key(self) -> str:
+ """One key per announced group, so a grouped evaluation's firings are not deduplicated into one."""
+ key = f"{self.alert_id}:{self.action}:{self.evaluation_key}"
+ return f"{key}:{self.grouping_key}" if self.grouping_key else key
def signal_action_and_weight(notification: NotificationAction) -> tuple[AlertSignalAction, float] | None:
@@ -79,7 +90,9 @@ def _alert_url(team_id: int) -> str:
def build_signal_extra(na: NotifiedAlert) -> dict:
+ group = {"group_labels": na.group_labels} if na.group_labels else {}
return {
+ **group,
"alert_id": na.alert_id,
"alert_name": na.alert_name,
"action": na.action,
@@ -101,6 +114,9 @@ def build_signal_description(na: NotifiedAlert) -> str:
scope += f" Services: {', '.join(services)}."
if severities:
scope += f" Severities: {', '.join(severities)}."
+ if na.group_labels:
+ group = ", ".join(f"{column}={value}" for column, value in sorted(na.group_labels.items()))
+ scope += f" Group: {group}."
if na.action == "firing":
return (
@@ -164,7 +180,8 @@ def notified_alerts_for_platform(team_id: int, signals: list[PlatformAlertSignal
result_count=signal.result_count,
consecutive_failures=signal.consecutive_failures,
filters=alert.filters,
- idempotency_key=f"{signal.alert_id}:{signal.action}:{signal.evaluation_key}",
+ idempotency_key=signal.idempotency_key,
+ group_labels=signal.labels,
)
)
return notified
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 49fe4bdf62ce..d45feb2545c1 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -85,7 +85,6 @@ from products.alerts_platform.backend.facade.platform_metrics import (
)
from products.alerts_platform.backend.facade.scheduling import is_utc_datetime_blocked, parse_blocked_windows_tuples
from products.logs.backend.alert_check_query import (
- GROUPABLE_LOGS_COLUMNS,
BatchedAlertCheckQuery,
BucketedCount,
GroupedAlertCheckQuery,
@@ -97,6 +96,7 @@ from products.logs.backend.alert_check_query import (
from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind
from products.logs.backend.alert_error_classifier import classify as classify_alert_error
from products.logs.backend.alert_evaluation_key import WINDOW_MARKER
+from products.logs.backend.alert_group_columns import GROUP_COLUMNS
from products.logs.backend.models import LogsAlertConfiguration
from products.logs.backend.platform_alert_backfill import platform_upsert_of
@@ -742,8 +742,8 @@ def _labels_of(grouping_key: str) -> dict[str, str] | None:
def _broken_grouping(check: PlatformAlertCheckInput) -> str | None:
if check.grouping.mode == GroupingMode.SINGLE:
return None
- if set(check.grouping.keys) - GROUPABLE_LOGS_COLUMNS:
- return f"A logs alert can only group by {', '.join(sorted(GROUPABLE_LOGS_COLUMNS))}"
+ if set(check.grouping.keys) - GROUP_COLUMNS.keys():
+ return f"A logs alert can only group by {', '.join(sorted(GROUP_COLUMNS))}"
# A group with no matching log returns no row, so a service gone silent, the case a `below`
# alert exists for, is never seen unless it was already open.
if check.condition.get("threshold_operator") != LogsAlertConfiguration.ThresholdOperator.ABOVE:
@@ -772,7 +772,6 @@ def _evaluate_grouped(
condition.window_minutes, check.check_interval_minutes, check.evaluation_periods
)
open_keys = check.open_keys()
- limit = len(open_keys) + check.grouping.max_instances
try:
result = GroupedAlertCheckQuery(
team=team,
@@ -782,8 +781,12 @@ def _evaluate_grouped(
group_by=check.grouping.keys,
open_groups=[labels for key in open_keys if (labels := _labels_of(key)) is not None],
worst_is_highest=condition.threshold_operator == LogsAlertConfiguration.ThresholdOperator.ABOVE,
- # Room for every open group and a full cap of new ones, so admission sees the worst.
- limit=limit,
+ threshold_count=condition.threshold_count,
+ datapoints_to_alarm=check.datapoints_to_alarm,
+ # Room for every open group and a full cap of new ones, so admission sees the worst. The
+ # query's one row past that reaches admission too, and when it breaches, admission finds
+ # no room for it and reports the cut as overflow.
+ limit=len(open_keys) + check.grouping.max_instances,
max_execution_time=query_seconds,
ch_user=ClickHouseUser.ALERTS_PLATFORM_LOGS,
).execute_rolling_checks(
@@ -796,9 +799,6 @@ def _evaluate_grouped(
return _delivery(check, _failed(check, error, now=now, muted=muted), window_end=date_to, now=now, failed=True)
counts = {grouping_key_of(group.labels): group for group in result.groups}
- # A hashed key keeps no labels, so the query cannot put that open group first, and the limit can
- # cut it while it still breaches. Its absence means no matching log only when nothing was cut.
- truncated = len(result.groups) >= limit
def observe(key: str, buckets: list[BucketedCount], labels: dict[str, str]) -> GroupObservation:
current_breached, *prior_breached = _derive_breaches(
@@ -814,7 +814,9 @@ def _evaluate_grouped(
def absent(key: str) -> GroupObservation | None:
labels = _labels_of(key)
- if truncated and labels is None:
+ # A hashed key keeps no labels, so the query cannot put that open group first, and the limit
+ # can cut it while it still breaches. Its absence means no matching log only when nothing was cut.
+ if result.truncated and labels is None:
return None
return observe(key, result.zero_counts(), labels or {})
diff --git a/products/logs/backend/platform_alert_wording.py b/products/logs/backend/platform_alert_wording.py
index 9ad57688a1c2..e610778822f2 100644
--- a/products/logs/backend/platform_alert_wording.py
+++ b/products/logs/backend/platform_alert_wording.py
@@ -21,6 +21,7 @@ from products.alerts_platform.backend.facade.contracts import (
SourceDescription,
)
from products.logs.backend.alert_evaluation_key import window_end_of
+from products.logs.backend.alert_group_columns import GROUP_COLUMNS
from products.logs.backend.logs_url_params import build_logs_url_params, has_filter_values
# A resolve reports the count that ended the firing, so it is not a breach. A held check, which
@@ -53,7 +54,13 @@ def _details(transition: AnnouncedTransition) -> tuple[MessageDetail, ...]:
f"{count} {noun} in {condition['window_minutes']}m "
f"(threshold: {condition['threshold_operator']} {condition['threshold_count']})"
)
- return (MessageDetail(label=_LABELS.get(transition.kind, "Count"), value=summary),)
+ # A grouped alert sends one message per group, so each one names the group it is about.
+ group = tuple(
+ MessageDetail(label=group_column.label, value=transition.labels[column])
+ for column, group_column in GROUP_COLUMNS.items()
+ if column in transition.labels
+ )
+ return (*group, MessageDetail(label=_LABELS.get(transition.kind, "Count"), value=summary))
def _context(filters: dict[str, Any]) -> tuple[str, ...]:
@@ -89,7 +96,37 @@ def _window_params(transition: AnnouncedTransition) -> str:
window_end = window_end_of(transition.evaluation_key)
date_to = _in_utc(replace(transition, occurred_at=window_end) if window_end else transition).occurred_at
date_from = date_to - timedelta(minutes=transition.condition["window_minutes"])
- return build_logs_url_params(transition.source_config, date_from=date_from, date_to=date_to)
+ return build_logs_url_params(_group_filters(transition), date_from=date_from, date_to=date_to)
+
+
+def _group_filters(transition: AnnouncedTransition) -> dict[str, Any]:
+ """The alert's filters narrowed to the group a transition is about, so a link opens its logs only.
+
+ The group's value replaces any list the alert has for that column, in its own field and in each
+ `filterGroup` selection of the column. An alert with a list counted only logs inside it, so the
+ group's value is one of them and the link narrows, never widens.
+ """
+ filters = dict(transition.source_config)
+ selected: dict[str, str] = {}
+ for column, group_column in GROUP_COLUMNS.items():
+ if column in transition.labels:
+ filters[group_column.filter_key] = [transition.labels[column]]
+ selected[group_column.filter_group_key] = transition.labels[column]
+ if selected and isinstance(filters.get("filterGroup"), dict):
+ # The logs scene ignores the field when `filterGroup` selects the same column.
+ filters["filterGroup"] = _narrowed(filters["filterGroup"], selected)
+ return filters
+
+
+def _narrowed(node: Any, selected: dict[str, str]) -> Any:
+ """A copy of a filter group whose include selections of the `selected` columns hold only their value."""
+ if not isinstance(node, dict):
+ return node
+ if isinstance(node.get("values"), list):
+ return {**node, "values": [_narrowed(child, selected) for child in node["values"]]}
+ if node.get("type") == "log" and node.get("operator") == "exact" and node.get("key") in selected:
+ return {**node, "value": [selected[node["key"]]]}
+ return node
_LEGACY_WEBHOOK_TYPES: Final = {
diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.py
index 782631baf0e0..a6096a439e73 100644
--- a/products/logs/backend/temporal/alert_evaluate.py
+++ b/products/logs/backend/temporal/alert_evaluate.py
@@ -23,6 +23,7 @@ with workflow.unsafe.imports_passed_through():
from products.alerts_platform.backend.facade.contracts import (
RECORD_OUTCOMES_ACTIVITY,
AlertEventKind,
+ PlatformAlertOutcome,
SourceBatchEvaluation,
SourceEvaluationInputs,
SourceOutcomeInputs,
@@ -124,26 +125,47 @@ def platform_signals(evaluation: SourceBatchEvaluation) -> list[PlatformAlertSig
}
signals: list[PlatformAlertSignal] = []
for outcome in evaluation.outcomes:
- if str(outcome.configuration_id) not in announced:
+ alert_id = announced.get(str(outcome.configuration_id))
+ if alert_id is None:
continue
- # A failed check reports on the outcome and carries no groups, so a broken alert signals from there.
- verdicts: list[tuple[AlertEventKind, float | None]] = [(group.kind, group.value) for group in outcome.groups]
- if outcome.failure is not None:
- verdicts.append((outcome.failure.kind, None))
signals.extend(
- PlatformAlertSignal(
- alert_id=announced[str(outcome.configuration_id)],
- action=_SIGNAL_ACTIONS[kind],
- result_count=int(value) if value is not None else None,
- consecutive_failures=outcome.consecutive_failures,
- evaluation_key=outcome.evaluation_key,
+ _signal(
+ alert_id,
+ outcome,
+ _SIGNAL_ACTIONS[group.kind],
+ group.value,
+ grouping_key=group.grouping_key,
+ labels=group.labels,
)
- for kind, value in verdicts
- if kind in _SIGNAL_ACTIONS
+ for group in outcome.groups
+ if group.kind in _SIGNAL_ACTIONS
)
+ # A failed check reports on the outcome and carries no groups, so a broken alert signals from there.
+ if outcome.failure is not None and outcome.failure.kind in _SIGNAL_ACTIONS:
+ signals.append(_signal(alert_id, outcome, _SIGNAL_ACTIONS[outcome.failure.kind], None))
return signals
+def _signal(
+ alert_id: str,
+ outcome: PlatformAlertOutcome,
+ action: AlertSignalAction,
+ value: float | None,
+ *,
+ grouping_key: str = "",
+ labels: dict[str, str] | None = None,
+) -> PlatformAlertSignal:
+ return PlatformAlertSignal(
+ alert_id=alert_id,
+ action=action,
+ result_count=int(value) if value is not None else None,
+ consecutive_failures=outcome.consecutive_failures,
+ evaluation_key=outcome.evaluation_key,
+ grouping_key=grouping_key,
+ labels=labels or {},
+ )
+
+
@activity.defn
@close_db_connections
def evaluate_logs_alerts_activity(inputs: SourceEvaluationInputs) -> SourceBatchEvaluation:
diff --git a/products/logs/backend/test/test_alert_check_query.py b/products/logs/backend/test/test_alert_check_query.py
index 27742c64a8ae..ab9cce99b2da 100644
--- a/products/logs/backend/test/test_alert_check_query.py
+++ b/products/logs/backend/test/test_alert_check_query.py
@@ -1076,6 +1076,8 @@ class TestExecuteRollingChecksBatched(ClickhouseTestMixin, APIBaseTest):
group_by=("service_name",),
open_groups=open_groups,
worst_is_highest=True,
+ threshold_count=10,
+ datapoints_to_alarm=1,
limit=limit,
max_execution_time=30,
ch_user=ClickHouseUser.DEFAULT,
@@ -1089,7 +1091,39 @@ class TestExecuteRollingChecksBatched(ClickhouseTestMixin, APIBaseTest):
assert grouped([], limit=2) == [self.SERVICE_B, self.SERVICE_A]
# The quieter group still comes back when it is open, ahead of a worse one the limit cuts.
- assert grouped([{"service_name": self.SERVICE_A}], limit=1) == [self.SERVICE_A]
+ assert grouped([{"service_name": self.SERVICE_A}], limit=1) == [self.SERVICE_A, self.SERVICE_B]
+
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
+ def test_a_limit_keeps_the_groups_that_breach_n_of_m_over_a_worse_latest_period(self):
+ steady, spike, smaller_spike = "rolling_grouped_steady", "rolling_grouped_spike", "rolling_grouped_spike_2"
+ # Periods are 12:15-12:20, 12:20-12:25 and 12:25-12:30.
+ self._seed(steady, datetime(2025, 12, 16, 12, 15, tzinfo=UTC), [2] * 15)
+ self._seed(spike, datetime(2025, 12, 16, 12, 25, tzinfo=UTC), [20] * 5)
+ self._seed(smaller_spike, datetime(2025, 12, 16, 12, 25, tzinfo=UTC), [12] * 5)
+ alert = self._make_alert(filters={"serviceNames": [steady, spike, smaller_spike]}, window_minutes=5)
+ nca = datetime(2025, 12, 16, 12, 30, tzinfo=UTC)
+
+ result = GroupedAlertCheckQuery(
+ team=self.team,
+ alert=alert,
+ date_from=nca - dt.timedelta(minutes=15),
+ date_to=nca,
+ group_by=("service_name",),
+ open_groups=[],
+ worst_is_highest=True,
+ threshold_count=5,
+ datapoints_to_alarm=2,
+ limit=1,
+ max_execution_time=30,
+ ch_user=ClickHouseUser.DEFAULT,
+ ).execute_rolling_checks(nca=nca, window_minutes=5, cadence_minutes=5, period_count=3)
+
+ # The row past the limit is the worst group cut.
+ assert [(g.labels["service_name"], [c.count for c in g.counts]) for g in result.groups] == [
+ (steady, [10, 10, 10]),
+ (spike, [0, 0, 100]),
+ ]
+ assert result.truncated
@time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_single_alert_cohort_matches_per_alert_path(self):
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index cd98b07cbfa8..950168d24251 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -1,4 +1,5 @@
import time
+from dataclasses import replace
from datetime import UTC, datetime, timedelta
from typing import Any
from uuid import UUID, uuid4
@@ -367,8 +368,12 @@ class TestLogsAlertEvaluation(APIBaseTest):
patch(f"{_MODULE}.fetch_live_logs_checkpoint", return_value=None),
patch(f"{_MODULE}.GroupedAlertCheckQuery") as query,
):
- query.return_value.execute_rolling_checks.return_value = GroupedRollingResult(
- groups=groups, period_starts=[now], query_duration_ms=1
+ # `counts` is in the order the query ranks groups, and the query keeps one row past its limit.
+ query.return_value.execute_rolling_checks.side_effect = lambda *_args: GroupedRollingResult(
+ groups=groups[: query.call_args.kwargs["limit"] + 1],
+ period_starts=[now],
+ query_duration_ms=1,
+ truncated=len(groups) > query.call_args.kwargs["limit"],
)
return evaluate_logs_batch(self.team.id, slot_of(configuration.next_check_at, now), now)
@@ -384,19 +389,20 @@ class TestLogsAlertEvaluation(APIBaseTest):
(outcome,) = self._run_grouped(configuration, counts).outcomes
return {group.labels.get("service_name", group.grouping_key[:7]): group.kind for group in outcome.groups}
- assert run_after({"api": 600, "web": 550}) == {}
+ assert run_after({"api": 600, "web": 550, "cron": 520}) == {}
assert run_after({"api": 600}) == {"sha256:": AlertEventKind.RESOLVED}
def test_a_grouped_alert_overflows_at_its_cap_until_a_resolved_group_gives_up_its_slot(self) -> None:
grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service_name",), max_instances=2)
configuration = self._configuration(grouping=grouping.to_stored())
- first = self._run_grouped(configuration, {"api": 500, "web": 3, "worker": 400, "cron": 300})
+ first = self._run_grouped(configuration, {"api": 500, "worker": 400, "cron": 300, "web": 3})
self._record(first)
(outcome,) = first.outcomes
(delivery,) = first.deliveries
- # The quiet group gets no row, and the cap admits the two worst of the three breaching.
+ # The cap admits the two worst of the three breaching, and the third is reported although
+ # a query cut at the cap would never have returned it.
assert [(group.labels["service_name"], group.kind) for group in outcome.groups] == [
("api", AlertEventKind.FIRING),
("worker", AlertEventKind.FIRING),
@@ -813,6 +819,26 @@ class TestPlatformAlertSignals(SimpleTestCase):
assert all(signal.alert_id == "legacy-1" for signal in signals)
assert [(s.action, s.result_count, s.consecutive_failures) for s in signals] == expected
+ def test_each_firing_group_of_one_evaluation_signals_under_its_own_key(self) -> None:
+ groups = tuple(
+ GroupOutcome(
+ grouping_key=grouping_key_of({"service_name": service}),
+ kind=AlertEventKind.FIRING,
+ new_state="firing",
+ notified=True,
+ value=500.0,
+ labels={"service_name": service},
+ )
+ for service in ("api", "web")
+ )
+ outcome = replace(_outcome(AlertEventKind.FIRING), groups=groups)
+ evaluation = SourceBatchEvaluation(outcomes=(outcome,), deliveries=(_delivery_for(owned_by_platform=True),))
+
+ signals = platform_signals(evaluation)
+
+ assert [s.labels for s in signals] == [{"service_name": "api"}, {"service_name": "web"}]
+ assert len({s.idempotency_key for s in signals}) == 2
+
class TestPlatformAlertSignalFacts(APIBaseTest):
def test_a_signal_carries_the_logs_alert_as_it_is_and_skips_a_deleted_one(self) -> None:
@@ -833,11 +859,26 @@ class TestPlatformAlertSignalFacts(APIBaseTest):
PlatformAlertSignal(
alert_id=str(uuid4()), action="firing", result_count=1, consecutive_failures=0, evaluation_key="k-1"
),
+ PlatformAlertSignal(
+ alert_id=str(alert.id),
+ action="firing",
+ result_count=700,
+ consecutive_failures=0,
+ evaluation_key="k-1",
+ grouping_key='{"service_name":"web"}',
+ labels={"service_name": "web"},
+ ),
],
)
assert [(n.alert_id, n.alert_name, n.threshold_count, n.result_count, n.filters) for n in notified] == [
- (str(alert.id), "API errors", 10, 500, {"serviceNames": ["api"]})
+ (str(alert.id), "API errors", 10, 500, {"serviceNames": ["api"]}),
+ (str(alert.id), "API errors", 10, 700, {"serviceNames": ["api"]}),
+ ]
+ # A retried emission of the same announcement must not start a second signal, and a second
+ # group of the same evaluation is not a retry.
+ assert [n.idempotency_key for n in notified] == [
+ f"{alert.id}:firing:k-1",
+ f'{alert.id}:firing:k-1:{{"service_name":"web"}}',
]
- # A retried emission of the same announcement must not start a second signal.
- assert notified[0].idempotency_key == f"{alert.id}:firing:k-1"
+ assert notified[1].group_labels == {"service_name": "web"}
diff --git a/products/logs/backend/test/test_alert_signal_emitter.py b/products/logs/backend/test/test_alert_signal_emitter.py
index fc040582cc7c..32e990ff5222 100644
--- a/products/logs/backend/test/test_alert_signal_emitter.py
+++ b/products/logs/backend/test/test_alert_signal_emitter.py
@@ -1,3 +1,5 @@
+import dataclasses
+
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -68,11 +70,20 @@ class TestBuildSignalExtra:
assert extra["filters"] == {"serviceNames": ["checkout"], "severityLevels": ["error"]}
assert extra["url"].endswith("/project/7/logs")
- @parameterized.expand([("firing",), ("broken",)])
- def test_built_extra_satisfies_signal_schema(self, action):
+ @parameterized.expand(
+ [
+ ("firing", "firing", {}),
+ ("broken", "broken", {}),
+ ("grouped_firing", "firing", {"service_name": "checkout", "severity_text": "error"}),
+ ]
+ )
+ def test_built_extra_satisfies_signal_schema(
+ self, _name: str, action: AlertSignalAction, group_labels: dict[str, str]
+ ) -> None:
# emit_signal validates extra against this variant with extra="forbid";
# if build_signal_extra drifts from the schema, every emit fails validation.
- LogsAlertStateChangeSignalExtra.model_validate(build_signal_extra(_notified(action)))
+ notified = dataclasses.replace(_notified(action), group_labels=group_labels)
+ LogsAlertStateChangeSignalExtra.model_validate(build_signal_extra(notified))
class TestBuildSignalDescription:
diff --git a/products/logs/backend/test/test_platform_alert_wording.py b/products/logs/backend/test/test_platform_alert_wording.py
index 4797eb0742f2..4b33a49b12c8 100644
--- a/products/logs/backend/test/test_platform_alert_wording.py
+++ b/products/logs/backend/test/test_platform_alert_wording.py
@@ -36,6 +36,23 @@ def _transition(
)
+def _facets(services: list[str], levels: list[str]) -> dict[str, Any]:
+ route = {"key": "http.route", "type": "log_attribute", "operator": "exact", "value": ["/checkout"]}
+ return {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {"key": "service_name", "type": "log", "operator": "exact", "value": services},
+ {"key": "severity_level", "type": "log", "operator": "exact", "value": levels},
+ route,
+ ],
+ }
+ ],
+ }
+
+
class TestLogsPlatformAlertWording(SimpleTestCase):
@parameterized.expand(
[
@@ -86,15 +103,48 @@ class TestLogsPlatformAlertWording(SimpleTestCase):
assert description.context == expected
- def test_the_link_opens_the_logs_the_check_counted(self) -> None:
- description = describe_logs_transition(project_id=7, transition=_transition(filters={"serviceNames": ["api"]}))
+ @parameterized.expand(
+ [
+ ("ungrouped", {}, (), ["api", "worker"], ["error", "warn"]),
+ (
+ "grouped",
+ {"service_name": "worker", "severity_text": "error"},
+ (MessageDetail(label="Service", value="worker"), MessageDetail(label="Severity", value="error")),
+ ["worker"],
+ ["error"],
+ ),
+ ]
+ )
+ def test_a_message_names_the_group_and_links_to_the_logs_the_check_counted(
+ self,
+ _name: str,
+ labels: dict[str, str],
+ group_details: tuple[MessageDetail, ...],
+ service_names: list[str],
+ severity_levels: list[str],
+ ) -> None:
+ filters = {
+ "serviceNames": ["api", "worker"],
+ "severityLevels": ["error", "warn"],
+ "filterGroup": _facets(["api", "worker"], ["error", "warn"]),
+ }
+ transition = replace(_transition(filters=filters), labels=labels)
+
+ description = describe_logs_transition(project_id=7, transition=transition)
+ assert description.details == (
+ *group_details,
+ MessageDetail(label="Threshold breached", value="11 logs in 10m (threshold: above 10)"),
+ )
assert description.data_link is not None
assert description.data_link.label == "View logs"
url = urlsplit(description.data_link.url)
params = parse_qs(url.query)
assert url.path == "/project/7/logs"
- assert json.loads(params["serviceNames"][0]) == ["api"]
+ assert json.loads(params["serviceNames"][0]) == service_names
+ assert json.loads(params["severityLevels"][0]) == severity_levels
+ # The logs scene reads a column's selection from `filterGroup` when the group holds one.
+ assert json.loads(params["filterGroup"][0]) == _facets(service_names, severity_levels)
assert json.loads(params["dateRange"][0]) == {
"date_from": "2026-10-08T17:55:00+00:00",
"date_to": "2026-10-08T18:05:00+00:00",
diff --git a/products/signals/backend/contracts.py b/products/signals/backend/contracts.py
index 5723e8a5c263..4df611278a7f 100644
--- a/products/signals/backend/contracts.py
+++ b/products/signals/backend/contracts.py
@@ -409,6 +409,8 @@ class LogsAlertStateChangeSignalExtra(SignalExtraBase):
consecutive_failures: int
filters: dict[str, object]
url: str
+ # The group a grouped alert fired for, by column. Absent for an ungrouped alert.
+ group_labels: dict[str, str] | None = None
class LogsAlertStateChangeSignalInput(SignalInputBase):
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 06059a05f6bb..9653eb691206 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -2070,6 +2070,8 @@ export const LogsAlertStateChangeSignalExtraThresholdOperatorEnumApi = {
export type LogsAlertStateChangeSignalExtraApiFilters = { [key: string]: unknown }
+export type LogsAlertStateChangeSignalExtraApiGroupLabels = { [key: string]: string } | null
+
export interface LogsAlertStateChangeSignalExtraApi {
alert_id: string
alert_name: string
@@ -2081,6 +2083,7 @@ export interface LogsAlertStateChangeSignalExtraApi {
consecutive_failures: number
filters: LogsAlertStateChangeSignalExtraApiFilters
url: string
+ group_labels?: LogsAlertStateChangeSignalExtraApiGroupLabels
}
export interface ReplayVisionScannerFindingSignalExtraApi {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8483c3aab4bc..4e00ea47821e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -63151,6 +63151,8 @@ export namespace Schemas {
export type LogsAlertStateChangeSignalExtraFilters = { [key: string]: unknown };
+ export type LogsAlertStateChangeSignalExtraGroupLabels = {[key: string]: string} | null;
+
export type LogsAlertStateChangeSignalExtraActionEnum = typeof LogsAlertStateChangeSignalExtraActionEnum[keyof typeof LogsAlertStateChangeSignalExtraActionEnum];
@@ -63178,6 +63180,7 @@ export namespace Schemas {
consecutive_failures: number;
filters: LogsAlertStateChangeSignalExtraFilters;
url: string;
+ group_labels?: LogsAlertStateChangeSignalExtraGroupLabels;
}
/**