Skip to content

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

feat(logs): fire platform logs alerts per service and severity (#114283)

Jimmy Zhua3366f1f89bb
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index c304b471f082..c68c1d2d5a07 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -288,7 +288,9 @@ a batch key spends the manifest bound on work its own evaluation then drops.
`check_status` lives on the configuration, not on an instance, for grouped and ungrouped configurations alike,
because a failed check returns no group to attribute the failure to.
-`record_outcomes` moves an ERRORED or BROKEN group verdict onto it and leaves the instance's firing state alone.
+A check that could not evaluate reports its failure on the outcome as a `CheckFailure`, with no groups, for every source.
+`record_outcomes` writes the machine's ERRORED or BROKEN onto `check_status`, leaves every instance alone, and writes one history row with the empty grouping key and the nil UUID as `alert_id`, which stands in for "no instance" because the sort key rejects Nullable.
+So a failed grouped check posts one error message, not one per group.
The check input hands the shared machine the configuration's status in place of each instance's state while it is not OK,
so the machine reads what it read when both shared one field.
@@ -302,6 +304,10 @@ The count it turned away travels on the delivery as `overflowed`, and the last m
An instance that is not firing, not muted, and that no check returned for longer than both 24 hours and its cooldown is deleted, which frees its slot.
Nothing is reaped while the configuration's checks fail, because a failed check returns no groups and every instance would look gone.
+Logs is the first source that groups, by `service_name` and `severity_text` only.
+A grouped logs alert leaves the batched cohort and runs `GroupedAlertCheckQuery`, one query per alert, with its open groups ordered first and the rest worst first.
+A group with no instance whose check decides nothing is left out, so a quiet service costs no row, and an open group the query does not return is checked against a zero count so it can resolve.
+
`alerts_platform_checks_skipped_total{source,reason}` counts these by reason.
### What a check leaves behind
diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.py
index 0d2b94075edb..8531df765a1a 100644
--- a/products/alerts/backend/platform_source_cycle.py
+++ b/products/alerts/backend/platform_source_cycle.py
@@ -42,6 +42,7 @@ from products.alerts_platform.backend.facade.api import due_check_ids, due_check
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertEventKind,
+ CheckFailure,
GroupOutcome,
PlatformAlertCheckInput,
PlatformAlertOutcome,
@@ -196,7 +197,10 @@ def evaluate_insight_check(
def _delivery(check: PlatformAlertCheckInput, outcome: PlatformAlertOutcome) -> AlertDeliveryRequest | None:
- if not any(group.kind.value in _EVENT_IDS_BY_KIND for group in outcome.groups):
+ kinds = [group.kind for group in outcome.groups]
+ if outcome.failure is not None:
+ kinds.append(outcome.failure.kind)
+ if not any(kind.value in _EVENT_IDS_BY_KIND for kind in kinds):
return None
legacy_id = str(check.legacy_configuration_id) if check.legacy_configuration_id is not None else None
if legacy_id not in LIVE_DELIVERY_INSIGHT_ALERT_IDS:
@@ -298,6 +302,7 @@ def _decide(check: PlatformAlertCheckInput, now: datetime, *, evaluation_id: str
error_message=str(error),
skip=SkipReason.BROKEN_CONFIG,
disable=True,
+ failed=True,
)
except Exception as error:
if classify_query_error(error) == QueryErrorCategory.RATE_LIMITED:
@@ -352,6 +357,7 @@ def _verdict(
query_duration_ms=query_duration_ms,
skip=skip,
disable=outcome.disable,
+ failed=skip == SkipReason.QUERY_FAILED,
)
@@ -382,6 +388,7 @@ def _recorded(
query_duration_ms: int | None = None,
skip: SkipReason | None = None,
disable: bool = False,
+ failed: bool = False,
) -> PlatformAlertOutcome:
"""The one place an outcome is built. Every path goes through the firing decision, because
an outcome without an episode clears the start of a firing the alert is still in."""
@@ -392,20 +399,29 @@ def _recorded(
previous_state = check.instance().state
if previous_state != outcome.new_state.value:
safe_record(increment_state_transition, source, previous_state, outcome.new_state.value)
+ kind = NOTIFICATION_EVENT_KINDS[notification]
+ firing_episode = decide_firing_episode(snapshot, outcome, now, policy=INSIGHT_ALERT_POLICY)
return PlatformAlertOutcome(
configuration_id=check.id,
evaluation_key=_evaluation_key(check, now),
consecutive_failures=outcome.consecutive_failures,
- groups=(
+ groups=()
+ if failed
+ else (
GroupOutcome(
grouping_key="",
- kind=NOTIFICATION_EVENT_KINDS[notification],
+ kind=kind,
new_state=outcome.new_state.value,
notified=notified,
- firing_episode=decide_firing_episode(snapshot, outcome, now, policy=INSIGHT_ALERT_POLICY),
+ firing_episode=firing_episode,
value=value,
),
),
+ failure=CheckFailure(
+ kind=kind, new_state=outcome.new_state.value, notified=notified, firing_episode=firing_episode
+ )
+ if failed
+ else None,
error_message=error_message,
query_duration_ms=query_duration_ms,
disable=disable,
diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.py
index 73639d0dc46a..c7a3d7a24c35 100644
--- a/products/alerts/backend/test/test_platform_source_cycle.py
+++ b/products/alerts/backend/test/test_platform_source_cycle.py
@@ -191,7 +191,8 @@ class TestPlatformInsightEvaluation(APIBaseTest):
outcome, _ = self._evaluate(self._copy(self._alert()), result=AlertExtractionError("bad query shape"))
assert outcome is not None
- assert (outcome.groups[0].kind, outcome.groups[0].new_state, outcome.disable) == (
+ assert outcome.failure is not None and outcome.groups == ()
+ assert (outcome.failure.kind, outcome.failure.new_state, outcome.disable) == (
AlertEventKind.ERRORED,
"errored",
True,
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 8d8e19dff06a..20ffc74d4992 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -363,6 +363,22 @@ class GroupOutcome:
muted_notification: str = ""
+@frozen
+class CheckFailure:
+ """What the shared machine decided for a check that could not evaluate.
+
+ It belongs to the check, not to a group, because a failed query returns no groups to attribute
+ the failure to. `new_state` is the machine's verdict, which stays the prior state under a
+ policy that rides through errors and becomes ERRORED or BROKEN under one that does not.
+ """
+
+ kind: AlertEventKind
+ new_state: str
+ notified: bool
+ firing_episode: FiringEpisode | None = None
+ muted_notification: str = ""
+
+
@frozen
class PlatformAlertOutcome:
"""What one check decided. The platform turns this into rows.
@@ -371,13 +387,16 @@ class PlatformAlertOutcome:
leaves its due time where it was, so discovery finds the same work every tick.
The fields here describe the check, and each of `groups` describes one group's verdict. A failed
- query fails every group at once, so the failure count and `disable` belong to the check.
+ query fails every group at once, so the failure count, `disable` and `failure` belong to the
+ check, and a failed check carries no groups. A successful check of an ungrouped source carries
+ exactly one group with the empty key; a grouped source's may carry none when nothing is open.
"""
configuration_id: UUID
evaluation_key: str
consecutive_failures: int
- groups: tuple[GroupOutcome, ...]
+ groups: tuple[GroupOutcome, ...] = ()
+ failure: CheckFailure | None = None
error_message: str | None = None
query_duration_ms: int | None = None
# Recording an outcome without it leaves a configuration discovery keeps handing back to an
@@ -388,10 +407,8 @@ class PlatformAlertOutcome:
schedule_group: str | None = None
def __post_init__(self) -> None:
- # A check's ERRORED or BROKEN arrives as a group's verdict, so an outcome with no group
- # would record a check that wrote no status and no history.
- if not self.groups:
- raise ValueError("an outcome needs at least one group")
+ if self.failure is not None and self.groups:
+ raise ValueError("a failed check reports no groups")
keys = [group.grouping_key for group in self.groups]
if len(set(keys)) != len(keys):
raise ValueError("an outcome names each group once")
@@ -535,6 +552,7 @@ class PlatformConfigurationSnapshot:
next_check_at: datetime | None
consecutive_failures: int
owner: str
+ check_status: str
@frozen
diff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.py
index 4023468ec201..75385768031e 100644
--- a/products/alerts_platform/backend/facade/testing.py
+++ b/products/alerts_platform/backend/facade/testing.py
@@ -24,7 +24,11 @@ from products.alerts_platform.backend.models import PlatformAlert, PlatformAlert
def _configuration_snapshot(row: PlatformAlertConfiguration) -> PlatformConfigurationSnapshot:
return PlatformConfigurationSnapshot(
- id=row.id, next_check_at=row.next_check_at, consecutive_failures=row.consecutive_failures, owner=row.owner
+ id=row.id,
+ next_check_at=row.next_check_at,
+ consecutive_failures=row.consecutive_failures,
+ check_status=row.check_status,
+ owner=row.owner,
)
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index b1307164dd68..6c55bcff1d02 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -17,6 +17,7 @@ from posthog.dataclasses import frozen
from posthog.models import Team
from products.alerts_platform.backend.facade.contracts import (
+ CheckFailure,
Grouping,
GroupOutcome,
InstanceCheckState,
@@ -304,36 +305,43 @@ def _condition_snapshot(configuration: PlatformAlertConfiguration) -> dict[str,
}
+# The `alert_id` of a history row that belongs to the check rather than to a group. The column is in
+# the table's sort key, which rejects Nullable, so the nil UUID stands in for "no instance".
+CONFIGURATION_ROW_ALERT_ID: Final = UUID(int=0)
+
+
def _event_row(
configuration: PlatformAlertConfiguration,
- alert: PlatformAlert,
outcome: PlatformAlertOutcome,
- group: GroupOutcome,
+ verdict: GroupOutcome | CheckFailure,
+ *,
+ alert: PlatformAlert | None,
previous_state: str,
now: datetime,
) -> PlatformAlertEventRow:
+ group = verdict if isinstance(verdict, GroupOutcome) else None
return PlatformAlertEventRow(
team_id=configuration.team_id,
source_kind=configuration.source_kind,
configuration_id=configuration.id,
- alert_id=alert.id,
- grouping_key=alert.grouping_key,
+ alert_id=alert.id if alert else CONFIGURATION_ROW_ALERT_ID,
+ grouping_key=alert.grouping_key if alert else "",
evaluation_key=outcome.evaluation_key,
- kind=group.kind.value,
+ kind=verdict.kind.value,
alert_name=configuration.name,
previous_state=previous_state,
- state=group.new_state,
+ state=verdict.new_state,
# The whole episode, ended or not. A resolve names the firing it closed, which is what a
# thread key needs and what the alert row no longer holds.
- episode_started_at=group.firing_episode.started_at if group.firing_episode else None,
- value=group.value,
- labels=group.labels,
+ episode_started_at=verdict.firing_episode.started_at if verdict.firing_episode else None,
+ value=group.value if group else None,
+ labels=group.labels if group else {},
condition_snapshot=_condition_snapshot(configuration),
source_config_snapshot=configuration.source_config,
query_duration_ms=outcome.query_duration_ms,
error_message=outcome.error_message,
consecutive_failures=outcome.consecutive_failures,
- muted_notification=group.muted_notification,
+ muted_notification=verdict.muted_notification,
occurred_at=now,
)
@@ -358,8 +366,15 @@ _CHECK_STATUSES: Final = frozenset(
)
-def _check_status(outcome: PlatformAlertOutcome) -> str:
- """BROKEN over ERRORED over OK, because a check is as bad as its worst verdict."""
+def _check_status(configuration: PlatformAlertConfiguration, outcome: PlatformAlertOutcome) -> str:
+ """BROKEN over ERRORED over OK, because a check is as bad as its worst verdict.
+
+ A failure that the policy rides through leaves the status where it was, so only the machine's
+ ERRORED or BROKEN moves it.
+ """
+ if outcome.failure is not None:
+ failed = outcome.failure.new_state
+ return failed if failed in _CHECK_STATUSES else configuration.check_status
states = {group.new_state for group in outcome.groups}
for status in (PlatformAlertConfiguration.CheckStatus.BROKEN, PlatformAlertConfiguration.CheckStatus.ERRORED):
if status.value in states:
@@ -410,6 +425,19 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
for group in by_id[str(configuration.id)].groups
},
)
+ # The empty-key instance of each failed configuration, so a failure row states the state
+ # an ungrouped check found.
+ alerts_by_configuration = {
+ key.configuration_id: alert
+ for key, alert in _instances(
+ team_id,
+ [
+ _InstanceKey(configuration_id=str(configuration.id), grouping_key="")
+ for configuration in configurations
+ if by_id[str(configuration.id)].failure is not None
+ ],
+ ).items()
+ }
# One read for the batch. Every configuration in it belongs to this team, and a
# calendar recurrence resolves its anchor against the team's zone.
team_timezone = Team.objects.filter(id=team_id).values_list("timezone", flat=True).first() or "UTC"
@@ -425,7 +453,16 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
continue
alert.last_seen_at = now
# Before either row is mutated, so the history row keeps the state the check found.
- rows.append(_event_row(configuration, alert, outcome, group, _check_state(configuration, alert), now))
+ rows.append(
+ _event_row(
+ configuration,
+ outcome,
+ group,
+ alert=alert,
+ previous_state=_check_state(configuration, alert),
+ now=now,
+ )
+ )
if group.notified:
alert.last_notified_at = now
if group.new_state in _CHECK_STATUSES:
@@ -436,7 +473,19 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
alert.firing_started_at = episode.started_at if episode and not episode.ended else None
alert.state = group.new_state
- configuration.check_status = _check_status(outcome)
+ if outcome.failure is not None:
+ ungrouped = alerts_by_configuration.get(str(configuration.id))
+ rows.append(
+ _event_row(
+ configuration,
+ outcome,
+ outcome.failure,
+ alert=None,
+ previous_state=_check_state(configuration, ungrouped),
+ now=now,
+ )
+ )
+ configuration.check_status = _check_status(configuration, outcome)
configuration.consecutive_failures = outcome.consecutive_failures
if outcome.disable:
configuration.enabled = False
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index 9453ba4ca6ac..5b9ce41f6c38 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -22,6 +22,7 @@ from products.alerts_platform.backend.facade.api import (
)
from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
+ CheckFailure,
FiringEpisode,
GroupAdmission,
Grouping,
@@ -35,6 +36,7 @@ from products.alerts_platform.backend.facade.contracts import (
SourceKind,
)
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertState
+from products.alerts_platform.backend.logic.platform_lifecycle import CONFIGURATION_ROW_ALERT_ID
from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
from products.alerts_platform.backend.models.platform_alert_events_sql import SHARDED_PLATFORM_ALERT_EVENTS_TABLE
@@ -78,7 +80,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
"configuration_id": self.configuration.id,
"evaluation_key": f"window:{at.isoformat()}",
"consecutive_failures": 0,
- "groups": groups or (GroupOutcome(**group_fields),),
+ "groups": (GroupOutcome(**group_fields),) if groups is None else groups,
}
fields.update(overrides)
# History rides `transaction.on_commit`, which a `TestCase` transaction never reaches.
@@ -183,15 +185,25 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
def test_a_failed_check_marks_the_configuration_and_the_instance_keeps_its_firing(self) -> None:
self._record(firing_episode=FiringEpisode(started_at=self.cutoff, ended=False))
+ failed_at = self._next_due()
self._record(
- at=self._next_due(),
- kind=AlertEventKind.ERRORED,
- new_state="errored",
- notified=False,
+ at=failed_at,
+ groups=(),
+ failure=CheckFailure(
+ kind=AlertEventKind.ERRORED,
+ new_state="errored",
+ notified=True,
+ firing_episode=FiringEpisode(started_at=self.cutoff, ended=True),
+ ),
consecutive_failures=1,
- firing_episode=FiringEpisode(started_at=self.cutoff, ended=True),
)
+ failure_rows = sync_execute(
+ "SELECT alert_id, grouping_key, previous_state, state FROM platform_alert_events "
+ "WHERE team_id = %(team_id)s AND configuration_id = %(configuration_id)s AND occurred_at = %(at)s",
+ {"team_id": self.team.id, "configuration_id": self.configuration.id, "at": failed_at},
+ )
+ assert failure_rows == [(CONFIGURATION_ROW_ALERT_ID, "", "firing", "errored")]
due = self._next_due()
stored = self._alert()
with team_scope(self.team.id):
@@ -605,7 +617,7 @@ def test_a_grouping_rejects_keys_its_mode_cannot_use(fields: dict[str, Any]) ->
@pytest.mark.parametrize(
"overrides",
[
- {"groups": ()},
+ {"failure": CheckFailure(kind=AlertEventKind.ERRORED, new_state="errored", notified=True)},
{"groups": (_group("api"), _group("api"))},
],
)
diff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.py
index ace8d3e366cb..4b3e3fbee63b 100644
--- a/products/logs/backend/alert_check_query.py
+++ b/products/logs/backend/alert_check_query.py
@@ -590,6 +590,132 @@ 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]
+ counts: list[BucketedCount]
+
+
+@dataclass(frozen=True)
+class GroupedRollingResult:
+ groups: list[GroupCounts]
+ period_starts: list[dt.datetime]
+ query_duration_ms: int
+
+ def zero_counts(self) -> list[BucketedCount]:
+ """The counts of a group with no matching log in any period, which returns no row."""
+ return [BucketedCount(timestamp=start, count=0) for start in self.period_starts]
+
+
+class GroupedAlertCheckQuery:
+ """One alert's rolling-window counts, split by the values of its grouping columns.
+
+ 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.
+ """
+
+ def __init__(
+ self,
+ *,
+ team: Team,
+ alert: AlertQuerySubject,
+ date_from: dt.datetime,
+ date_to: dt.datetime,
+ group_by: Sequence[str],
+ open_groups: Sequence[dict[str, str]],
+ worst_is_highest: bool,
+ 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
+ if not group_by or unknown:
+ raise ValueError(f"A logs alert cannot group by {sorted(unknown) or 'nothing'}")
+ self.team = team
+ self.alert = alert
+ self.group_by = tuple(group_by)
+ self.open_groups = list(open_groups)
+ self.worst_is_highest = worst_is_highest
+ self.limit = limit
+ self._ch_user = ch_user
+ self._settings = AlertCheckQuery.SETTINGS.model_copy(
+ update={"max_execution_time": max_execution_time, "timeout_overflow_mode": "throw"}
+ )
+ self.where_expr = build_alert_where_expr(team=team, alert=alert, date_from=date_from, date_to=date_to)
+
+ def execute_rolling_checks(
+ self, nca: dt.datetime, window_minutes: int, cadence_minutes: int, period_count: int
+ ) -> GroupedRollingResult:
+ _tag_alert_query(team=self.team, alert_config_id=str(self.alert.id), source="logs_alert_grouped")
+ ranges = _rolling_check_ranges(nca, window_minutes, cadence_minutes, period_count)
+ query = self._build_query(ranges)
+
+ start_ms = time.monotonic_ns() // 1_000_000
+ response = execute_hogql_query(
+ query_type="alert_check",
+ query=query,
+ team=self.team,
+ workload=Workload.LOGS,
+ ch_user=self._ch_user,
+ settings=self._settings,
+ limit_context=LimitContext.QUERY,
+ modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),
+ )
+ duration_ms = time.monotonic_ns() // 1_000_000 - start_ms
+
+ width = len(self.group_by)
+ groups = [
+ GroupCounts(
+ labels={column: str(value) for column, value in zip(self.group_by, row[:width])},
+ counts=[BucketedCount(timestamp=start, count=count) for (start, _), count in zip(ranges, row[width:])],
+ )
+ for row in response.results
+ ]
+ return GroupedRollingResult(
+ groups=groups, period_starts=[start for start, _ in ranges], query_duration_ms=duration_ms
+ )
+
+ 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: list[ast.Expr] = [
+ ast.Alias(alias=f"period_{i}", expr=ast.Call(name="countIf", args=[_timestamp_in_range(start, end)]))
+ for i, (start, end) in enumerate(ranges)
+ ]
+ order_by = [
+ 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])
+ known = ast.Tuple(
+ exprs=[
+ ast.Tuple(exprs=[ast.Constant(value=labels.get(column, "")) for column in self.group_by])
+ for labels in self.open_groups
+ ]
+ )
+ is_open = ast.CompareOperation(op=ast.CompareOperationOp.In, left=group, right=known)
+ order_by.insert(0, ast.OrderExpr(expr=is_open, order="DESC"))
+ return ast.SelectQuery(
+ select=[*columns, *periods],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["logs"])),
+ 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),
+ )
+
+
# Fall back to `now` when the checkpoint is older than this — a quiet partition
# can pin `min(...)` hours behind while other partitions have fresh data.
CHECKPOINT_MAX_STALENESS = dt.timedelta(minutes=5)
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 0bc90b4c2a81..a5ba6755c790 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -14,7 +14,9 @@ logs stack would have said given the same configuration. The lifecycle decision
the shared machine configured with this source's policy, not from the logs product.
"""
+import json
import time
+import hashlib
from collections.abc import Sequence
from dataclasses import replace
from datetime import datetime, timedelta
@@ -37,6 +39,8 @@ from products.alerts_platform.backend.facade.api import due_checks, refresh_sett
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertEventKind,
+ CheckFailure,
+ GroupingMode,
GroupOutcome,
MuteReason,
PlatformAlertCheckInput,
@@ -73,8 +77,10 @@ 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,
fetch_live_logs_checkpoint,
is_projection_eligible,
resolve_alert_date_to,
@@ -242,8 +248,10 @@ def is_in_quiet_hours(schedule_restriction: dict | None, now: datetime, tz_name:
return False
-def _snapshot(check: PlatformAlertCheckInput, prior_breached: tuple[bool, ...]) -> AlertSnapshot:
- instance = check.instance()
+def _snapshot(
+ check: PlatformAlertCheckInput, prior_breached: tuple[bool, ...], grouping_key: str = ""
+) -> AlertSnapshot:
+ instance = check.instance(grouping_key)
return AlertSnapshot(
state=AlertState(instance.state),
cooldown=timedelta(minutes=check.cooldown_minutes),
@@ -278,6 +286,7 @@ def _record_check_metrics(
skip: SkipReason | None = None,
muted_by_quiet_hours: bool = False,
now: datetime,
+ grouping_key: str = "",
) -> None:
safe_record(increment_checks, SourceKind.LOGS.value, notification.value)
if skip is not None:
@@ -286,7 +295,7 @@ def _record_check_metrics(
# The machine owns the snooze predicate, so the source's flag is what separates the two.
mute_reason = MuteReason.QUIET_HOURS if muted_by_quiet_hours else MuteReason.SNOOZE
safe_record(increment_notifications_muted, SourceKind.LOGS.value, mute_reason.value)
- previous_state = check.instance().state
+ previous_state = check.instance(grouping_key).state
if previous_state != new_state:
safe_record(increment_state_transition, SourceKind.LOGS.value, previous_state, new_state)
if check.next_check_at is not None:
@@ -341,25 +350,42 @@ def _recorded(
query_duration_ms: int | None = None,
muted_notification: str = "",
disable: bool = False,
+ failed: bool = False,
) -> PlatformAlertOutcome:
"""The one place a recorded outcome is built, so every path states the firing the same way."""
- return PlatformAlertOutcome(
- configuration_id=check.id,
- evaluation_key=evaluation_key,
- consecutive_failures=outcome.consecutive_failures,
- groups=(
+ firing_episode = decide_firing_episode(_snapshot(check, ()), outcome, now, policy=PLATFORM_LOGS_ALERT_POLICY)
+ failure = (
+ CheckFailure(
+ kind=kind,
+ new_state=outcome.new_state.value,
+ notified=notified,
+ firing_episode=firing_episode,
+ muted_notification=muted_notification,
+ )
+ if failed
+ else None
+ )
+ groups = (
+ ()
+ if failed
+ else (
GroupOutcome(
grouping_key="",
kind=kind,
new_state=outcome.new_state.value,
notified=notified,
- firing_episode=decide_firing_episode(
- _snapshot(check, ()), outcome, now, policy=PLATFORM_LOGS_ALERT_POLICY
- ),
+ firing_episode=firing_episode,
value=value,
muted_notification=muted_notification,
),
- ),
+ )
+ )
+ return PlatformAlertOutcome(
+ configuration_id=check.id,
+ evaluation_key=evaluation_key,
+ consecutive_failures=outcome.consecutive_failures,
+ groups=groups,
+ failure=failure,
error_message=error_message,
query_duration_ms=query_duration_ms,
disable=disable,
@@ -376,6 +402,7 @@ def _delivery(
now: datetime,
value: float | None = None,
query_duration_ms: int | None = None,
+ failed: bool = False,
) -> Decision:
"""What the platform records for a verdict, and what delivery would announce for it."""
recorded = _recorded(
@@ -392,6 +419,7 @@ def _delivery(
"" if outcome.muted_notification == NotificationAction.NONE else outcome.muted_notification.value
),
disable=outcome.disable,
+ failed=failed,
)
return recorded, _request(check, recorded, outcome, sends_messages=outcome.notification != NotificationAction.NONE)
@@ -515,6 +543,7 @@ def _held(
notified=False,
now=now,
error_message=error_message,
+ failed=True,
)
_record_check_metrics(
check, new_state=outcome.new_state.value, notification=NotificationAction.NONE, skip=skip, now=now
@@ -557,7 +586,13 @@ def _evaluate_cohort(
# batch would advance every other check's schedule and leave this one due with its failure
# counter unmoved, never reaching the escalation that stops it.
return [
- _delivery(check, _failed(check, error, now=now, muted=check.id in muted_ids), window_end=date_to, now=now)
+ _delivery(
+ check,
+ _failed(check, error, now=now, muted=check.id in muted_ids),
+ window_end=date_to,
+ now=now,
+ failed=True,
+ )
for check in checks
]
@@ -569,17 +604,26 @@ def _evaluate_cohort(
value: float | None = float(buckets[-1].count) if buckets else 0.0
# One query serves the cohort, so every check in it records the same duration.
duration_ms: int | None = result.query_duration_ms
+ failed = False
try:
outcome = _evaluate_one(check, buckets, now=now, muted=muted)
except Exception as error:
logger.exception("Failed to evaluate a logs alert", check_id=str(check.id), error=str(error))
outcome = _failed(check, error, now=now, muted=muted)
# A check that reached no verdict measured nothing.
- value, duration_ms = None, None
+ value, duration_ms, failed = None, None, True
# Outside the block above on purpose. Resolving a destination reads the database, and a
# failure there is not this check's failure.
decided.append(
- _delivery(check, outcome, window_end=date_to, now=now, value=value, query_duration_ms=duration_ms)
+ _delivery(
+ check,
+ outcome,
+ window_end=date_to,
+ now=now,
+ value=value,
+ query_duration_ms=duration_ms,
+ failed=failed,
+ )
)
return decided
@@ -637,22 +681,234 @@ def _as_configured_now(
def _stopped(check: PlatformAlertCheckInput, *, now: datetime) -> Decision:
"""A check whose logs alert no longer runs. It leaves the state alone and disables the copy."""
state = check.instance().state
- unchanged = ControlPlaneOutcome(new_state=AlertState(state), consecutive_failures=check.consecutive_failures)
- recorded = _recorded(
- check,
- outcome=unchanged,
- evaluation_key=_evaluation_key(check, now),
- kind=AlertEventKind.CHECK,
- notified=False,
- now=now,
- disable=True,
- )
+ if check.grouping.mode == GroupingMode.SINGLE:
+ unchanged = ControlPlaneOutcome(new_state=AlertState(state), consecutive_failures=check.consecutive_failures)
+ recorded = _recorded(
+ check,
+ outcome=unchanged,
+ evaluation_key=_evaluation_key(check, now),
+ kind=AlertEventKind.CHECK,
+ notified=False,
+ now=now,
+ disable=True,
+ )
+ else:
+ # No group was checked, so each instance keeps its state and no row is created.
+ recorded = PlatformAlertOutcome(
+ configuration_id=check.id,
+ evaluation_key=_evaluation_key(check, now),
+ consecutive_failures=check.consecutive_failures,
+ disable=True,
+ )
_record_check_metrics(
check, new_state=state, notification=NotificationAction.NONE, skip=SkipReason.SOURCE_RULE, now=now
)
return recorded, None
+# A grouping key is a stored column of at most 255 characters, so a longer label set is hashed.
+_MAX_GROUPING_KEY_LENGTH: Final = 255
+
+
+def grouping_key_of(labels: dict[str, str]) -> str:
+ """The instance key for one group's label values. Stable across checks, so a group keeps its row."""
+ key = json.dumps(labels, sort_keys=True, separators=(",", ":"))
+ if len(key) <= _MAX_GROUPING_KEY_LENGTH:
+ return key
+ return f"sha256:{hashlib.sha256(key.encode()).hexdigest()}"
+
+
+def _labels_of(grouping_key: str) -> dict[str, str] | None:
+ """The labels `grouping_key_of` encoded, or None for a hashed key, which keeps no labels."""
+ if grouping_key.startswith("sha256:"):
+ return None
+ try:
+ labels = json.loads(grouping_key)
+ except ValueError:
+ return None
+ return labels if isinstance(labels, dict) else 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))}"
+ # 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:
+ return "A grouped logs alert can only alert above a threshold"
+ return None
+
+
+@frozen
+class _GroupVerdict:
+ grouping_key: str
+ labels: dict[str, str]
+ outcome: AlertCheckOutcome
+ value: float
+
+
+def _evaluate_grouped(
+ team: Team,
+ check: PlatformAlertCheckInput,
+ *,
+ checkpoint: datetime | None,
+ now: datetime,
+ query_seconds: int,
+ muted: bool,
+) -> Decision:
+ """One grouped alert: its own query, then the shared machine once per group.
+
+ A group with no instance whose check decides nothing is left out, so a quiet group costs no
+ row. An open group the query did not return had no matching log, so it is checked against a
+ zero count and can resolve.
+ """
+ condition = LogsAlertCondition.of(check)
+ date_to = resolve_alert_date_to(check.next_check_at or now, checkpoint)
+ lookback = rolling_check_lookback_minutes(
+ condition.window_minutes, check.check_interval_minutes, check.evaluation_periods
+ )
+ open_keys = [instance.grouping_key for instance in check.instances if instance.state != AlertState.NOT_FIRING.value]
+ try:
+ result = GroupedAlertCheckQuery(
+ team=team,
+ alert=check,
+ date_from=date_to - timedelta(minutes=lookback),
+ date_to=date_to,
+ 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=len(open_keys) + check.grouping.max_instances,
+ max_execution_time=query_seconds,
+ ch_user=ClickHouseUser.ALERTS_PLATFORM_LOGS,
+ ).execute_rolling_checks(
+ date_to, condition.window_minutes, check.check_interval_minutes, check.evaluation_periods
+ )
+ except Exception as error:
+ logger.exception("Grouped logs alert query failed", check_id=str(check.id), error=str(error))
+ 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}
+ existing = {instance.grouping_key for instance in check.instances}
+ verdicts: list[_GroupVerdict] = []
+ # 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) >= len(open_keys) + check.grouping.max_instances
+ absent = [key for key in open_keys if key not in counts and not (truncated and _labels_of(key) is None)]
+ for key in [*counts, *absent]:
+ group = counts.get(key)
+ buckets = group.counts if group is not None else result.zero_counts()
+ current_breached, *prior_windows_breached = _derive_breaches(
+ buckets, condition.threshold_count, condition.threshold_operator, check.evaluation_periods
+ ) or (False,)
+ # The machine alone, without `_verdict`'s metrics, so a quiet group left out below counts nothing.
+ outcome = evaluate_alert_check(
+ _snapshot(check, tuple(prior_windows_breached), key),
+ CheckInput(threshold_breached=current_breached, muted=muted),
+ now,
+ policy=PLATFORM_LOGS_ALERT_POLICY,
+ )
+ decided_nothing = (
+ outcome.new_state == AlertState.NOT_FIRING
+ and outcome.notification == NotificationAction.NONE
+ and outcome.muted_notification == NotificationAction.NONE
+ )
+ if decided_nothing and key not in existing:
+ continue
+ _record_check_metrics(
+ check,
+ new_state=outcome.new_state.value,
+ notification=outcome.notification,
+ muted_notification=outcome.muted_notification,
+ muted_by_quiet_hours=muted,
+ now=now,
+ grouping_key=key,
+ )
+ verdicts.append(
+ _GroupVerdict(
+ grouping_key=key,
+ labels=group.labels if group is not None else (_labels_of(key) or {}),
+ outcome=outcome,
+ value=float(buckets[-1].count) if buckets else 0.0,
+ )
+ )
+
+ # Firing verdicts first, so a cap keeps the groups that announce something.
+ verdicts.sort(key=lambda verdict: verdict.outcome.new_state == AlertState.NOT_FIRING)
+ admission = check.admit([verdict.grouping_key for verdict in verdicts])
+ admitted = [verdict for verdict in verdicts if verdict.grouping_key in set(admission.admitted)]
+ recorded = PlatformAlertOutcome(
+ configuration_id=check.id,
+ evaluation_key=_evaluation_key(check, date_to),
+ consecutive_failures=0,
+ groups=tuple(
+ GroupOutcome(
+ grouping_key=verdict.grouping_key,
+ kind=NOTIFICATION_EVENT_KINDS[verdict.outcome.notification],
+ new_state=verdict.outcome.new_state.value,
+ notified=verdict.outcome.update_last_notified_at,
+ firing_episode=decide_firing_episode(
+ _snapshot(check, (), verdict.grouping_key),
+ verdict.outcome,
+ now,
+ policy=PLATFORM_LOGS_ALERT_POLICY,
+ ),
+ value=verdict.value,
+ labels=verdict.labels,
+ muted_notification=(
+ ""
+ if verdict.outcome.muted_notification == NotificationAction.NONE
+ else verdict.outcome.muted_notification.value
+ ),
+ )
+ for verdict in admitted
+ ),
+ query_duration_ms=result.query_duration_ms,
+ )
+ return recorded, _grouped_request(check, recorded, admitted, overflowed=admission.overflowed)
+
+
+def _grouped_request(
+ check: PlatformAlertCheckInput,
+ recorded: PlatformAlertOutcome,
+ admitted: Sequence[_GroupVerdict],
+ *,
+ overflowed: int,
+) -> AlertDeliveryRequest | None:
+ destination_alert_id = str(check.legacy_configuration_id or check.id)
+ actions = {
+ verdict.grouping_key: action
+ for verdict in admitted
+ if (
+ action := decide_incident_action(
+ AlertState(check.instance(verdict.grouping_key).state),
+ verdict.outcome.new_state,
+ policy=PLATFORM_LOGS_ALERT_POLICY,
+ )
+ )
+ is not None
+ }
+ if actions and not _has_incident_destination(check.team_id, destination_alert_id):
+ actions = {}
+ sends_messages = any(verdict.outcome.notification != NotificationAction.NONE for verdict in admitted)
+ if not sends_messages and not actions:
+ return None
+ return AlertDeliveryRequest(
+ source=SourceKind.LOGS,
+ team_id=check.team_id,
+ configuration_id=str(check.id),
+ evaluation_key=recorded.evaluation_key,
+ destination_alert_id=destination_alert_id,
+ event_ids_by_kind=_EVENT_IDS_BY_KIND,
+ event_ids_by_incident_action=_EVENT_IDS_BY_INCIDENT_ACTION,
+ incident_actions=actions,
+ sends_messages=sends_messages,
+ overflowed=overflowed,
+ )
+
+
def _triage(checks: Sequence[PlatformAlertCheckInput], *, now: datetime, tz_name: str) -> _Triage:
"""Splits a batch into the checks a query can answer, the ones already decided, and the muted.
@@ -666,7 +922,9 @@ def _triage(checks: Sequence[PlatformAlertCheckInput], *, now: datetime, tz_name
evaluable: list[PlatformAlertCheckInput] = []
muted_ids: set[UUID] = set()
for check in checks:
- broken_reason = _detect_broken_filter_config(check.source_config) or _broken_condition(check)
+ broken_reason = (
+ _detect_broken_filter_config(check.source_config) or _broken_condition(check) or _broken_grouping(check)
+ )
if broken_reason is not None:
logger.warning(
"Marking a logs alert BROKEN for an invalid filter config",
@@ -776,7 +1034,11 @@ def _evaluate_admitted(
checkpoint = None
cohorts: dict[tuple, list[PlatformAlertCheckInput]] = {}
+ grouped: list[PlatformAlertCheckInput] = []
for check in triage.evaluable:
+ if check.grouping.mode != GroupingMode.SINGLE:
+ grouped.append(check)
+ continue
cohorts.setdefault(_cohort_key(check, checkpoint, cutoff), []).append(check)
if len(cohorts) > MAX_COHORTS_PER_CYCLE:
@@ -807,6 +1069,21 @@ def _evaluate_admitted(
team, chunk, cohort_key, now=cutoff, query_seconds=query_seconds, muted_ids=triage.muted_ids
)
)
+ for check in grouped:
+ query_seconds = min(MAX_QUERY_SECONDS, int(deadline - time.monotonic()))
+ if query_seconds < MIN_QUERY_SECONDS:
+ unqueried += 1
+ continue
+ decided.append(
+ _evaluate_grouped(
+ team,
+ check,
+ checkpoint=checkpoint,
+ now=cutoff,
+ query_seconds=query_seconds,
+ muted=check.id in triage.muted_ids,
+ )
+ )
if unqueried:
logger.warning(
diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.py
index f0bfcc2c5d14..771ccc68ae03 100644
--- a/products/logs/backend/temporal/alert_evaluate.py
+++ b/products/logs/backend/temporal/alert_evaluate.py
@@ -88,19 +88,26 @@ def platform_signals(evaluation: SourceBatchEvaluation) -> list[PlatformAlertSig
for delivery in evaluation.deliveries
if delivery.owned_by_platform and delivery.sends_messages
}
- return [
- PlatformAlertSignal(
- alert_id=announced[str(outcome.configuration_id)],
- action=_SIGNAL_ACTIONS[group.kind],
- result_count=int(group.value) if group.value is not None else None,
- consecutive_failures=outcome.consecutive_failures,
- evaluation_key=outcome.evaluation_key,
+ signals: list[PlatformAlertSignal] = []
+ for outcome in evaluation.outcomes:
+ if str(outcome.configuration_id) not in announced:
+ 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,
+ )
+ for kind, value in verdicts
+ if kind in _SIGNAL_ACTIONS
)
- for outcome in evaluation.outcomes
- if str(outcome.configuration_id) in announced
- for group in outcome.groups
- if group.kind in _SIGNAL_ACTIONS
- ]
+ return signals
@activity.defn
diff --git a/products/logs/backend/test/test_alert_check_query.py b/products/logs/backend/test/test_alert_check_query.py
index f42c095f3b86..27742c64a8ae 100644
--- a/products/logs/backend/test/test_alert_check_query.py
+++ b/products/logs/backend/test/test_alert_check_query.py
@@ -21,6 +21,7 @@ from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.printer import prepare_and_print_ast
from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import ClickHouseUser
from products.logs.backend.alert_check_query import (
CHECKPOINT_MAX_STALENESS,
@@ -29,6 +30,7 @@ from products.logs.backend.alert_check_query import (
BatchedAlertCheckQuery,
BatchedBucketedResult,
BucketedCount,
+ GroupedAlertCheckQuery,
_rolling_check_ranges,
fetch_live_logs_checkpoint,
is_projection_eligible,
@@ -1056,6 +1058,39 @@ class TestExecuteRollingChecksBatched(ClickhouseTestMixin, APIBaseTest):
).execute_rolling_checks(nca=nca, window_minutes=15, cadence_minutes=5, period_count=3)
assert batched.per_alert[str(alert.id)] == single
+ @time_machine.travel("2025-12-16T13:30:00Z", tick=False)
+ def test_each_group_counts_what_its_own_single_alert_query_counts(self):
+ base = datetime(2025, 12, 16, 12, 0, tzinfo=UTC)
+ self._seed(self.SERVICE_A, base, [3] * 60)
+ self._seed(self.SERVICE_B, base, [7] * 60)
+ both = self._make_alert(filters={"serviceNames": [self.SERVICE_A, self.SERVICE_B]})
+ nca = datetime(2025, 12, 16, 12, 30, tzinfo=UTC)
+ date_from = nca - dt.timedelta(minutes=15 + 2 * 5)
+
+ def grouped(open_groups: list[dict[str, str]], limit: int) -> list[str]:
+ result = GroupedAlertCheckQuery(
+ team=self.team,
+ alert=both,
+ date_from=date_from,
+ date_to=nca,
+ group_by=("service_name",),
+ open_groups=open_groups,
+ worst_is_highest=True,
+ limit=limit,
+ max_execution_time=30,
+ ch_user=ClickHouseUser.DEFAULT,
+ ).execute_rolling_checks(nca=nca, window_minutes=15, cadence_minutes=5, period_count=3)
+ for group in result.groups:
+ alone = self._make_alert(filters={"serviceNames": [group.labels["service_name"]]})
+ assert group.counts == AlertCheckQuery(
+ team=self.team, alert=alone, date_from=date_from, date_to=nca
+ ).execute_rolling_checks(nca=nca, window_minutes=15, cadence_minutes=5, period_count=3)
+ return [group.labels["service_name"] for group in result.groups]
+
+ 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]
+
@time_machine.travel("2025-12-16T13:30:00Z", tick=False)
def test_single_alert_cohort_matches_per_alert_path(self):
base = datetime(2025, 12, 16, 12, 0, tzinfo=UTC)
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 500b39e95705..9bf71bfdc4fa 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -22,6 +22,9 @@ from products.alerts_platform.backend.facade.api import due_checks, list_configu
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertEventKind,
+ CheckFailure,
+ Grouping,
+ GroupingMode,
GroupOutcome,
IncidentAction,
PlatformAlertOutcome,
@@ -32,13 +35,19 @@ from products.alerts_platform.backend.facade.contracts import (
from products.alerts_platform.backend.facade.lifecycle import AlertState
from products.alerts_platform.backend.facade.temporal import source_evaluation_timeout
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
-from products.logs.backend.alert_check_query import BatchedBucketedResult, BucketedCount
+from products.logs.backend.alert_check_query import (
+ BatchedBucketedResult,
+ BucketedCount,
+ GroupCounts,
+ GroupedRollingResult,
+)
from products.logs.backend.alert_signal_emitter import PlatformAlertSignal, notified_alerts_for_platform
from products.logs.backend.alert_source_cycle import (
BATCH_QUERY_BUDGET_SECONDS,
INFLIGHT_KEY,
MAX_QUERY_SECONDS,
evaluate_logs_batch,
+ grouping_key_of,
)
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
from products.logs.backend.platform_alert_backfill import backfill_platform_alert_configurations
@@ -326,16 +335,103 @@ class TestLogsAlertEvaluation(APIBaseTest):
(False, {"": IncidentAction.RESOLVE})
]
+ def _run_grouped(
+ self, configuration: PlatformConfigurationSnapshot, counts: dict[str, int], *, now: datetime | None = None
+ ) -> SourceBatchEvaluation:
+ now = now or self.cutoff
+ groups = [
+ GroupCounts(labels={"service_name": service}, counts=[BucketedCount(timestamp=now, count=count)])
+ for service, count in counts.items()
+ ]
+ with (
+ 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
+ )
+ return evaluate_logs_batch(self.team.id, slot_of(configuration.next_check_at, now), now)
+
+ def test_an_open_group_with_a_hashed_key_resolves_only_when_the_query_was_not_cut(self) -> None:
+ grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service_name",), max_instances=1)
+ configuration = self._configuration(grouping=grouping.to_stored())
+ long_name = "checkout-" * 40
+ self._record(self._run_grouped(configuration, {long_name: 500}))
+
+ def run_after(counts: dict[str, int]) -> dict[str, AlertEventKind]:
+ with team_scope(self.team.id):
+ platform_testing.set_due_at(configuration.id, self.cutoff - timedelta(minutes=1))
+ (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}) == {"sha256:": AlertEventKind.RESOLVED}
+
+ def test_a_grouped_alert_fires_per_group_resolves_a_vanished_one_and_reports_overflow(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})
+ 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.
+ assert [(group.labels["service_name"], group.kind) for group in outcome.groups] == [
+ ("api", AlertEventKind.FIRING),
+ ("worker", AlertEventKind.FIRING),
+ ]
+ assert delivery.overflowed == 1
+
+ with team_scope(self.team.id):
+ platform_testing.set_due_at(configuration.id, self.cutoff - timedelta(minutes=1))
+ second = self._run_grouped(configuration, {"api": 500})
+
+ (outcome,) = second.outcomes
+ assert {group.labels["service_name"]: group.kind for group in outcome.groups} == {
+ "api": AlertEventKind.CHECK,
+ "worker": AlertEventKind.RESOLVED,
+ }
+
+ def test_a_grouped_alert_switched_off_in_logs_keeps_its_open_groups(self) -> None:
+ grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service_name",))
+ configuration = self._configuration(grouping=grouping.to_stored())
+ self._record(self._run_grouped(configuration, {"api": 500}))
+ LogsAlertConfiguration.objects.filter(id=self._legacy_ids[configuration.id]).update(enabled=False)
+
+ with team_scope(self.team.id):
+ platform_testing.set_due_at(configuration.id, self.cutoff - timedelta(minutes=1))
+ stopped = self._run_grouped(configuration, {})
+ self._record(stopped)
+
+ (outcome,) = stopped.outcomes
+ with team_scope(self.team.id):
+ (copy,) = list_configurations(
+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], limit=10, offset=0
+ ).configurations
+ open_group = platform_testing.alert_for(
+ configuration.id, grouping_key=grouping_key_of({"service_name": "api"})
+ )
+ ungrouped = platform_testing.alert_for(configuration.id)
+ assert (outcome.groups, outcome.disable, copy.enabled) == ((), True, False)
+ assert open_group is not None and open_group.state == "firing"
+ assert ungrouped is None
+
@parameterized.expand(
[
("filter_group", {"condition": CONDITION, "filterGroup": {"type": "nonsense"}}),
("unknown_operator", {"condition": {**CONDITION, "threshold_operator": "equals"}}),
("zero_window", {"condition": {**CONDITION, "window_minutes": 0}}),
("null_filter_values", {"condition": CONDITION, "filterGroup": {"type": "AND", "values": None}}),
+ ("grouped_by_an_attribute", {"condition": CONDITION}, ("http.route",)),
+ ("grouped_below", {"condition": {**CONDITION, "threshold_operator": "below"}}, ("service_name",)),
]
)
- def test_a_broken_config_stops_being_discovered(self, _name: str, source_config: dict[str, Any]) -> None:
- configuration = self._configuration(source_config=source_config)
+ def test_a_broken_config_stops_being_discovered(
+ self, _name: str, source_config: dict[str, Any], grouping_keys: tuple[str, ...] = ()
+ ) -> None:
+ grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=grouping_keys) if grouping_keys else Grouping()
+ configuration = self._configuration(source_config=source_config, grouping=grouping.to_stored())
healthy = self._configuration(name="Healthy")
evaluation, query = self._run(configuration, healthy)
@@ -344,19 +440,17 @@ class TestLogsAlertEvaluation(APIBaseTest):
queried = {check.id for call in query.call_args_list for check in call.kwargs["alerts"]}
assert queried == {healthy.id}
with team_scope(self.team.id):
- alert = platform_testing.alert_for(configuration.id)
- assert alert is not None
- assert alert.state == AlertState.BROKEN
+ assert platform_testing.configuration(configuration.id).check_status == AlertState.BROKEN
assert due_checks(self.team.id, SourceKind.LOGS.value, self._slot(), self.cutoff + timedelta(hours=1)) == ()
@parameterized.expand(
[
- ("a_transient_error_holds_the_counter", ValueError("cluster busy"), 4, "not_firing"),
+ ("a_transient_error_holds_the_counter", ValueError("cluster busy"), 4, "ok"),
("an_invalid_query_escalates", ExposedHogQLError("unknown field"), 5, "broken"),
]
)
def test_a_failed_query_advances_the_schedule_instead_of_leaving_the_check_due(
- self, _name: str, error: Exception, expected_failures: int, expected_state: str
+ self, _name: str, error: Exception, expected_failures: int, expected_status: str
) -> None:
configuration = self._configuration(consecutive_failures=4)
@@ -365,10 +459,10 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert [o.consecutive_failures for o in evaluation.outcomes] == [expected_failures]
with team_scope(self.team.id):
- alert = platform_testing.alert_for(configuration.id)
- assert alert is not None
+ # A failed check fails every group, so it writes the configuration and no instance.
+ assert platform_testing.alert_for(configuration.id) is None
configuration = platform_testing.configuration(configuration.id)
- assert alert.state == expected_state
+ assert configuration.check_status == expected_status
assert configuration.next_check_at is not None
assert configuration.next_check_at > self.cutoff
@@ -450,7 +544,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
evaluation, _ = self._run(unreadable, healthy)
- states = {o.configuration_id: g.new_state for o in evaluation.outcomes for g in o.groups}
+ states = {o.configuration_id: (o.failure or o.groups[0]).new_state for o in evaluation.outcomes}
assert states == {unreadable.id: "broken", healthy.id: "firing"}
def test_a_check_whose_copy_cannot_be_updated_evaluates_the_stored_copy(self) -> None:
@@ -526,10 +620,18 @@ class TestEvaluationTimeoutLadder(SimpleTestCase):
def _outcome(kind: AlertEventKind, *, notified: bool = True) -> PlatformAlertOutcome:
+ # A broken check is a failure, which the platform reports on the outcome with no groups.
+ if kind == AlertEventKind.BROKEN:
+ return PlatformAlertOutcome(
+ configuration_id=UUID("01936a2e-0000-7000-8000-000000000001"),
+ evaluation_key="slot:x|window:y",
+ consecutive_failures=5,
+ failure=CheckFailure(kind=kind, new_state="broken", notified=notified),
+ )
return PlatformAlertOutcome(
configuration_id=UUID("01936a2e-0000-7000-8000-000000000001"),
evaluation_key="slot:x|window:y",
- consecutive_failures=5 if kind == AlertEventKind.BROKEN else 0,
+ consecutive_failures=0,
groups=(
GroupOutcome(
grouping_key="",