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(alerts): let a platform alert configuration group its instances (#114282)

Jimmy Zhu2518d055dbdf
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index f667465f1340..c304b471f082 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -282,12 +282,25 @@ The failure case goes through `evaluate_alert_check` with an errored `CheckInput
transient. A transient error advances the schedule but holds the counter, because a cluster outage must not
disable every alert that ran during it.
-`suppressed` is the single definition of what holds a configuration back, and it is BROKEN alone.
+`suppressed` is the single definition of what holds a configuration back, and it is a BROKEN `check_status` alone.
Both `discover_demand` and `due_checks` exclude on it. Discovery has to, because a broken alert that still mints
a batch key spends the manifest bound on work its own evaluation then drops.
-It is one correlated `Exists` rather than a lookup across the relation: Django splits an excluded multi-valued
-lookup into a subquery per leaf, which would let the conditions match different alert rows once a source writes
-a real grouping key, and would bury them where Postgres cannot lift them into an anti-join.
+
+`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.
+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.
+
+A configuration's `snooze_until` mutes every instance, and an instance's own `snooze_until` mutes one group.
+The check input and the read API show each instance the later of the two.
+
+A configuration's `grouping` holds `max_instances` (100 by default), the most instance rows it keeps.
+A source calls `check.admit(keys)` with its groups in priority order: a group that already has an instance is always admitted, so it can resolve, and new groups fill the remaining room front first.
+The count it turned away travels on the delivery as `overflowed`, and the last message of that delivery says how many groups were not tracked.
+`record_outcomes` enforces the cap again and drops a group past it, counted on `alerts_platform_groups_over_cap_total`.
+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.
`alerts_platform_checks_skipped_total{source,reason}` counts these by reason.
diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.py
index 0efc1e0c5a19..0d2b94075edb 100644
--- a/products/alerts/backend/platform_source_cycle.py
+++ b/products/alerts/backend/platform_source_cycle.py
@@ -223,8 +223,11 @@ def _legacy_alert(check: PlatformAlertCheckInput) -> AlertConfiguration | None:
def _snapshot(check: PlatformAlertCheckInput) -> AlertSnapshot:
+ instance = check.instance()
return insight_snapshot(
- AlertState(check.state), last_notified_at=check.last_notified_at, firing_started_at=check.firing_started_at
+ AlertState(instance.state),
+ last_notified_at=instance.last_notified_at,
+ firing_started_at=instance.firing_started_at,
)
@@ -386,8 +389,9 @@ def _recorded(
safe_record(increment_checks, source, notification.value)
if skip is not None:
safe_record(increment_checks_skipped, source, skip.value)
- if check.state != outcome.new_state.value:
- safe_record(increment_state_transition, source, check.state, outcome.new_state.value)
+ previous_state = check.instance().state
+ if previous_state != outcome.new_state.value:
+ safe_record(increment_state_transition, source, previous_state, outcome.new_state.value)
return PlatformAlertOutcome(
configuration_id=check.id,
evaluation_key=_evaluation_key(check, now),
diff --git a/products/alerts_platform/backend/delivery/dispatch.py b/products/alerts_platform/backend/delivery/dispatch.py
index bfa07e0aa8c5..5fb51c7ab071 100644
--- a/products/alerts_platform/backend/delivery/dispatch.py
+++ b/products/alerts_platform/backend/delivery/dispatch.py
@@ -42,6 +42,15 @@ def deliver(
busy = 0
for transition in announcement.transitions:
+ is_last = transition is announcement.transitions[-1]
+ message = build_message(
+ announcement,
+ transition,
+ team_id=team_id,
+ incident_action=incident_action,
+ source_alert_url=source_alert_url,
+ overflowed=announcement.overflowed if is_last else 0,
+ )
key = _thread_key(
configuration_id=configuration_id,
provider=transport.provider,
@@ -54,13 +63,7 @@ def deliver(
team_id=team_id,
configuration_id=configuration_id,
target=target,
- message=build_message(
- announcement,
- transition,
- team_id=team_id,
- incident_action=incident_action,
- source_alert_url=source_alert_url,
- ),
+ message=message,
in_reply_to=None,
)
continue
@@ -82,13 +85,7 @@ def deliver(
team_id=team_id,
configuration_id=configuration_id,
target=target,
- message=build_message(
- announcement,
- transition,
- team_id=team_id,
- incident_action=incident_action,
- source_alert_url=source_alert_url,
- ),
+ message=message,
in_reply_to=claim.handle,
)
except Exception:
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.py
index b5137c060986..72db2ee5c913 100644
--- a/products/alerts_platform/backend/delivery/evaluation.py
+++ b/products/alerts_platform/backend/delivery/evaluation.py
@@ -214,7 +214,7 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
configuration_id=request.configuration_id,
evaluation_key=request.evaluation_key,
target=target,
- announcement=replace(announced, transitions=transitions),
+ announcement=replace(announced, transitions=transitions, overflowed=request.overflowed),
incident_action=action_by_event_id.get(event_id),
source_alert_url=request.source_alert_url,
)
diff --git a/products/alerts_platform/backend/delivery/message.py b/products/alerts_platform/backend/delivery/message.py
index 1ae5ce349079..412941f3744d 100644
--- a/products/alerts_platform/backend/delivery/message.py
+++ b/products/alerts_platform/backend/delivery/message.py
@@ -153,6 +153,7 @@ def build_message(
team_id: int,
incident_action: IncidentAction | None = None,
source_alert_url: str | None = None,
+ overflowed: int = 0,
) -> AlertMessage:
"""The message for one transition.
@@ -174,13 +175,20 @@ def build_message(
description = describe(announcement.source, project_id=project_id, transition=transition)
failure_kinds = (AlertEventKind.ERRORED, AlertEventKind.BROKEN)
if transition.kind in failure_kinds:
- details = _failure_details(transition, announcement.consecutive_failures)
+ details = list(_failure_details(transition, announcement.consecutive_failures))
else:
- details = description.details or _breach_details(transition)
+ details = list(description.details or _breach_details(transition))
+ if overflowed:
+ details.append(
+ MessageDetail(
+ label="Untracked groups",
+ value=f"{pluralize(overflowed, 'more group')} not tracked because this alert is at its group limit",
+ )
+ )
return AlertMessage(
headline=headline.format(kind=_SOURCE_LABELS[announcement.source], name=announcement.alert_name),
symbol=_SYMBOLS[kind],
- details=details,
+ details=tuple(details),
configuration_id=announcement.configuration_id,
alert_name=announcement.alert_name,
source=announcement.source,
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index dc38945e0eef..8d8e19dff06a 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -17,7 +17,7 @@ from uuid import UUID
from posthog.dataclasses import frozen
from posthog.enums import LabeledStrEnum
-from products.alerts_platform.backend.facade.enums import PlatformAlertState
+from products.alerts_platform.backend.facade.enums import PlatformAlertCheckStatus, PlatformAlertState
if TYPE_CHECKING:
# facade.lifecycle imports this module, so the policy type stays off the runtime import path.
@@ -103,12 +103,88 @@ def source_condition(source_config: dict[str, Any]) -> dict[str, Any]:
return condition if isinstance(condition, dict) else {}
+class GroupingMode(StrEnum):
+ SINGLE = "single"
+ BY_RESULT_LABELS = "by_result_labels"
+
+
+class OnOverflow(StrEnum):
+ # The only mode, because a cap that drops groups silently reads the same as nothing being wrong.
+ DEGRADE_VISIBLE = "degrade_visible"
+
+
+DEFAULT_MAX_INSTANCES: Final = 100
+
+
+@frozen
+class Grouping:
+ """How a configuration splits its results into instances.
+
+ `keys` names the result labels whose values make a group's key, so it is empty for a single
+ instance and required for grouping by labels. `max_instances` bounds how many instance rows a
+ configuration holds, which bounds the messages one check can post.
+ """
+
+ mode: GroupingMode = GroupingMode.SINGLE
+ keys: tuple[str, ...] = ()
+ max_instances: int = DEFAULT_MAX_INSTANCES
+ on_overflow: OnOverflow = OnOverflow.DEGRADE_VISIBLE
+
+ def __post_init__(self) -> None:
+ if self.mode == GroupingMode.SINGLE and self.keys:
+ raise ValueError("a single-instance grouping takes no keys")
+ if self.mode == GroupingMode.BY_RESULT_LABELS and not self.keys:
+ raise ValueError("grouping by result labels needs at least one key")
+ if len(set(self.keys)) != len(self.keys):
+ raise ValueError("a grouping names each key once")
+ if self.max_instances < 1:
+ raise ValueError("max_instances must be at least 1")
+
+ @classmethod
+ def from_stored(cls, stored: Mapping[str, Any]) -> Grouping:
+ return cls(
+ mode=GroupingMode(stored.get("mode", GroupingMode.SINGLE)),
+ keys=tuple(stored.get("keys", ())),
+ max_instances=int(stored.get("max_instances", DEFAULT_MAX_INSTANCES)),
+ on_overflow=OnOverflow(stored.get("on_overflow", OnOverflow.DEGRADE_VISIBLE)),
+ )
+
+ def to_stored(self) -> dict[str, Any]:
+ return {
+ "mode": self.mode.value,
+ "keys": list(self.keys),
+ "max_instances": self.max_instances,
+ "on_overflow": self.on_overflow.value,
+ }
+
+
+@frozen
+class GroupAdmission:
+ """Which of a check's groups the configuration has room for, and how many it turned away."""
+
+ admitted: tuple[str, ...]
+ overflowed: int
+
+
+@frozen
+class InstanceCheckState:
+ """One instance's runtime state, as the shared machine reads it for that group."""
+
+ grouping_key: str
+ state: str
+ last_notified_at: datetime | None = None
+ snooze_until: datetime | None = None
+ firing_started_at: datetime | None = None
+
+
@frozen
class PlatformAlertCheckInput:
"""One configuration and its runtime state, as a source adapter reads it.
- Flat rather than nested, because a source never holds the rows and has nothing to do with
- the split between what belongs to the configuration and what belongs to the instance.
+ `instances` holds every instance the configuration has, already composed with what belongs to
+ the configuration: a failing check status replaces each state, and a configuration mute
+ extends each snooze. A grouped source reads one per group it evaluates, and an open instance
+ whose key a successful check does not return has gone and resolves.
"""
id: UUID
@@ -123,11 +199,44 @@ class PlatformAlertCheckInput:
next_check_at: datetime | None
consecutive_failures: int
legacy_configuration_id: UUID | None
- state: str
- last_notified_at: datetime | None
+ check_status: str
snooze_until: datetime | None
- firing_started_at: datetime | None = None
owned_by_platform: bool = False
+ instances: tuple[InstanceCheckState, ...] = ()
+ grouping: Grouping = field(default_factory=Grouping)
+
+ def admit(self, grouping_keys: Sequence[str]) -> GroupAdmission:
+ """The groups a check may report, from keys in the source's priority order.
+
+ A group that already has an instance is always admitted, so an open group can still
+ resolve. New groups fill what `max_instances` leaves, front first.
+ """
+ existing = {instance.grouping_key for instance in self.instances}
+ room = max(self.grouping.max_instances - len(existing), 0)
+ admitted: list[str] = []
+ overflowed = 0
+ for key in dict.fromkeys(grouping_keys):
+ if key in existing:
+ admitted.append(key)
+ elif room > 0:
+ admitted.append(key)
+ room -= 1
+ else:
+ overflowed += 1
+ return GroupAdmission(admitted=tuple(admitted), overflowed=overflowed)
+
+ def instance(self, grouping_key: str = "") -> InstanceCheckState:
+ """The instance for a group, or the state a group with no instance starts from."""
+ for instance in self.instances:
+ if instance.grouping_key == grouping_key:
+ return instance
+ return InstanceCheckState(
+ grouping_key=grouping_key,
+ state=PlatformAlertState.NOT_FIRING.value
+ if self.check_status == PlatformAlertCheckStatus.OK
+ else self.check_status,
+ snooze_until=self.snooze_until,
+ )
@property
def filters(self) -> dict[str, Any]:
@@ -351,6 +460,9 @@ class EvaluationAnnouncement:
# whole evaluation, and every group in one announcement saw the same count.
consecutive_failures: int
transitions: tuple[AnnouncedTransition, ...]
+ # Groups the configuration had no room for. The last message names them, so a cap never drops
+ # a group without anyone being told.
+ overflowed: int = 0
@frozen
@@ -392,6 +504,7 @@ class AlertDeliveryRequest:
# The alert's page in the source's own product. Without one a message links to the platform's page.
source_alert_url: str | None = None
owned_by_platform: bool = False
+ overflowed: int = 0
@frozen
diff --git a/products/alerts_platform/backend/facade/platform_metrics.py b/products/alerts_platform/backend/facade/platform_metrics.py
index 6e46c1467dfc..e712507d8a45 100644
--- a/products/alerts_platform/backend/facade/platform_metrics.py
+++ b/products/alerts_platform/backend/facade/platform_metrics.py
@@ -11,7 +11,9 @@ from products.alerts_platform.backend.temporal.metrics import (
increment_checks_skipped,
increment_checks_unfinished,
increment_deliveries_deferred,
+ increment_groups_over_cap,
increment_history_rows_dropped,
+ increment_instances_reaped,
increment_notifications_muted,
increment_state_transition,
record_batch_duration,
@@ -25,7 +27,9 @@ __all__ = [
"increment_checks_skipped",
"increment_checks_unfinished",
"increment_deliveries_deferred",
+ "increment_groups_over_cap",
"increment_history_rows_dropped",
+ "increment_instances_reaped",
"increment_notifications_muted",
"increment_state_transition",
"record_batch_duration",
diff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.py
index 84a5208e2fcb..4023468ec201 100644
--- a/products/alerts_platform/backend/facade/testing.py
+++ b/products/alerts_platform/backend/facade/testing.py
@@ -81,7 +81,7 @@ def alert_for(configuration_id: UUID, *, grouping_key: str = "") -> PlatformAler
.filter(configuration_id=configuration_id, grouping_key=grouping_key)
.first()
)
- return None if row is None else instance_view(row, row.configuration.check_status)
+ return None if row is None else instance_view(row, row.configuration)
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 1fb83c6287b3..b1307164dd68 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -17,7 +17,9 @@ from posthog.dataclasses import frozen
from posthog.models import Team
from products.alerts_platform.backend.facade.contracts import (
+ Grouping,
GroupOutcome,
+ InstanceCheckState,
PlatformAlertCheckInput,
PlatformAlertOutcome,
PlatformAlertUpsert,
@@ -25,7 +27,12 @@ from products.alerts_platform.backend.facade.contracts import (
source_condition,
)
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertState
-from products.alerts_platform.backend.facade.platform_metrics import increment_history_rows_dropped, safe_record
+from products.alerts_platform.backend.facade.platform_metrics import (
+ increment_groups_over_cap,
+ increment_history_rows_dropped,
+ increment_instances_reaped,
+ safe_record,
+)
from products.alerts_platform.backend.facade.scheduling import (
advance_schedule,
compute_shard_offset_seconds,
@@ -43,16 +50,15 @@ def due_q(moment: datetime) -> Q:
return Q(next_check_at__lte=moment) | Q(next_check_at__isnull=True)
-def _existing_alerts(team_id: int, configurations: Sequence[PlatformAlertConfiguration]) -> dict[str, PlatformAlert]:
- """The runtime rows that exist. A configuration with none has never been evaluated.
-
- The grouping key is empty until a source groups its results, so today this is the whole of
- an alert's state and a real key needs no new table.
- """
- return {
- str(alert.configuration_id): alert
- for alert in PlatformAlert.objects.for_team(team_id).filter(configuration__in=configurations, grouping_key="")
- }
+def _instances_by_configuration(
+ team_id: int, configurations: Sequence[PlatformAlertConfiguration]
+) -> dict[str, list[PlatformAlert]]:
+ """Every runtime row each configuration has. A configuration with none has never been evaluated."""
+ found: dict[str, list[PlatformAlert]] = {}
+ rows = PlatformAlert.objects.for_team(team_id).filter(configuration__in=configurations).order_by("grouping_key")
+ for alert in rows:
+ found.setdefault(str(alert.configuration_id), []).append(alert)
+ return found
@frozen
@@ -76,9 +82,33 @@ def _instances(team_id: int, keys: Collection[_InstanceKey]) -> dict[_InstanceKe
def _alerts_for_write(
team_id: int, wanted: Mapping[_InstanceKey, PlatformAlertConfiguration]
) -> dict[_InstanceKey, PlatformAlert]:
- """The runtime rows, creating any group that has none yet."""
+ """The runtime rows, creating any group that has none yet while its configuration has room.
+
+ A group past `max_instances` gets no row, and so no write and no history. A source admits
+ groups before it reports them, so this is the backstop for one that did not.
+ """
+ configuration_ids = {key.configuration_id for key in wanted}
+ held: dict[str, int] = {}
+ for configuration_id in (
+ PlatformAlert.objects.for_team(team_id)
+ .filter(configuration_id__in=configuration_ids)
+ .values_list("configuration_id", flat=True)
+ ):
+ held[str(configuration_id)] = held.get(str(configuration_id), 0) + 1
existing = _instances(team_id, wanted.keys())
- missing = [key for key in wanted if key not in existing]
+ missing: list[_InstanceKey] = []
+ over_cap: dict[str, int] = {}
+ for key in wanted:
+ if key in existing:
+ continue
+ configuration = wanted[key]
+ if held.get(key.configuration_id, 0) >= Grouping.from_stored(configuration.grouping).max_instances:
+ over_cap[configuration.source_kind] = over_cap.get(configuration.source_kind, 0) + 1
+ continue
+ held[key.configuration_id] = held.get(key.configuration_id, 0) + 1
+ missing.append(key)
+ for source_kind, count in over_cap.items():
+ safe_record(increment_groups_over_cap, source_kind, count)
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
@@ -95,6 +125,41 @@ def _alerts_for_write(
return existing
+# Long enough that a group which resolves and fires again inside a day keeps its cooldown.
+REAP_AFTER: Final = timedelta(hours=24)
+
+
+def _reap(team_id: int, configurations: Sequence[PlatformAlertConfiguration], now: datetime) -> None:
+ """Deletes instances that hold a slot and nothing else, so a stale group frees its place.
+
+ Only an instance that is not firing, not muted, and that no check returned for longer than both
+ `REAP_AFTER` and its cooldown. A configuration whose checks fail returns no groups, so its
+ instances look unseen without being gone, and none of them is reaped while it is not OK.
+ """
+ healthy = {str(c.id): c for c in configurations if c.check_status == PlatformAlertConfiguration.CheckStatus.OK}
+ if not healthy:
+ return
+ candidates = (
+ PlatformAlert.objects.for_team(team_id)
+ .filter(
+ configuration_id__in=list(healthy), state=PlatformAlert.State.NOT_FIRING, last_seen_at__lt=now - REAP_AFTER
+ )
+ .filter(Q(snooze_until__isnull=True) | Q(snooze_until__lte=now))
+ .values_list("id", "configuration_id", "last_seen_at")
+ )
+ reaped: dict[str, list[UUID]] = {}
+ for alert_id, configuration_id, last_seen_at in candidates:
+ configuration = healthy[str(configuration_id)]
+ if configuration.snooze_until is not None and configuration.snooze_until > now:
+ continue
+ if last_seen_at is None or last_seen_at >= now - timedelta(minutes=configuration.cooldown_minutes):
+ continue
+ reaped.setdefault(configuration.source_kind, []).append(alert_id)
+ for source_kind, ids in reaped.items():
+ PlatformAlert.objects.for_team(team_id).filter(id__in=ids).delete()
+ safe_record(increment_instances_reaped, source_kind, len(ids))
+
+
def suppressed() -> Q:
"""Configurations a check status holds back.
@@ -158,11 +223,11 @@ def due_checks(
if not configurations:
return ()
- alerts = _existing_alerts(team_id, configurations)
- return tuple(_check(c, alerts.get(str(c.id))) for c in configurations)
+ instances = _instances_by_configuration(team_id, configurations)
+ return tuple(_check(c, instances.get(str(c.id), [])) for c in configurations)
-def _check(c: PlatformAlertConfiguration, alert: PlatformAlert | None) -> PlatformAlertCheckInput:
+def _check(c: PlatformAlertConfiguration, alerts: Sequence[PlatformAlert]) -> PlatformAlertCheckInput:
return PlatformAlertCheckInput(
id=c.id,
team_id=c.team_id,
@@ -176,14 +241,27 @@ 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=_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,
+ check_status=c.check_status,
+ snooze_until=c.snooze_until,
+ instances=tuple(
+ InstanceCheckState(
+ grouping_key=alert.grouping_key,
+ state=_check_state(c, alert),
+ last_notified_at=alert.last_notified_at,
+ snooze_until=_later(c.snooze_until, alert.snooze_until),
+ firing_started_at=alert.firing_started_at,
+ )
+ for alert in alerts
+ ),
+ grouping=Grouping.from_stored(c.grouping),
owned_by_platform=c.owner == PlatformAlertConfiguration.Owner.PLATFORM,
)
+def _later(first: datetime | None, second: datetime | None) -> datetime | None:
+ return max((moment for moment in (first, second) if moment is not None), default=None)
+
+
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."""
@@ -340,7 +418,12 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
for configuration in configurations:
outcome = by_id[str(configuration.id)]
for group in outcome.groups:
- alert = alerts[_InstanceKey(configuration_id=str(configuration.id), grouping_key=group.grouping_key)]
+ alert = alerts.get(
+ _InstanceKey(configuration_id=str(configuration.id), grouping_key=group.grouping_key)
+ )
+ if alert is None:
+ 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))
if group.notified:
@@ -369,11 +452,12 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
)
PlatformAlert.objects.for_team(team_id).bulk_update(
- list(alerts.values()), ["state", "last_notified_at", "firing_started_at"]
+ list(alerts.values()), ["state", "last_notified_at", "firing_started_at", "last_seen_at"]
)
PlatformAlertConfiguration.objects.for_team(team_id).bulk_update(
configurations, ["check_status", "consecutive_failures", "enabled", "next_check_at"]
)
+ _reap(team_id, configurations, now)
# `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.
transaction.on_commit(lambda: _record_history(team_id, rows))
@@ -431,6 +515,9 @@ def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -
"schedule_restriction": upsert.schedule_restriction,
# Reached by a backfill run, which re-admits a copy an operator switched off.
"switched_off_at": None,
+ # A source's snooze mutes the whole alert. State is left alone because a muted alert
+ # keeps tracking reality.
+ "snooze_until": upsert.snooze_until,
}
if (
existing is None
@@ -454,16 +541,10 @@ 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
)
- 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"]
if revived:
- alert.state = PlatformAlert.State.NOT_FIRING.value
- alert.firing_started_at = None
- update_fields += ["state", "firing_started_at"]
- alert.save(update_fields=update_fields)
+ PlatformAlert.objects.for_team(upsert.team_id).filter(configuration=configuration).update(
+ state=PlatformAlert.State.NOT_FIRING.value, firing_started_at=None
+ )
return created
diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.py
index 4f93bda089d1..e16aaec9e524 100644
--- a/products/alerts_platform/backend/logic/platform_reads.py
+++ b/products/alerts_platform/backend/logic/platform_reads.py
@@ -17,19 +17,22 @@ from products.alerts_platform.backend.facade.contracts import (
from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
-def instance_view(alert: PlatformAlert, check_status: str) -> PlatformAlertSnapshot:
+def instance_view(alert: PlatformAlert, configuration: PlatformAlertConfiguration) -> 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.
+ A configuration mute shows on every instance for the same reason a check reads it there.
"""
+ check_status = configuration.check_status
+ snoozes = [moment for moment in (configuration.snooze_until, alert.snooze_until) if moment is not None]
return PlatformAlertSnapshot(
id=alert.id,
grouping_key=alert.grouping_key,
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,
+ snooze_until=max(snoozes, default=None),
)
@@ -52,7 +55,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, configuration.check_status) for alert in configuration.alerts.all()),
+ alerts=tuple(instance_view(alert, configuration) for alert in configuration.alerts.all()),
)
@@ -103,4 +106,4 @@ def alert_snapshot(team_id: int, configuration_id: str, grouping_key: str) -> Pl
.filter(configuration_id=configuration_id, grouping_key=grouping_key)
.first()
)
- return instance_view(alert, alert.configuration.check_status) if alert is not None else None
+ return instance_view(alert, alert.configuration) if alert is not None else None
diff --git a/products/alerts_platform/backend/migrations/0012_platformalertconfiguration_grouping_snooze.py b/products/alerts_platform/backend/migrations/0012_platformalertconfiguration_grouping_snooze.py
new file mode 100644
index 000000000000..3c15024fa790
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0012_platformalertconfiguration_grouping_snooze.py
@@ -0,0 +1,27 @@
+# Generated by Django 5.2.18 on 2026-10-08 01:00
+
+from django.db import migrations, models
+
+import products.alerts_platform.backend.models.platform_alert
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0011_move_check_status_onto_configuration"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="platformalertconfiguration",
+ name="grouping",
+ field=models.JSONField(
+ db_default={"keys": [], "mode": "single"},
+ default=products.alerts_platform.backend.models.platform_alert.single_instance_grouping,
+ ),
+ ),
+ migrations.AddField(
+ model_name="platformalertconfiguration",
+ name="snooze_until",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/alerts_platform/backend/migrations/0013_move_snooze_onto_configuration.py b/products/alerts_platform/backend/migrations/0013_move_snooze_onto_configuration.py
new file mode 100644
index 000000000000..53dcfc8b8303
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0013_move_snooze_onto_configuration.py
@@ -0,0 +1,33 @@
+from django.db import migrations
+
+# A backfill copied each source's snooze onto the instance with the empty grouping key, and a
+# source snooze mutes the whole alert. Both statements match nothing on a second run.
+COPY_SNOOZE_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 snooze_until = alert.snooze_until
+FROM alerts_platformalert AS alert
+WHERE alert.configuration_id = configuration.id
+ AND alert.grouping_key = ''
+ AND alert.snooze_until IS NOT NULL
+ AND configuration.snooze_until IS NULL
+"""
+
+CLEAR_SNOOZE_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 snooze_until = NULL
+WHERE grouping_key = ''
+ AND snooze_until IS NOT NULL
+"""
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0012_platformalertconfiguration_grouping_snooze"),
+ ]
+
+ operations = [
+ migrations.RunSQL(COPY_SNOOZE_ONTO_CONFIGURATION, reverse_sql=migrations.RunSQL.noop),
+ migrations.RunSQL(CLEAR_SNOOZE_FROM_INSTANCES, reverse_sql=migrations.RunSQL.noop),
+ ]
diff --git a/products/alerts_platform/backend/migrations/0014_platformalert_last_seen_at.py b/products/alerts_platform/backend/migrations/0014_platformalert_last_seen_at.py
new file mode 100644
index 000000000000..b04910243c29
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0014_platformalert_last_seen_at.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.18 on 2026-10-08 02:43
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0013_move_snooze_onto_configuration"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="platformalert",
+ name="last_seen_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txt
index bbd6a0ed2ad2..bc18f089c09a 100644
--- a/products/alerts_platform/backend/migrations/max_migration.txt
+++ b/products/alerts_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_move_check_status_onto_configuration
+0014_platformalert_last_seen_at
diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
index 819295c7999b..6549fbaea8b6 100644
--- a/products/alerts_platform/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -22,6 +22,10 @@ from products.alerts_platform.backend.facade.enums import (
)
+def single_instance_grouping() -> dict[str, object]:
+ return {"mode": "single", "keys": []}
+
+
# nosemgrep: tuple-return-prefer-dataclass -- Django's `choices` contract is (value, label) pairs.
def source_kind_choices() -> list[tuple[str, str]]:
# A callable, so a new source does not write a state-only migration for its choice.
@@ -57,6 +61,8 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
source_kind = models.CharField(max_length=32, choices=source_kind_choices)
source_config = models.JSONField(default=dict)
+ # The stored form of the facade's `Grouping`.
+ grouping = models.JSONField(default=single_instance_grouping, db_default={"mode": "single", "keys": []})
# Retired, because a source keeps its bound in `source_config["condition"]`. Nothing reads these.
threshold_count = models.PositiveIntegerField(null=True, blank=True)
@@ -76,6 +82,8 @@ class PlatformAlertConfiguration(TeamScopedRootMixin, UUIDModel):
schedule_restriction = models.JSONField(null=True, blank=True)
next_check_at = models.DateTimeField(null=True, blank=True)
+ # Mutes every instance. An instance's own snooze mutes one group, and the later of the two holds.
+ snooze_until = 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"
@@ -145,6 +153,9 @@ class PlatformAlert(TeamScopedRootMixin, UUIDModel):
# rather than an opaque id, because `last_notified_at >= firing_started_at` is then how a
# reader knows whether this firing was ever announced.
firing_started_at = models.DateTimeField(null=True, blank=True)
+ # The last check that returned this group. Reaping reads it to free the slot of a group that
+ # stopped appearing. Null for a row no check has recorded since the column existed.
+ last_seen_at = models.DateTimeField(null=True, blank=True)
class Meta:
db_table = "alerts_platformalert"
diff --git a/products/alerts_platform/backend/temporal/metrics.py b/products/alerts_platform/backend/temporal/metrics.py
index c0dcecd8963c..c6a05c1934e4 100644
--- a/products/alerts_platform/backend/temporal/metrics.py
+++ b/products/alerts_platform/backend/temporal/metrics.py
@@ -93,6 +93,22 @@ def increment_state_transition(source: str, from_state: str, to_state: str) -> N
).add(1)
+def increment_groups_over_cap(source: str, count: int) -> None:
+ """Groups an outcome reported past its configuration's `max_instances`. A source admits groups
+ before it reports them, so a nonzero count means a source skipped that step."""
+ get_metric_meter({"source": source}).create_counter(
+ "alerts_platform_groups_over_cap_total",
+ "Groups dropped at record time because the configuration had no room for another instance",
+ ).add(count)
+
+
+def increment_instances_reaped(source: str, count: int) -> None:
+ get_metric_meter({"source": source}).create_counter(
+ "alerts_platform_instances_reaped_total",
+ "Idle alert instances deleted so their configuration can admit new groups",
+ ).add(count)
+
+
def increment_deliveries_deferred(source: str, count: int) -> None:
"""Deliveries a batch decided on but could not carry inside its activity payload bound.
diff --git a/products/alerts_platform/backend/tests/test_delivery_dispatch.py b/products/alerts_platform/backend/tests/test_delivery_dispatch.py
index c426f7491d3b..8536aaff2abb 100644
--- a/products/alerts_platform/backend/tests/test_delivery_dispatch.py
+++ b/products/alerts_platform/backend/tests/test_delivery_dispatch.py
@@ -229,12 +229,17 @@ class TestDeliveryDispatch(SimpleTestCase):
alert_name="API errors",
consecutive_failures=0,
transitions=(_transition(grouping_key="checkout"), _transition(grouping_key="search")),
+ overflowed=3,
)
self._deliver(transport, store, announcement)
assert [handle for _, handle in transport.sends] == [None, None]
assert len(store.threads) == 2
+ assert [
+ [detail.value for detail in message.details if detail.label == "Untracked groups"]
+ for message, _ in transport.sends
+ ] == [[], ["3 more groups not tracked because this alert is at its group limit"]]
def test_a_retried_evaluation_does_not_send_a_second_copy(self) -> None:
store = RecordingThreadStore()
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index 0fec46a50e5c..9453ba4ca6ac 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -23,7 +23,12 @@ from products.alerts_platform.backend.facade.api import (
from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
FiringEpisode,
+ GroupAdmission,
+ Grouping,
+ GroupingMode,
GroupOutcome,
+ InstanceCheckState,
+ PlatformAlertCheckInput,
PlatformAlertOutcome,
PlatformAlertUpsert,
PlatformOwnershipHandover,
@@ -195,7 +200,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
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"
+ assert check.instance().state == "errored"
self._record(at=due, kind=AlertEventKind.CHECK, new_state="not_firing", notified=False)
@@ -262,6 +267,88 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
)
assert rows == [("api", api.id, "firing", 40.0), ("web", web.id, "not_firing", None)]
+ def test_a_check_reads_each_group_composed_with_the_configuration(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),
+ ),
+ GroupOutcome(grouping_key="web", kind=AlertEventKind.CHECK, new_state="not_firing", notified=False),
+ )
+ )
+ due = self._next_due()
+ muted_until = due + timedelta(hours=1)
+ with team_scope(self.team.id):
+ PlatformAlert.objects.filter(configuration=self.configuration, grouping_key="web").update(
+ snooze_until=due + timedelta(hours=2)
+ )
+ PlatformAlertConfiguration.objects.filter(id=self.configuration.id).update(snooze_until=muted_until)
+
+ (check,) = due_checks(self.team.id, SourceKind.LOGS.value, slot_of(due, due), due)
+
+ assert {
+ key: (check.instance(key).state, check.instance(key).snooze_until) for key in ("api", "web", "new")
+ } == {
+ "api": ("firing", muted_until),
+ "web": ("not_firing", due + timedelta(hours=2)),
+ "new": ("not_firing", muted_until),
+ }
+ assert check.instance("api").firing_started_at == self.cutoff
+
+ def _group(self, key: str, *, state: str = "not_firing") -> GroupOutcome:
+ return GroupOutcome(grouping_key=key, kind=AlertEventKind.CHECK, new_state=state, notified=False)
+
+ def test_a_group_past_the_cap_gets_no_instance_and_no_history(self) -> None:
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(id=self.configuration.id).update(
+ grouping=Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service",), max_instances=1).to_stored()
+ )
+
+ self._record(groups=(self._group("api"), self._group("web")))
+
+ with team_scope(self.team.id):
+ keys = list(
+ PlatformAlert.objects.filter(configuration=self.configuration).values_list("grouping_key", flat=True)
+ )
+ rows = sync_execute(
+ "SELECT grouping_key FROM platform_alert_events WHERE team_id = %(team_id)s AND configuration_id = %(configuration_id)s",
+ {"team_id": self.team.id, "configuration_id": self.configuration.id},
+ )
+ assert (keys, rows) == (["api"], [("api",)])
+
+ @parameterized.expand(
+ [
+ ("idle_past_the_window", {}, False),
+ ("firing", {"state": "firing"}, True),
+ ("seen_recently", {"last_seen_hours_ago": 2}, True),
+ ("still_snoozed", {"snoozed": True}, True),
+ ("checks_failing", {"recorded_state": "errored"}, True),
+ ("cooldown_outlasts_the_window", {"cooldown_minutes": 48 * 60}, True),
+ ]
+ )
+ def test_an_idle_group_is_reaped_so_its_slot_frees(self, _name: str, case: dict[str, Any], kept: bool) -> None:
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(id=self.configuration.id).update(
+ cooldown_minutes=case.get("cooldown_minutes", 0)
+ )
+ PlatformAlert.objects.create(
+ team=self.team,
+ configuration=self.configuration,
+ grouping_key="old",
+ state=case.get("state", "not_firing"),
+ last_seen_at=self.cutoff - timedelta(hours=case.get("last_seen_hours_ago", 25)),
+ snooze_until=self.cutoff + timedelta(hours=1) if case.get("snoozed") else None,
+ )
+
+ self._record(groups=(self._group("api", state=case.get("recorded_state", "not_firing")),))
+
+ with team_scope(self.team.id):
+ assert PlatformAlert.objects.filter(configuration=self.configuration, grouping_key="old").exists() is kept
+
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.
@@ -369,9 +456,8 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
)
with team_scope(self.team.id):
PlatformAlertConfiguration.objects.filter(legacy_configuration_id=legacy_id).update(consecutive_failures=3)
- PlatformAlert.objects.filter(configuration__legacy_configuration_id=legacy_id).update(
- state="firing", firing_started_at=self.cutoff
- )
+ copied = PlatformAlertConfiguration.objects.get(legacy_configuration_id=legacy_id)
+ platform_testing.start_firing(copied.id, team_id=self.team.id, at=self.cutoff)
if disabled_between:
disable_configurations(SourceKind.LOGS, team_id=self.team.id)
with time_machine.travel(self.cutoff, tick=False):
@@ -404,14 +490,16 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
for c in due_checks(self.team.id, SourceKind.LOGS.value, self.slot, self.cutoff)
if c.legacy_configuration_id == legacy_id
]
- return check.state, check.snooze_until
+ instance = check.instance()
+ return instance.state, instance.snooze_until
with time_machine.travel(self.cutoff, tick=False):
copy(snoozed_until)
assert snooze_seen_by_check() == ("not_firing", snoozed_until)
with team_scope(self.team.id):
- PlatformAlert.objects.filter(configuration__legacy_configuration_id=legacy_id).update(state="firing")
+ copied = PlatformAlertConfiguration.objects.get(legacy_configuration_id=legacy_id)
+ PlatformAlert.objects.create(team=self.team, configuration=copied, state="firing")
with time_machine.travel(self.cutoff, tick=False):
copy(snoozed_until)
assert snooze_seen_by_check() == ("firing", snoozed_until)
@@ -427,7 +515,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
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)
+ platform_testing.start_firing(copied.id, team_id=self.team.id, at=self.cutoff)
with time_machine.travel(self.cutoff, tick=False):
self._copy(legacy_id, revive=True)
@@ -467,6 +555,53 @@ def _group(grouping_key: str) -> GroupOutcome:
return GroupOutcome(grouping_key=grouping_key, kind=AlertEventKind.CHECK, new_state="not_firing", notified=False)
+ "existing, returned, expected",
+ [
+ ((), ("a", "b", "c", "d"), GroupAdmission(admitted=("a", "b", "c"), overflowed=1)),
+ (("x", "y", "z"), ("q", "x"), GroupAdmission(admitted=("x",), overflowed=1)),
+ (("x",), ("x", "a", "a", "b"), GroupAdmission(admitted=("x", "a", "b"), overflowed=0)),
+ ],
+)
+def test_a_check_admits_existing_groups_and_new_ones_up_to_the_cap(
+ existing: tuple[str, ...], returned: tuple[str, ...], expected: GroupAdmission
+) -> None:
+ check = PlatformAlertCheckInput(
+ id=uuid4(),
+ team_id=1,
+ name="API errors",
+ source_config={},
+ check_interval_minutes=5,
+ evaluation_periods=1,
+ datapoints_to_alarm=1,
+ cooldown_minutes=0,
+ schedule_restriction=None,
+ next_check_at=None,
+ consecutive_failures=0,
+ legacy_configuration_id=None,
+ check_status="ok",
+ snooze_until=None,
+ instances=tuple(InstanceCheckState(grouping_key=key, state="not_firing") for key in existing),
+ grouping=Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service",), max_instances=3),
+ )
+
+ assert check.admit(returned) == expected
+
+
+ "fields",
+ [
+ {"mode": GroupingMode.SINGLE, "keys": ("service",)},
+ {"mode": GroupingMode.BY_RESULT_LABELS, "keys": ()},
+ {"mode": GroupingMode.BY_RESULT_LABELS, "keys": ("service", "service")},
+ {"mode": GroupingMode.BY_RESULT_LABELS, "keys": ("service",), "max_instances": 0},
+ ],
+)
+def test_a_grouping_rejects_keys_its_mode_cannot_use(fields: dict[str, Any]) -> None:
+ with pytest.raises(ValueError):
+ Grouping(**fields)
+
+
@pytest.mark.parametrize(
"overrides",
[
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 2eb1b33fd4e5..0bc90b4c2a81 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -243,16 +243,17 @@ def is_in_quiet_hours(schedule_restriction: dict | None, now: datetime, tz_name:
def _snapshot(check: PlatformAlertCheckInput, prior_breached: tuple[bool, ...]) -> AlertSnapshot:
+ instance = check.instance()
return AlertSnapshot(
- state=AlertState(check.state),
+ state=AlertState(instance.state),
cooldown=timedelta(minutes=check.cooldown_minutes),
- last_notified_at=check.last_notified_at,
- snooze_until=check.snooze_until,
+ last_notified_at=instance.last_notified_at,
+ snooze_until=instance.snooze_until,
consecutive_failures=check.consecutive_failures,
evaluation_periods=check.evaluation_periods,
datapoints_to_alarm=check.datapoints_to_alarm,
recent_events_breached=prior_breached,
- firing_started_at=check.firing_started_at,
+ firing_started_at=instance.firing_started_at,
)
@@ -285,8 +286,9 @@ 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)
- if check.state != new_state:
- safe_record(increment_state_transition, SourceKind.LOGS.value, check.state, new_state)
+ previous_state = check.instance().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:
lag_ms = int((now - check.next_check_at).total_seconds() * 1000)
if lag_ms > 0:
@@ -405,7 +407,7 @@ def _request(
"""
destination_alert_id = str(check.legacy_configuration_id)
incident_action = decide_incident_action(
- AlertState(check.state), outcome.new_state, policy=PLATFORM_LOGS_ALERT_POLICY
+ AlertState(check.instance().state), outcome.new_state, policy=PLATFORM_LOGS_ALERT_POLICY
)
if incident_action is not None and not _has_incident_destination(check.team_id, destination_alert_id):
incident_action = None
@@ -626,13 +628,16 @@ def _as_configured_now(
logger.exception("Failed to bring a platform logs copy up to date", check_id=str(check.id))
current.append(check)
continue
- current.append(replace(check, **{field: getattr(upsert, field) for field in _LIVE_FIELDS}))
+ # A logs mute lives on the configuration alone, so each instance takes the live one too.
+ instances = tuple(replace(instance, snooze_until=upsert.snooze_until) for instance in check.instances)
+ current.append(replace(check, instances=instances, **{field: getattr(upsert, field) for field in _LIVE_FIELDS}))
return current, stopped
def _stopped(check: PlatformAlertCheckInput, *, now: datetime) -> Decision:
"""A check whose logs alert no longer runs. It leaves the state alone and disables the copy."""
- unchanged = ControlPlaneOutcome(new_state=AlertState(check.state), consecutive_failures=check.consecutive_failures)
+ state = check.instance().state
+ unchanged = ControlPlaneOutcome(new_state=AlertState(state), consecutive_failures=check.consecutive_failures)
recorded = _recorded(
check,
outcome=unchanged,
@@ -643,7 +648,7 @@ def _stopped(check: PlatformAlertCheckInput, *, now: datetime) -> Decision:
disable=True,
)
_record_check_metrics(
- check, new_state=check.state, notification=NotificationAction.NONE, skip=SkipReason.SOURCE_RULE, now=now
+ check, new_state=state, notification=NotificationAction.NONE, skip=SkipReason.SOURCE_RULE, now=now
)
return recorded, None
diff --git a/products/logs/backend/test/test_alert_comparison.py b/products/logs/backend/test/test_alert_comparison.py
index 07ff959d101b..0c8ba46e5b57 100644
--- a/products/logs/backend/test/test_alert_comparison.py
+++ b/products/logs/backend/test/test_alert_comparison.py
@@ -42,8 +42,7 @@ def _check_input(alert_id, *, next_check_at) -> PlatformAlertCheckInput:
next_check_at=next_check_at,
consecutive_failures=0,
legacy_configuration_id=None,
- state="not_firing",
- last_notified_at=None,
+ check_status="ok",
snooze_until=None,
)