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.

refactor(alerts): report check verdicts per group and status per config (#114281)

Jimmy Zhu5dda29e8ed1d
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index afdbb50db1cf..f667465f1340 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -293,8 +293,11 @@ a real grouping key, and would bury them where Postgres cannot lift them into an
### What a check leaves behind
-Every check writes one row to `platform_alert_events` in ClickHouse, including a check that
-confirmed the alert.
+Every check writes one row to `platform_alert_events` in ClickHouse for each group its outcome
+reports, including a check that confirmed the alert.
+An outcome carries what describes the whole check (the evaluation key, the failure count, `disable`,
+the next due time) once, and a `GroupOutcome` per group for what describes one instance (its state,
+firing and value). A source that does not group reports one group with the empty key.
Postgres could not take that volume without a per-check retention flag, and a TTL'd ClickHouse
table needs no such flag, so nothing has to decide which checks are worth keeping.
diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.py
index 4e8002a4f130..0efc1e0c5a19 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,
+ GroupOutcome,
PlatformAlertCheckInput,
PlatformAlertOutcome,
SkipReason,
@@ -195,7 +196,7 @@ def evaluate_insight_check(
def _delivery(check: PlatformAlertCheckInput, outcome: PlatformAlertOutcome) -> AlertDeliveryRequest | None:
- if outcome.kind.value not in _EVENT_IDS_BY_KIND:
+ if not any(group.kind.value in _EVENT_IDS_BY_KIND for group in outcome.groups):
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:
@@ -390,12 +391,17 @@ def _recorded(
return PlatformAlertOutcome(
configuration_id=check.id,
evaluation_key=_evaluation_key(check, now),
- kind=NOTIFICATION_EVENT_KINDS[notification],
- new_state=outcome.new_state.value,
- notified=notified,
consecutive_failures=outcome.consecutive_failures,
- firing_episode=decide_firing_episode(snapshot, outcome, now, policy=INSIGHT_ALERT_POLICY),
- value=value,
+ groups=(
+ GroupOutcome(
+ grouping_key="",
+ kind=NOTIFICATION_EVENT_KINDS[notification],
+ new_state=outcome.new_state.value,
+ notified=notified,
+ firing_episode=decide_firing_episode(snapshot, outcome, now, policy=INSIGHT_ALERT_POLICY),
+ value=value,
+ ),
+ ),
error_message=error_message,
query_duration_ms=query_duration_ms,
disable=disable,
diff --git a/products/alerts/backend/test/test_platform_evaluate_workflow.py b/products/alerts/backend/test/test_platform_evaluate_workflow.py
index a71efccfca93..3efe25012b21 100644
--- a/products/alerts/backend/test/test_platform_evaluate_workflow.py
+++ b/products/alerts/backend/test/test_platform_evaluate_workflow.py
@@ -23,6 +23,7 @@ from products.alerts_platform.backend.facade.contracts import (
AlertBatchKey,
AlertDeliveryRequest,
AlertEventKind,
+ GroupOutcome,
PlatformAlertOutcome,
SourceBatchEvaluation,
SourceEvaluationInputs,
@@ -55,10 +56,8 @@ async def test_a_check_that_fails_does_not_stop_the_batch_recording_the_rest(env
outcome = PlatformAlertOutcome(
configuration_id=uuid.UUID(inputs.configuration_id),
evaluation_key="slot:2026-09-16T10:00:00+00:00",
- kind=AlertEventKind.FIRING,
- new_state="firing",
- notified=True,
consecutive_failures=0,
+ groups=(GroupOutcome(grouping_key="", kind=AlertEventKind.FIRING, new_state="firing", notified=True),),
)
delivery = AlertDeliveryRequest(
source=SourceKind.INSIGHT,
@@ -149,10 +148,8 @@ async def test_a_batch_refills_the_slots_its_finished_checks_free(
outcome = PlatformAlertOutcome(
configuration_id=uuid.UUID(inputs.configuration_id),
evaluation_key="slot:2026-09-16T10:00:00+00:00",
- kind=AlertEventKind.CHECK,
- new_state="not_firing",
- notified=False,
consecutive_failures=0,
+ groups=(GroupOutcome(grouping_key="", kind=AlertEventKind.CHECK, new_state="not_firing", notified=False),),
)
return SourceBatchEvaluation(outcomes=(outcome,), deliveries=())
diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.py
index 0886daf695ad..73639d0dc46a 100644
--- a/products/alerts/backend/test/test_platform_source_cycle.py
+++ b/products/alerts/backend/test/test_platform_source_cycle.py
@@ -94,7 +94,7 @@ class TestPlatformInsightEvaluation(APIBaseTest):
assert get_query_tags().ch_user == ClickHouseUser.ALERTS_PLATFORM_INSIGHT
record_outcomes(self.team.id, (outcome,), CUTOFF)
- assert (outcome.kind, outcome.value, outcome.evaluation_key) == (
+ assert (outcome.groups[0].kind, outcome.groups[0].value, outcome.evaluation_key) == (
AlertEventKind.FIRING,
150.0,
f"slot:{slot_of(configuration.next_check_at, CUTOFF)}",
@@ -158,7 +158,11 @@ class TestPlatformInsightEvaluation(APIBaseTest):
query.assert_not_called()
assert outcome is not None
- assert (outcome.kind, outcome.new_state, outcome.disable) == (AlertEventKind.CHECK, state, False)
+ assert (outcome.groups[0].kind, outcome.groups[0].new_state, outcome.disable) == (
+ AlertEventKind.CHECK,
+ state,
+ False,
+ )
def test_a_copy_whose_production_alert_is_gone_is_disabled(self) -> None:
outcome, query = self._evaluate(self._copy(None))
@@ -176,7 +180,7 @@ class TestPlatformInsightEvaluation(APIBaseTest):
outcome, _ = self._evaluate(self._copy(self._alert()), result=error)
assert outcome is not None
- assert (outcome.kind, outcome.new_state, outcome.error_message, outcome.disable) == (
+ assert (outcome.groups[0].kind, outcome.groups[0].new_state, outcome.error_message, outcome.disable) == (
AlertEventKind.CHECK,
"not_firing",
CAPACITY_REJECTED,
@@ -187,7 +191,11 @@ class TestPlatformInsightEvaluation(APIBaseTest):
outcome, _ = self._evaluate(self._copy(self._alert()), result=AlertExtractionError("bad query shape"))
assert outcome is not None
- assert (outcome.kind, outcome.new_state, outcome.disable) == (AlertEventKind.ERRORED, "errored", True)
+ assert (outcome.groups[0].kind, outcome.groups[0].new_state, outcome.disable) == (
+ AlertEventKind.ERRORED,
+ "errored",
+ True,
+ )
@override_settings(ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_EVALUATIONS=1)
def test_the_pool_defers_what_it_cannot_hold_until_a_check_frees_its_slot(self) -> None:
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 5289225be193..dc38945e0eef 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -235,27 +235,42 @@ class FiringEpisode:
ended: bool
+@frozen
+class GroupOutcome:
+ """What one check decided for one group. The platform turns each into an instance write and a
+ history row.
+
+ A source that does not group sends one of these with the empty key, which is its one instance.
+ """
+
+ grouping_key: str
+ kind: AlertEventKind
+ new_state: str
+ notified: bool
+ firing_episode: FiringEpisode | None = None
+ value: float | None = None
+ labels: dict[str, str] = field(default_factory=dict)
+ # What a mute held back, so history separates a muted fire from a check that said nothing.
+ muted_notification: str = ""
+
+
@frozen
class PlatformAlertOutcome:
"""What one check decided. The platform turns this into rows.
Every check produces one, including a check a source skipped. A skip that records nothing
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.
"""
configuration_id: UUID
evaluation_key: str
- kind: AlertEventKind
- new_state: str
- notified: bool
consecutive_failures: int
- firing_episode: FiringEpisode | None = None
- value: float | None = None
- labels: dict[str, str] = field(default_factory=dict)
+ groups: tuple[GroupOutcome, ...]
error_message: str | None = None
query_duration_ms: int | None = None
- # What a mute held back, so history separates a muted fire from a check that said nothing.
- muted_notification: str = ""
# Recording an outcome without it leaves a configuration discovery keeps handing back to an
# evaluation that cannot succeed.
disable: bool = False
@@ -263,6 +278,15 @@ class PlatformAlertOutcome:
# one query can do so. None spreads the configuration by its own id.
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")
+ keys = [group.grouping_key for group in self.groups]
+ if len(set(keys)) != len(keys):
+ raise ValueError("an outcome names each group once")
+
@frozen
class GroupTransition:
diff --git a/products/alerts_platform/backend/facade/enums.py b/products/alerts_platform/backend/facade/enums.py
index a133f704de9b..13e3ac23c85b 100644
--- a/products/alerts_platform/backend/facade/enums.py
+++ b/products/alerts_platform/backend/facade/enums.py
@@ -32,6 +32,15 @@ class PlatformAlertState(LabeledStrEnum):
BROKEN = "broken", "Broken"
+class PlatformAlertCheckStatus(LabeledStrEnum):
+ """Whether a configuration's checks succeed. It holds for every instance of the configuration,
+ because a failed check returns no group to attribute the failure to."""
+
+ OK = "ok", "OK"
+ ERRORED = "errored", "Errored"
+ BROKEN = "broken", "Broken"
+
+
class PlatformAlertConfigurationRecurrenceUnit(LabeledStrEnum):
"""The calendar unit a configuration recurs on, when it does not recur on a minute interval."""
diff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.py
index 3a17c2acf032..84a5208e2fcb 100644
--- a/products/alerts_platform/backend/facade/testing.py
+++ b/products/alerts_platform/backend/facade/testing.py
@@ -76,8 +76,12 @@ def start_firing(configuration_id: UUID, *, team_id: int, at: datetime) -> None:
def alert_for(configuration_id: UUID, *, grouping_key: str = "") -> PlatformAlertSnapshot | None:
"""The instance row a check wrote, or None when no check has written one."""
- row = PlatformAlert.objects.filter(configuration_id=configuration_id, grouping_key=grouping_key).first()
- return None if row is None else instance_view(row)
+ row = (
+ PlatformAlert.objects.select_related("configuration")
+ .filter(configuration_id=configuration_id, grouping_key=grouping_key)
+ .first()
+ )
+ return None if row is None else instance_view(row, row.configuration.check_status)
def undeclared_policy_divergences(correspondence: SourceCorrespondence) -> frozenset[str]:
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 76a4ca64b184..1fb83c6287b3 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -4,18 +4,20 @@ A source decides whether its data breached; everything about what that means for
and every write to these rows, stays here. A source never holds one of these models.
"""
-from collections.abc import Collection, Sequence
+from collections.abc import Collection, Mapping, Sequence
from datetime import datetime, timedelta
from typing import Final
from uuid import UUID
from django.db import connection, transaction
-from django.db.models import Exists, OuterRef, Q, QuerySet
+from django.db.models import Q, QuerySet
from django.utils import timezone as django_timezone
+from posthog.dataclasses import frozen
from posthog.models import Team
from products.alerts_platform.backend.facade.contracts import (
+ GroupOutcome,
PlatformAlertCheckInput,
PlatformAlertOutcome,
PlatformAlertUpsert,
@@ -53,46 +55,57 @@ def _existing_alerts(team_id: int, configurations: Sequence[PlatformAlertConfigu
}
-def _alerts_for_write(team_id: int, configurations: Sequence[PlatformAlertConfiguration]) -> dict[str, PlatformAlert]:
- """The runtime rows, creating any configuration that has none yet."""
- existing = _existing_alerts(team_id, configurations)
- missing = [c for c in configurations if str(c.id) not in existing]
+@frozen
+class _InstanceKey:
+ configuration_id: str
+ grouping_key: str
+
+
+def _instances(team_id: int, keys: Collection[_InstanceKey]) -> dict[_InstanceKey, PlatformAlert]:
+ rows = PlatformAlert.objects.for_team(team_id).filter(
+ configuration_id__in={key.configuration_id for key in keys},
+ grouping_key__in={key.grouping_key for key in keys},
+ )
+ found = {
+ _InstanceKey(configuration_id=str(row.configuration_id), grouping_key=row.grouping_key): row for row in rows
+ }
+ # The filter crosses every configuration with every key, so it can return pairs nobody asked for.
+ return {key: row for key, row in found.items() if key in keys}
+
+
+def _alerts_for_write(
+ team_id: int, wanted: Mapping[_InstanceKey, PlatformAlertConfiguration]
+) -> dict[_InstanceKey, PlatformAlert]:
+ """The runtime rows, creating any group that has none yet."""
+ existing = _instances(team_id, wanted.keys())
+ missing = [key for key in wanted if key not in existing]
if missing:
# ignore_conflicts leans on the unique constraint, so a concurrent cycle creating the
# same row is not an error. `for_team` because these models are fail-closed and a
# Temporal activity has no ambient scope; the rows still carry `team_id` themselves,
# because a queryset filter does not propagate into row creation.
PlatformAlert.objects.for_team(team_id).bulk_create(
- [PlatformAlert(team_id=team_id, configuration=c, grouping_key="") for c in missing],
+ [
+ PlatformAlert(team_id=team_id, configuration=wanted[key], grouping_key=key.grouping_key)
+ for key in missing
+ ],
ignore_conflicts=True,
)
- existing.update(_existing_alerts(team_id, missing))
+ existing.update(_instances(team_id, missing))
return existing
-def suppressed() -> Exists:
- """Configurations a runtime state holds back.
+def suppressed() -> Q:
+ """Configurations a check status holds back.
BROKEN only. A mute holds an announcement rather than a check, so a snoozed alert is
discovered and evaluated like any other and its state keeps tracking reality.
- The state lives on `PlatformAlert`, so discovery and the batch read both reach for this
- rather than each writing the predicate out. If the two disagreed, a broken alert would be
- dispatched by one and dropped by the other, every tick, in silence.
-
- Excluded as one `Exists` rather than as a lookup across the relation. Django splits an
- excluded multi-valued lookup into a subquery per leaf, which lets the conditions match
- different alert rows once a source writes a real grouping key, and buries them where
- Postgres cannot lift them into an anti-join.
+ Discovery and the batch read both reach for this rather than each writing the predicate out.
+ If the two disagreed, a broken alert would be dispatched by one and dropped by the other,
+ every tick, in silence.
"""
- # `unscoped` because the subquery runs without ambient scope in both callers, and it is
- # correlated to a configuration the outer query has already scoped, so the foreign key keeps
- # it inside that team.
- return Exists(
- PlatformAlert.objects.unscoped().filter(
- configuration=OuterRef("pk"), grouping_key="", state=PlatformAlert.State.BROKEN
- )
- )
+ return Q(check_status=PlatformAlertConfiguration.CheckStatus.BROKEN)
def _due(team_id: int, source_kind: str, cutoff: datetime) -> QuerySet[PlatformAlertConfiguration]:
@@ -163,7 +176,7 @@ def _check(c: PlatformAlertConfiguration, alert: PlatformAlert | None) -> Platfo
next_check_at=c.next_check_at,
consecutive_failures=c.consecutive_failures,
legacy_configuration_id=c.legacy_configuration_id,
- state=alert.state if alert else PlatformAlert.State.NOT_FIRING.value,
+ state=_check_state(c, alert),
last_notified_at=alert.last_notified_at if alert else None,
snooze_until=alert.snooze_until if alert else None,
firing_started_at=alert.firing_started_at if alert else None,
@@ -171,6 +184,14 @@ def _check(c: PlatformAlertConfiguration, alert: PlatformAlert | None) -> Platfo
)
+def _check_state(configuration: PlatformAlertConfiguration, alert: PlatformAlert | None) -> str:
+ """The state the shared machine expects. It reads ERRORED and BROKEN from the same field as
+ firing, so the configuration's status takes the place of the instance's while it is not OK."""
+ if configuration.check_status != PlatformAlertConfiguration.CheckStatus.OK:
+ return configuration.check_status
+ return alert.state if alert else PlatformAlert.State.NOT_FIRING.value
+
+
def slot_of(next_check_at: datetime | None, cutoff: datetime) -> str:
"""The minute a configuration is due for. One that has never been checked has no due time
of its own, so it belongs to the tick that found it.
@@ -209,6 +230,7 @@ def _event_row(
configuration: PlatformAlertConfiguration,
alert: PlatformAlert,
outcome: PlatformAlertOutcome,
+ group: GroupOutcome,
previous_state: str,
now: datetime,
) -> PlatformAlertEventRow:
@@ -219,21 +241,21 @@ def _event_row(
alert_id=alert.id,
grouping_key=alert.grouping_key,
evaluation_key=outcome.evaluation_key,
- kind=outcome.kind.value,
+ kind=group.kind.value,
alert_name=configuration.name,
previous_state=previous_state,
- state=outcome.new_state,
+ state=group.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=outcome.firing_episode.started_at if outcome.firing_episode else None,
- value=outcome.value,
- labels=outcome.labels,
+ episode_started_at=group.firing_episode.started_at if group.firing_episode else None,
+ value=group.value,
+ labels=group.labels,
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=outcome.muted_notification,
+ muted_notification=group.muted_notification,
occurred_at=now,
)
@@ -253,6 +275,20 @@ def _shard_offset_seconds(configuration: PlatformAlertConfiguration, outcome: Pl
)
+_CHECK_STATUSES: Final = frozenset(
+ {PlatformAlertConfiguration.CheckStatus.ERRORED.value, PlatformAlertConfiguration.CheckStatus.BROKEN.value}
+)
+
+
+def _check_status(outcome: PlatformAlertOutcome) -> str:
+ """BROKEN over ERRORED over OK, because a check is as bad as its worst verdict."""
+ states = {group.new_state for group in outcome.groups}
+ for status in (PlatformAlertConfiguration.CheckStatus.BROKEN, PlatformAlertConfiguration.CheckStatus.ERRORED):
+ if status.value in states:
+ return status.value
+ return PlatformAlertConfiguration.CheckStatus.OK.value
+
+
def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now: datetime) -> int:
"""Persists a batch's decisions and advances each configuration's schedule.
@@ -288,7 +324,14 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
)
if not configurations:
return 0
- alerts = _alerts_for_write(team_id, configurations)
+ alerts = _alerts_for_write(
+ team_id,
+ {
+ _InstanceKey(configuration_id=str(configuration.id), grouping_key=group.grouping_key): configuration
+ for configuration in configurations
+ for group in by_id[str(configuration.id)].groups
+ },
+ )
# 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"
@@ -296,17 +339,21 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
rows: list[PlatformAlertEventRow] = []
for configuration in configurations:
outcome = by_id[str(configuration.id)]
- alert = alerts[str(configuration.id)]
- # Before the row is mutated, so the history row keeps the state the check found.
- rows.append(_event_row(configuration, alert, outcome, alert.state, now))
- episode = outcome.firing_episode
- # The row holds the firing the alert is in, so a check that ended one clears it. The
- # ended firing stays on the history row instead.
- alert.firing_started_at = episode.started_at if episode and not episode.ended else None
- alert.state = outcome.new_state
- if outcome.notified:
- alert.last_notified_at = now
-
+ for group in outcome.groups:
+ alert = alerts[_InstanceKey(configuration_id=str(configuration.id), grouping_key=group.grouping_key)]
+ # 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))
+ if group.notified:
+ alert.last_notified_at = now
+ if group.new_state in _CHECK_STATUSES:
+ continue
+ episode = group.firing_episode
+ # The row holds the firing the alert is in, so a check that ended one clears it. The
+ # ended firing stays on the history row instead.
+ 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)
configuration.consecutive_failures = outcome.consecutive_failures
if outcome.disable:
configuration.enabled = False
@@ -325,7 +372,7 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
list(alerts.values()), ["state", "last_notified_at", "firing_started_at"]
)
PlatformAlertConfiguration.objects.for_team(team_id).bulk_update(
- configurations, ["consecutive_failures", "enabled", "next_check_at"]
+ configurations, ["check_status", "consecutive_failures", "enabled", "next_check_at"]
)
# `on_commit` rather than a statement after the block, so a caller that wraps this in its
# own `atomic()` cannot leave history for state its rollback removed.
@@ -398,6 +445,7 @@ def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -
revived = existing is not None and upsert.enabled and (revive or not existing["enabled"])
if revived:
defaults["consecutive_failures"] = 0
+ defaults["check_status"] = PlatformAlertConfiguration.CheckStatus.OK
# After any check already running, so an outcome it read before the source came back
# on, such as a stop, finds the row no longer due and records nothing.
defaults["next_check_at"] = max(
@@ -406,7 +454,8 @@ def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -
configuration, created = PlatformAlertConfiguration.objects.unscoped().update_or_create(
legacy_configuration_id=upsert.legacy_configuration_id, defaults=defaults
)
- alert = _alerts_for_write(upsert.team_id, [configuration])[str(configuration.id)]
+ key = _InstanceKey(configuration_id=str(configuration.id), grouping_key="")
+ alert = _alerts_for_write(upsert.team_id, {key: configuration})[key]
# Otherwise state is left alone, because a muted alert keeps tracking reality.
alert.snooze_until = upsert.snooze_until
update_fields = ["snooze_until"]
@@ -495,18 +544,26 @@ def take_ownership(handover: PlatformOwnershipHandover) -> bool:
.select_for_update()
.get(legacy_configuration_id=handover.legacy_configuration_id)
)
- alert = _alerts_for_write(handover.team_id, [configuration])[str(configuration.id)]
+ key = _InstanceKey(configuration_id=str(configuration.id), grouping_key="")
+ alert = _alerts_for_write(handover.team_id, {key: configuration})[key]
if alert.state == PlatformAlertState.FIRING or alert.firing_started_at is not None:
return False
+ # ERRORED and BROKEN are the configuration's check status, so the instance starts at rest.
+ failing = handover.state in (PlatformAlertState.ERRORED, PlatformAlertState.BROKEN)
+ configuration.check_status = (
+ handover.state.value if failing else PlatformAlertConfiguration.CheckStatus.OK.value
+ )
configuration.owner = PlatformAlertOwner.PLATFORM
configuration.owner_changed_at = handover.at
configuration.consecutive_failures = handover.consecutive_failures
# A platform check that started before the handover records only rows still due, so a
# schedule after the handover keeps it from recording over the carried state.
configuration.next_check_at = max(handover.next_check_at, handover.at + _HANDOVER_FENCE)
- configuration.save(update_fields=["owner", "owner_changed_at", "consecutive_failures", "next_check_at"])
+ configuration.save(
+ update_fields=["owner", "owner_changed_at", "consecutive_failures", "next_check_at", "check_status"]
+ )
- alert.state = handover.state
+ alert.state = PlatformAlertState.NOT_FIRING if failing else handover.state
alert.last_notified_at = handover.last_notified_at
alert.save(update_fields=["state", "last_notified_at"])
return True
diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.py
index 136f4ac39345..4f93bda089d1 100644
--- a/products/alerts_platform/backend/logic/platform_reads.py
+++ b/products/alerts_platform/backend/logic/platform_reads.py
@@ -17,12 +17,16 @@ from products.alerts_platform.backend.facade.contracts import (
from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
-def instance_view(alert: PlatformAlert) -> PlatformAlertSnapshot:
- """One instance row as a contract. Shared with the test doors, so both describe one shape."""
+def instance_view(alert: PlatformAlert, check_status: str) -> PlatformAlertSnapshot:
+ """One instance row as a contract. Shared with the test doors, so both describe one shape.
+
+ A configuration whose checks fail shows that status on every instance, because nothing says
+ which group caused the failure. The row keeps its own state so a recovery continues its firing.
+ """
return PlatformAlertSnapshot(
id=alert.id,
grouping_key=alert.grouping_key,
- state=alert.state,
+ state=alert.state if check_status == PlatformAlertConfiguration.CheckStatus.OK else check_status,
firing_started_at=alert.firing_started_at,
last_notified_at=alert.last_notified_at,
snooze_until=alert.snooze_until,
@@ -48,7 +52,7 @@ def _configuration_view(configuration: PlatformAlertConfiguration) -> PlatformAl
legacy_configuration_id=configuration.legacy_configuration_id,
created_at=configuration.created_at,
updated_at=configuration.updated_at,
- alerts=tuple(instance_view(alert) for alert in configuration.alerts.all()),
+ alerts=tuple(instance_view(alert, configuration.check_status) for alert in configuration.alerts.all()),
)
@@ -95,7 +99,8 @@ def alert_snapshot(team_id: int, configuration_id: str, grouping_key: str) -> Pl
"""One group's current runtime state, or None when the platform has recorded none."""
alert = (
PlatformAlert.objects.for_team(team_id)
+ .select_related("configuration")
.filter(configuration_id=configuration_id, grouping_key=grouping_key)
.first()
)
- return instance_view(alert) if alert is not None else None
+ return instance_view(alert, alert.configuration.check_status) if alert is not None else None
diff --git a/products/alerts_platform/backend/migrations/0010_platformalertconfiguration_check_status.py b/products/alerts_platform/backend/migrations/0010_platformalertconfiguration_check_status.py
new file mode 100644
index 000000000000..44dd3600ed8e
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0010_platformalertconfiguration_check_status.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.18 on 2026-10-08 00:39
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0009_platformalertconfiguration_switched_off_at"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="platformalertconfiguration",
+ name="check_status",
+ field=models.CharField(
+ choices=[("ok", "OK"), ("errored", "Errored"), ("broken", "Broken")],
+ db_default="ok",
+ default="ok",
+ max_length=16,
+ ),
+ ),
+ ]
diff --git a/products/alerts_platform/backend/migrations/0011_move_check_status_onto_configuration.py b/products/alerts_platform/backend/migrations/0011_move_check_status_onto_configuration.py
new file mode 100644
index 000000000000..441adaa6f033
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0011_move_check_status_onto_configuration.py
@@ -0,0 +1,32 @@
+from django.db import migrations
+
+# Every instance written so far has the empty grouping key, so its ERRORED or BROKEN is the whole
+# configuration's. Both statements match nothing on a second run, which makes a retry a no-op.
+COPY_STATUS_ONTO_CONFIGURATION = """
+-- migration-analyzer: safe reason=holds only the copies the logs and insight backfills made, and nothing reads it on a request path
+UPDATE alerts_platformalertconfiguration AS configuration
+SET check_status = alert.state
+FROM alerts_platformalert AS alert
+WHERE alert.configuration_id = configuration.id
+ AND alert.grouping_key = ''
+ AND alert.state IN ('errored', 'broken')
+"""
+
+# The machine already ended the firing when it wrote ERRORED or BROKEN, so the instance is not firing.
+CLEAR_STATUS_FROM_INSTANCES = """
+-- migration-analyzer: safe reason=holds only the copies the logs and insight backfills made, and nothing reads it on a request path
+UPDATE alerts_platformalert
+SET state = 'not_firing', firing_started_at = NULL
+WHERE state IN ('errored', 'broken')
+"""
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0010_platformalertconfiguration_check_status"),
+ ]
+
+ operations = [
+ migrations.RunSQL(COPY_STATUS_ONTO_CONFIGURATION, reverse_sql=migrations.RunSQL.noop),
+ migrations.RunSQL(CLEAR_STATUS_FROM_INSTANCES, reverse_sql=migrations.RunSQL.noop),
+ ]
diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txt
index 0265911b9bcb..bbd6a0ed2ad2 100644
--- a/products/alerts_platform/backend/migrations/max_migration.txt
+++ b/products/alerts_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0009_platformalertconfiguration_switched_off_at
+0011_move_check_status_onto_configuration
diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
index 209c22aaf009..819295c7999b 100644
--- a/products/alerts_platform/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -14,6 +14,7 @@ from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import UUIDModel
from products.alerts_platform.backend.facade.enums import (
+ PlatformAlertCheckStatus,
PlatformAlertConfigurationRecurrenceUnit,
PlatformAlertConfigurationSourceKind,
PlatformAlertOwner,
@@ -40,6 +41,7 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
SourceKind = PlatformAlertConfigurationSourceKind
RecurrenceUnit = PlatformAlertConfigurationRecurrenceUnit
Owner = PlatformAlertOwner
+ CheckStatus = PlatformAlertCheckStatus
# No database constraint: creating one takes a lock on `posthog_team` that queues behind
# live writes. Django still cascades in Python, which is the only path that deletes a team.
@@ -75,6 +77,9 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
next_check_at = models.DateTimeField(null=True, blank=True)
consecutive_failures = models.PositiveIntegerField(default=0, db_default=0)
+ check_status = models.CharField(
+ max_length=16, choices=CheckStatus.choices, default=CheckStatus.OK.value, db_default="ok"
+ )
# The row this was copied from, so a backfill can run twice and so a comparison can line
# an evaluation up against the one the source's own stack produced.
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index 4f377257d035..0fec46a50e5c 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -2,6 +2,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any
from uuid import UUID, uuid4
+import pytest
import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
@@ -10,16 +11,19 @@ from parameterized import parameterized
from posthog.clickhouse.client import sync_execute
from posthog.models.scoping import team_scope
+from products.alerts_platform.backend.facade import testing as platform_testing
from products.alerts_platform.backend.facade.api import (
disable_configurations,
due_checks,
record_outcomes,
+ slot_of,
take_ownership,
upsert_configuration,
)
from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
FiringEpisode,
+ GroupOutcome,
PlatformAlertOutcome,
PlatformAlertUpsert,
PlatformOwnershipHandover,
@@ -29,6 +33,8 @@ from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, Pl
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
+_GROUP_FIELDS = ("kind", "new_state", "notified", "firing_episode", "value", "labels", "muted_notification")
+
class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
def setUp(self) -> None:
@@ -52,24 +58,31 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
)
self.slot = (self.cutoff - timedelta(minutes=1)).isoformat()
- def _record(self, *, at: datetime | None = None, **overrides) -> None:
+ def _record(
+ self, *, at: datetime | None = None, groups: tuple[GroupOutcome, ...] | None = None, **overrides
+ ) -> None:
at = at or self.cutoff
- fields = {
- "configuration_id": self.configuration.id,
- "evaluation_key": f"window:{at.isoformat()}",
+ group_fields: dict[str, Any] = {
+ "grouping_key": "",
"kind": AlertEventKind.FIRING,
"new_state": "firing",
"notified": True,
+ }
+ group_fields.update({name: overrides.pop(name) for name in _GROUP_FIELDS if name in overrides})
+ fields: dict[str, Any] = {
+ "configuration_id": self.configuration.id,
+ "evaluation_key": f"window:{at.isoformat()}",
"consecutive_failures": 0,
+ "groups": groups or (GroupOutcome(**group_fields),),
}
fields.update(overrides)
# History rides `transaction.on_commit`, which a `TestCase` transaction never reaches.
with self.captureOnCommitCallbacks(execute=True):
record_outcomes(self.team.id, [PlatformAlertOutcome(**fields)], at)
- def _alert(self) -> PlatformAlert:
+ def _alert(self, grouping_key: str = "") -> PlatformAlert:
with team_scope(self.team.id):
- return PlatformAlert.objects.get(configuration=self.configuration)
+ return PlatformAlert.objects.get(configuration=self.configuration, grouping_key=grouping_key)
def test_the_row_holds_the_firing_the_alert_is_in_and_drops_the_one_that_ended(self) -> None:
# A field missing from the `bulk_update` list is never persisted and nothing else notices.
@@ -136,7 +149,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
with team_scope(self.team.id):
self.configuration.refresh_from_db()
- assert self.configuration.enabled is False
+ assert (self.configuration.enabled, self.configuration.check_status) == (False, "broken")
assert due_checks(self.team.id, SourceKind.LOGS.value, self.slot, self.cutoff + timedelta(hours=1)) == ()
def test_switching_a_source_off_leaves_the_alerts_the_platform_owns(self) -> None:
@@ -157,6 +170,38 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
owned.refresh_from_db()
assert (self.configuration.enabled, owned.enabled) == (False, True)
+ def _next_due(self) -> datetime:
+ with team_scope(self.team.id):
+ self.configuration.refresh_from_db()
+ assert self.configuration.next_check_at is not None
+ return self.configuration.next_check_at
+
+ 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))
+ self._record(
+ at=self._next_due(),
+ kind=AlertEventKind.ERRORED,
+ new_state="errored",
+ notified=False,
+ consecutive_failures=1,
+ firing_episode=FiringEpisode(started_at=self.cutoff, ended=True),
+ )
+
+ due = self._next_due()
+ stored = self._alert()
+ with team_scope(self.team.id):
+ shown = platform_testing.alert_for(self.configuration.id)
+ assert self.configuration.check_status == "errored"
+ assert (stored.state, stored.firing_started_at) == ("firing", self.cutoff)
+ assert shown is not None and shown.state == "errored"
+ (check,) = due_checks(self.team.id, SourceKind.LOGS.value, slot_of(due, due), due)
+ assert check.state == "errored"
+
+ self._record(at=due, kind=AlertEventKind.CHECK, new_state="not_firing", notified=False)
+
+ self._next_due()
+ assert (self.configuration.check_status, self._alert().state) == ("ok", "not_firing")
+
def test_recording_a_batch_twice_advances_the_schedule_once(self) -> None:
self._record()
with team_scope(self.team.id):
@@ -192,6 +237,31 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
# `insert_events` never raises, so without reading a row back a broken write is invisible.
assert rows == [("firing", "not_firing", "firing", 47.0, "API errors", "fire", 10, self.cutoff, "logs")]
+ def test_each_group_of_a_check_keeps_its_own_instance_and_history_row(self) -> None:
+ self._record(
+ groups=(
+ GroupOutcome(
+ grouping_key="api",
+ kind=AlertEventKind.FIRING,
+ new_state="firing",
+ notified=True,
+ firing_episode=FiringEpisode(started_at=self.cutoff, ended=False),
+ value=40.0,
+ ),
+ GroupOutcome(grouping_key="web", kind=AlertEventKind.CHECK, new_state="not_firing", notified=False),
+ )
+ )
+
+ api, web = self._alert("api"), self._alert("web")
+ assert (api.state, api.firing_started_at, api.last_notified_at) == ("firing", self.cutoff, self.cutoff)
+ assert (web.state, web.firing_started_at, web.last_notified_at) == ("not_firing", None, None)
+ rows = sync_execute(
+ "SELECT grouping_key, alert_id, state, value FROM platform_alert_events "
+ "WHERE team_id = %(team_id)s AND configuration_id = %(configuration_id)s ORDER BY grouping_key",
+ {"team_id": self.team.id, "configuration_id": self.configuration.id},
+ )
+ assert rows == [("api", api.id, "firing", 40.0), ("web", web.id, "not_firing", None)]
+
def test_a_resolve_row_keeps_the_firing_it_ended(self) -> None:
# The alert row clears the firing on a resolve, so history is the only place left holding
# the start a delivery needs to reply under the message that fired.
@@ -234,10 +304,8 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
PlatformAlertOutcome(
configuration_id=c.id,
evaluation_key=f"window:{self.cutoff.isoformat()}",
- kind=AlertEventKind.CHECK,
- new_state="not_firing",
- notified=False,
consecutive_failures=0,
+ groups=(_group(""),),
schedule_group=schedule_group,
)
for c in configurations
@@ -356,8 +424,10 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
self._copy(legacy_id)
with team_scope(self.team.id):
copied = PlatformAlertConfiguration.objects.get(legacy_configuration_id=legacy_id)
- PlatformAlertConfiguration.objects.filter(id=copied.id).update(consecutive_failures=5)
- PlatformAlert.objects.filter(configuration=copied).update(state="broken")
+ PlatformAlertConfiguration.objects.filter(id=copied.id).update(
+ consecutive_failures=5, check_status="broken"
+ )
+ PlatformAlert.objects.filter(configuration=copied).update(state="firing", firing_started_at=self.cutoff)
with time_machine.travel(self.cutoff, tick=False):
self._copy(legacy_id, revive=True)
@@ -369,11 +439,13 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
PlatformAlertOutcome(
configuration_id=copied.id,
evaluation_key="window:stale",
- kind=AlertEventKind.CHECK,
- new_state="broken",
- notified=False,
consecutive_failures=5,
disable=True,
+ groups=(
+ GroupOutcome(
+ grouping_key="", kind=AlertEventKind.CHECK, new_state="broken", notified=False
+ ),
+ ),
)
],
self.cutoff,
@@ -383,4 +455,32 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
with team_scope(self.team.id):
copied = PlatformAlertConfiguration.objects.get(id=copied.id)
alert = PlatformAlert.objects.get(configuration=copied)
- assert (copied.enabled, copied.consecutive_failures, alert.state) == (True, 0, "not_firing")
+ assert (copied.enabled, copied.consecutive_failures, copied.check_status, alert.state) == (
+ True,
+ 0,
+ "ok",
+ "not_firing",
+ )
+
+
+def _group(grouping_key: str) -> GroupOutcome:
+ return GroupOutcome(grouping_key=grouping_key, kind=AlertEventKind.CHECK, new_state="not_firing", notified=False)
+
+
+ "overrides",
+ [
+ {"groups": ()},
+ {"groups": (_group("api"), _group("api"))},
+ ],
+)
+def test_an_outcome_rejects_an_invalid_shape(overrides: dict[str, Any]) -> None:
+ fields: dict[str, Any] = {
+ "configuration_id": uuid4(),
+ "evaluation_key": "slot:2026-09-16T10:00:00+00:00",
+ "consecutive_failures": 0,
+ "groups": (_group(""),),
+ }
+ fields.update(overrides)
+ with pytest.raises(ValueError):
+ PlatformAlertOutcome(**fields)
diff --git a/products/alerts_platform/backend/tests/test_temporal_workflows.py b/products/alerts_platform/backend/tests/test_temporal_workflows.py
index e57b329b9dc4..a87865c2d6c0 100644
--- a/products/alerts_platform/backend/tests/test_temporal_workflows.py
+++ b/products/alerts_platform/backend/tests/test_temporal_workflows.py
@@ -486,12 +486,15 @@ async def test_probe_workflow_cancellation_does_not_start_delivery() -> None:
class TestDemandDiscovery(APIBaseTest):
- def _configuration(self, *, minutes_ago: int | None, enabled: bool = True, name: str = "alert"):
+ def _configuration(
+ self, *, minutes_ago: int | None, enabled: bool = True, name: str = "alert", check_status: str = "ok"
+ ):
with team_scope(self.team.id):
return PlatformAlertConfiguration.objects.create(
team=self.team,
name=name,
enabled=enabled,
+ check_status=check_status,
source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
source_config={},
check_interval_minutes=5,
@@ -505,14 +508,11 @@ class TestDemandDiscovery(APIBaseTest):
def _key(self, minutes_ago: int) -> AlertBatchKey:
return AlertBatchKey(team_id=self.team.id, slot=(self.tick - dt.timedelta(minutes=minutes_ago)).isoformat())
- def _alert(
- self, configuration, *, state: str, snooze_until: dt.datetime | None = None, grouping_key: str = ""
- ) -> None:
+ def _alert(self, configuration, *, state: str, snooze_until: dt.datetime | None = None) -> None:
with team_scope(self.team.id):
PlatformAlert.objects.create(
team=self.team,
configuration=configuration,
- grouping_key=grouping_key,
state=state,
snooze_until=snooze_until,
)
@@ -521,19 +521,15 @@ class TestDemandDiscovery(APIBaseTest):
self._configuration(minutes_ago=1, name="due")
self._configuration(minutes_ago=-1, name="not yet due")
self._configuration(minutes_ago=1, enabled=False, name="disabled")
- self._alert(self._configuration(minutes_ago=2, name="broken"), state=PlatformAlert.State.BROKEN)
+ self._configuration(minutes_ago=2, name="broken", check_status="broken")
# Excluding a muted alert here would stop its state tracking reality for the whole snooze.
self._alert(
self._configuration(minutes_ago=3, name="snoozed"),
state=PlatformAlert.State.NOT_FIRING,
snooze_until=self.tick + dt.timedelta(hours=1),
)
- # Two rows on one configuration, neither suppressing on its own. Written as a lookup across
- # the relation instead of one correlated subquery, the empty group and the broken state match
- # different rows and this configuration silently stops being checked.
- grouped = self._configuration(minutes_ago=4, name="broken in one group only")
- self._alert(grouped, state=PlatformAlert.State.NOT_FIRING)
- self._alert(grouped, state=PlatformAlert.State.BROKEN, grouping_key="/api/checkout")
+ # An errored check retries, so only BROKEN holds a configuration back.
+ self._configuration(minutes_ago=4, name="errored", check_status="errored")
discovered = demand.discover_demand(self.tick.isoformat())
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index f3d40e604944..2eb1b33fd4e5 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -37,6 +37,7 @@ from products.alerts_platform.backend.facade.api import due_checks, refresh_sett
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertEventKind,
+ GroupOutcome,
MuteReason,
PlatformAlertCheckInput,
PlatformAlertOutcome,
@@ -343,15 +344,22 @@ def _recorded(
return PlatformAlertOutcome(
configuration_id=check.id,
evaluation_key=evaluation_key,
- kind=kind,
- new_state=outcome.new_state.value,
- notified=notified,
consecutive_failures=outcome.consecutive_failures,
- firing_episode=decide_firing_episode(_snapshot(check, ()), outcome, now, policy=PLATFORM_LOGS_ALERT_POLICY),
- value=value,
+ groups=(
+ 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
+ ),
+ value=value,
+ muted_notification=muted_notification,
+ ),
+ ),
error_message=error_message,
query_duration_ms=query_duration_ms,
- muted_notification=muted_notification,
disable=disable,
# A broken alert is never discovered again, so its slot does not matter.
schedule_group=None if outcome.new_state == AlertState.BROKEN else _schedule_group(check),
diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.py
index 894f766f19d4..f0bfcc2c5d14 100644
--- a/products/logs/backend/temporal/alert_evaluate.py
+++ b/products/logs/backend/temporal/alert_evaluate.py
@@ -91,13 +91,15 @@ def platform_signals(evaluation: SourceBatchEvaluation) -> list[PlatformAlertSig
return [
PlatformAlertSignal(
alert_id=announced[str(outcome.configuration_id)],
- action=_SIGNAL_ACTIONS[outcome.kind],
- result_count=int(outcome.value) if outcome.value is not None else None,
+ 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,
)
for outcome in evaluation.outcomes
- if outcome.kind in _SIGNAL_ACTIONS and str(outcome.configuration_id) in announced
+ if str(outcome.configuration_id) in announced
+ for group in outcome.groups
+ if group.kind in _SIGNAL_ACTIONS
]
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 07684859d6b4..500b39e95705 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -22,6 +22,7 @@ from products.alerts_platform.backend.facade.api import due_checks, list_configu
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertEventKind,
+ GroupOutcome,
IncidentAction,
PlatformAlertOutcome,
PlatformConfigurationSnapshot,
@@ -161,7 +162,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
evaluation, _ = self._run(configuration)
self._record(evaluation)
- assert [(o.kind, o.value) for o in evaluation.outcomes] == [(AlertEventKind.FIRING, 500.0)]
+ assert [(g.kind, g.value) for o in evaluation.outcomes for g in o.groups] == [(AlertEventKind.FIRING, 500.0)]
assert [(d.sends_messages, d.incident_actions, d.owned_by_platform) for d in evaluation.deliveries] == [
(True, {"": IncidentAction.TRIGGER} if paged else {}, owner == "platform")
]
@@ -212,7 +213,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
evaluation, _ = self._run(copied)
- assert [(o.kind, o.value) for o in evaluation.outcomes] == [(AlertEventKind.FIRING, 500.0)]
+ assert [(g.kind, g.value) for o in evaluation.outcomes for g in o.groups] == [(AlertEventKind.FIRING, 500.0)]
def test_a_cohort_query_is_capped_below_the_batch_budget(self) -> None:
_, query = self._run(self._configuration())
@@ -307,7 +308,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
# firing reaching it, a FIRING alert does not fire again on its own and stays silent.
unmuted, _ = self._run(configuration, now=datetime(2026, 9, 16, 12, 30, tzinfo=UTC))
- assert [o.kind for o in unmuted.outcomes] == [AlertEventKind.FIRING]
+ assert [g.kind for o in unmuted.outcomes for g in o.groups] == [AlertEventKind.FIRING]
def test_a_resolve_cooldown_holds_still_closes_the_incident(self) -> None:
configuration = self._configuration(cooldown_minutes=60)
@@ -320,7 +321,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
later = datetime(2026, 9, 16, 10, 10, tzinfo=UTC)
cleared, _ = self._run(configuration, now=later, count=0)
- assert [o.kind for o in cleared.outcomes] == [AlertEventKind.CHECK]
+ assert [g.kind for o in cleared.outcomes for g in o.groups] == [AlertEventKind.CHECK]
assert [(d.sends_messages, d.incident_actions) for d in cleared.deliveries] == [
(False, {"": IncidentAction.RESOLVE})
]
@@ -406,7 +407,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
evaluation, query = self._run(configuration)
self._record(evaluation)
- assert [o.kind for o in evaluation.outcomes] == [AlertEventKind.CHECK]
+ assert [g.kind for o in evaluation.outcomes for g in o.groups] == [AlertEventKind.CHECK]
assert query.called is still_runs
with team_scope(self.team.id):
(copy,) = list_configurations(
@@ -449,7 +450,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
evaluation, _ = self._run(unreadable, healthy)
- states = {o.configuration_id: o.new_state for o in evaluation.outcomes}
+ states = {o.configuration_id: g.new_state for o in evaluation.outcomes for g in o.groups}
assert states == {unreadable.id: "broken", healthy.id: "firing"}
def test_a_check_whose_copy_cannot_be_updated_evaluates_the_stored_copy(self) -> None:
@@ -460,7 +461,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
with patch(f"{_MODULE}.refresh_settings", side_effect=RuntimeError("database blip")):
evaluation, _ = self._run(configuration)
- assert [o.new_state for o in evaluation.outcomes] == ["firing"]
+ assert [g.new_state for o in evaluation.outcomes for g in o.groups] == ["firing"]
def test_the_logs_product_rows_are_never_written(self) -> None:
legacy = LogsAlertConfiguration.objects.create(
@@ -528,11 +529,16 @@ def _outcome(kind: AlertEventKind, *, notified: bool = True) -> PlatformAlertOut
return PlatformAlertOutcome(
configuration_id=UUID("01936a2e-0000-7000-8000-000000000001"),
evaluation_key="slot:x|window:y",
- kind=kind,
- new_state="firing",
- notified=notified,
consecutive_failures=5 if kind == AlertEventKind.BROKEN else 0,
- value=500.0 if kind == AlertEventKind.FIRING else None,
+ groups=(
+ GroupOutcome(
+ grouping_key="",
+ kind=kind,
+ new_state="firing",
+ notified=notified,
+ value=500.0 if kind == AlertEventKind.FIRING else None,
+ ),
+ ),
)