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): snooze one group of a grouped platform alert (#119983)

Jimmy Zhu3afe6c3772e3
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index f36d25f06857..4b49a4d491ec 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -296,6 +296,9 @@ 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.
+`POST /api/projects/:id/platform_alerts/:id/snooze_group/` sets or clears an instance's snooze on a grouped alert the platform owns.
+Unlike a snooze of the whole alert, it leaves the group's firing open and the schedule alone, so the group's incident edges still go out.
+`record_outcomes` reads each instance's mute again when it writes a verdict, so a check that was already running when a snooze landed records its fire or resolve as muted instead of announcing it.
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.
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index 023c76de0367..b76c2fa20505 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -20,6 +20,7 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformAlertHistory,
PlatformAlertOutcome,
PlatformAlertRuntime,
+ PlatformAlertSnapshot,
PlatformAlertUpsert,
PlatformCheckEventPage,
PlatformHandback,
@@ -164,6 +165,30 @@ def update_configuration(
)
+def snooze_group(
+ *,
+ team_id: int,
+ source_kinds: Sequence[str],
+ configuration_id: UUID,
+ grouping_key: str,
+ snooze_until: datetime | None,
+) -> PlatformAlertSnapshot | None:
+ """Mutes one group of a configuration the platform owns until `snooze_until`, or clears the mute
+ when it is None. Returns the group, or None when the caller cannot read the configuration.
+
+ Raises `PlatformAlertNotEditable` for a configuration its source owns, `UnknownPlatformAlertGroup`
+ for a key with no instance, and `InvalidPlatformAlertEdit` for a time not in the future or an
+ alert that is not grouped.
+ """
+ return platform_writes.snooze_group(
+ team_id=team_id,
+ source_kinds=source_kinds,
+ configuration_id=configuration_id,
+ grouping_key=grouping_key,
+ snooze_until=snooze_until,
+ )
+
+
def update_owned_copy(
*,
team_id: int,
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index e5466b7614e8..772f0264d1e0 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -875,6 +875,10 @@ class PlatformAlertNotEditable(Exception):
"""A configuration the platform does not own, so its source's own API writes it."""
+class UnknownPlatformAlertGroup(LookupError):
+ """A grouping key the configuration has no instance for."""
+
+
class SourceEditMirror(Protocol):
"""Writes an edit made through the platform API onto the source's own row.
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 8a4948954687..a5c341d15434 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -18,6 +18,7 @@ from posthog.dataclasses import frozen
from posthog.models import Team
from products.alerts_platform.backend.facade.contracts import (
+ AlertEventKind,
CheckFailure,
Grouping,
GroupingMode,
@@ -33,6 +34,7 @@ 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.lifecycle import NotificationAction
from products.alerts_platform.backend.facade.platform_metrics import (
increment_groups_over_cap,
increment_history_rows_dropped,
@@ -474,6 +476,28 @@ def _without_stale_groups(
return replace(outcome, groups=(), overflowed=0, evicted=())
+_HELD_BY_MUTE: Final = {
+ AlertEventKind.FIRING: NotificationAction.FIRE.value,
+ AlertEventKind.RESOLVED: NotificationAction.RESOLVE.value,
+}
+
+
+def _held_by_mute(
+ configuration: PlatformAlertConfiguration, alert: PlatformAlert, group: GroupOutcome, now: datetime
+) -> GroupOutcome:
+ """The verdict, or the verdict muted when a mute that the check did not see holds now.
+
+ A check reads the mute when it starts, so a snooze set while it runs reaches only this write.
+ Held the way the machine holds a muted announcement: the state and the firing still move,
+ and `last_notified_at` stays behind, so a held fire goes out once the mute ends.
+ """
+ held = _HELD_BY_MUTE.get(group.kind)
+ snooze_until = _composed(configuration, alert).snooze_until
+ if held is None or snooze_until is None or snooze_until <= now:
+ return group
+ return replace(group, kind=AlertEventKind.CHECK, notified=False, muted_notification=held)
+
+
def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now: datetime) -> int:
"""Persists a batch's decisions and advances each configuration's schedule.
@@ -534,12 +558,13 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
rows: list[PlatformAlertEventRow] = []
for configuration in configurations:
outcome = by_id[str(configuration.id)]
- for group in outcome.groups:
+ for reported in outcome.groups:
alert = alerts.get(
- _InstanceKey(configuration_id=str(configuration.id), grouping_key=group.grouping_key)
+ _InstanceKey(configuration_id=str(configuration.id), grouping_key=reported.grouping_key)
)
if alert is None:
continue
+ group = _held_by_mute(configuration, alert, reported, now)
touched.append(alert)
alert.last_seen_at = now
# Before either row is mutated, so the history row keeps the state the check found.
diff --git a/products/alerts_platform/backend/logic/platform_writes.py b/products/alerts_platform/backend/logic/platform_writes.py
index cca495a1464c..4424fb015421 100644
--- a/products/alerts_platform/backend/logic/platform_writes.py
+++ b/products/alerts_platform/backend/logic/platform_writes.py
@@ -6,7 +6,8 @@ and the next check reads back. Writing the copy here would fork it, so those are
from collections.abc import Callable, Sequence
from dataclasses import replace
-from datetime import datetime
+from datetime import datetime, timedelta
+from typing import Final
from uuid import UUID
from django.db import transaction
@@ -20,16 +21,19 @@ from products.alerts_platform.backend.facade.contracts import (
MAX_EVALUATION_PERIODS,
MAX_STORED_INTEGER,
Grouping,
+ GroupingMode,
InvalidPlatformAlertEdit,
PlatformAlertConfigurationEdit,
PlatformAlertConfigurationView,
PlatformAlertNotEditable,
+ PlatformAlertSnapshot,
SourceKind,
+ UnknownPlatformAlertGroup,
)
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_restriction
from products.alerts_platform.backend.logic import control_plane, platform_lifecycle, platform_reads, source_configs
-from products.alerts_platform.backend.models import PlatformAlertConfiguration
+from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
class MissingPlatformCopy(Exception):
@@ -126,6 +130,66 @@ def update_configuration(
)
+# A snoozed group keeps its slot under `max_instances`, so a forgotten long snooze would hold it.
+MAX_GROUP_SNOOZE: Final = timedelta(days=30)
+
+
+def snooze_group(
+ *,
+ team_id: int,
+ source_kinds: Sequence[str],
+ configuration_id: UUID,
+ grouping_key: str,
+ snooze_until: datetime | None,
+) -> PlatformAlertSnapshot | None:
+ """Sets or clears the mute of one group of a configuration the platform owns.
+
+ None when the configuration does not exist or its kind is not among `source_kinds`.
+
+ Unlike a snooze of the whole alert, this leaves the group's firing open and the schedule alone.
+ The alert's other groups still need their checks, so this group's checks go on too. Ending the
+ firing would send a resolve now, and a breach that goes on would trigger a new incident at the
+ next check. The mute holds the group's messages, and its incident edges still go out.
+ """
+ now = django_timezone.now()
+ if snooze_until is not None and snooze_until <= now:
+ raise InvalidPlatformAlertEdit("snooze_until", "Pick a time in the future, or send null to unsnooze.")
+ if snooze_until is not None and snooze_until > now + MAX_GROUP_SNOOZE:
+ raise InvalidPlatformAlertEdit(
+ "snooze_until", f"A group can be snoozed for up to {MAX_GROUP_SNOOZE.days} days. Pick an earlier time."
+ )
+ with transaction.atomic():
+ # The configuration before its instance, the order `record_outcomes` locks them in.
+ configuration = (
+ PlatformAlertConfiguration.objects.for_team(team_id, canonical=True)
+ .select_for_update()
+ .filter(id=configuration_id, source_kind__in=list(source_kinds))
+ .first()
+ )
+ if configuration is None:
+ return None
+ if configuration.owner != PlatformAlertOwner.PLATFORM:
+ raise PlatformAlertNotEditable(
+ f"This alert is managed by the {configuration.source_kind} product, so its groups cannot be "
+ "snoozed here. Snooze the whole alert there instead."
+ )
+ # The one instance of an ungrouped alert is the whole alert, whose snooze also ends the firing.
+ if Grouping.from_stored(configuration.grouping).mode == GroupingMode.SINGLE:
+ raise InvalidPlatformAlertEdit(
+ "grouping_key", "This alert is not grouped, so it has no group to snooze. Snooze the whole alert."
+ )
+ alert = (
+ PlatformAlert.objects.for_team(team_id, canonical=True)
+ .filter(configuration=configuration, grouping_key=grouping_key)
+ .first()
+ )
+ if alert is None:
+ raise UnknownPlatformAlertGroup(grouping_key)
+ alert.snooze_until = snooze_until
+ alert.save(update_fields=["snooze_until"])
+ return platform_reads.instance_view(alert, configuration)
+
+
def update_owned_copy(
*,
team_id: int,
diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.py
index a04c156ec545..ca203930df0a 100644
--- a/products/alerts_platform/backend/presentation/views/platform_alert.py
+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py
@@ -1,13 +1,16 @@
from dataclasses import replace
from functools import cache, cached_property
from typing import Any, Literal, cast
+from uuid import UUID
from drf_spectacular.utils import OpenApiResponse, PolymorphicProxySerializer, extend_schema, extend_schema_field
from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.pagination import PrecountedLimitOffsetPagination
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.exceptions import Conflict
@@ -30,9 +33,11 @@ from products.alerts_platform.backend.facade.contracts import (
GroupingMode,
InvalidPlatformAlertEdit,
OnOverflow,
+ PlatformAlertConfigurationView,
PlatformAlertNotEditable,
SourceConfigSpec,
SourceKind,
+ UnknownPlatformAlertGroup,
)
from products.alerts_platform.backend.facade.enums import (
PlatformAlertCheckStatus,
@@ -274,6 +279,19 @@ PLATFORM_ALERT_CONFIGURATION_EDIT = PolymorphicProxySerializer(
resource_type_field_name="source_kind",
)
+
+class PlatformAlertGroupSnoozeSerializer(serializers.Serializer):
+ grouping_key = serializers.CharField(
+ max_length=255,
+ help_text="Key of the group to snooze, as the grouping_key of one of the alert's instances.",
+ )
+ snooze_until = serializers.DateTimeField(
+ allow_null=True,
+ help_text="Time until which this group's notifications are muted. Must be in the future and at most "
+ "30 days away. Null clears the group's snooze. The group keeps being checked, and its firing stays open.",
+ )
+
+
EDIT_RESPONSES = {
200: PlatformAlertConfigurationSerializer,
403: OpenApiResponse(description="The caller cannot write alerts of this source kind."),
@@ -339,17 +357,26 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generic
def _readable_source_kinds(self) -> list[str]:
return self._source_kinds_with("viewer", "read")
- def _edit(self, request: Request, pk: str, *, partial: bool) -> Response:
- configuration_id = serializers.UUIDField().run_validation(pk)
- team_id = self._canonical_team_id()
+ @cached_property
+ def _writable_source_kinds(self) -> list[str]:
+ return self._source_kinds_with("editor", "write")
+
+ def _writable_configuration(
+ self, team_id: int, configuration_id: UUID, verb: str
+ ) -> PlatformAlertConfigurationView:
current = platform_api.get_configuration(
team_id=team_id, source_kinds=self._readable_source_kinds(), configuration_id=configuration_id
)
if current is None:
raise NotFound()
- writable = self._source_kinds_with("editor", "write")
- if current.source_kind not in writable:
- raise PermissionDenied(f"You cannot edit {current.source_kind} alerts.")
+ if current.source_kind not in self._writable_source_kinds:
+ raise PermissionDenied(f"You cannot {verb} {current.source_kind} alerts.")
+ return current
+
+ def _edit(self, request: Request, pk: str, *, partial: bool) -> Response:
+ configuration_id = serializers.UUIDField().run_validation(pk)
+ team_id = self._canonical_team_id()
+ current = self._writable_configuration(team_id, configuration_id, "edit")
# Checked again under the row lock. Here it answers before the body is validated, so a caller
# never fixes a body for an alert it can never write.
if current.owner != PlatformAlertOwner.PLATFORM:
@@ -367,7 +394,7 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generic
try:
updated = platform_api.update_configuration(
team_id=team_id,
- source_kinds=writable,
+ source_kinds=self._writable_source_kinds,
configuration_id=configuration_id,
# A partial update names only the fields it changes. The rest keep what is stored.
change=lambda stored: replace(stored, **fields),
@@ -388,6 +415,45 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generic
def partial_update(self, request: Request, pk: str, **kwargs) -> Response:
return self._edit(request, pk, partial=True)
+ @validated_request(
+ PlatformAlertGroupSnoozeSerializer,
+ responses={
+ 200: PlatformAlertSerializer,
+ 400: OpenApiResponse(description="The time is not in the future, or the alert is not grouped."),
+ 403: OpenApiResponse(description="The caller cannot write alerts of this source kind."),
+ 404: OpenApiResponse(
+ description="No alert with this id that the caller can read, or no group with this key."
+ ),
+ 409: OpenApiResponse(description="The source product owns this alert, so only its own API changes it."),
+ },
+ summary="Snooze one group of a grouped alert",
+ )
+ @action(detail=True, methods=["post"], required_scopes=["alert:write"])
+ def snooze_group(self, request: ValidatedRequest, pk: str, **kwargs) -> Response:
+ configuration_id = serializers.UUIDField().run_validation(pk)
+ team_id = self._canonical_team_id()
+ self._writable_configuration(team_id, configuration_id, "snooze")
+ try:
+ group = platform_api.snooze_group(
+ team_id=team_id,
+ source_kinds=self._writable_source_kinds,
+ configuration_id=configuration_id,
+ grouping_key=request.validated_data["grouping_key"],
+ snooze_until=request.validated_data["snooze_until"],
+ )
+ except PlatformAlertNotEditable as error:
+ raise Conflict(str(error)) from error
+ except UnknownPlatformAlertGroup as error:
+ raise NotFound(
+ "This alert has no group with that key. A group that stays quiet is removed, so refresh the "
+ "alert to see its current groups."
+ ) from error
+ except InvalidPlatformAlertEdit as error:
+ raise ValidationError({error.field_name: str(error)}) from error
+ if group is None:
+ raise NotFound()
+ return Response(PlatformAlertSerializer(group).data)
+
def list(self, request: Request, **kwargs) -> Response:
paginator = cast(PrecountedLimitOffsetPagination, self.paginator)
limit = paginator.get_limit(request)
diff --git a/products/alerts_platform/backend/tests/api/test_platform_alert.py b/products/alerts_platform/backend/tests/api/test_platform_alert.py
index 769dea185600..23dbf461817b 100644
--- a/products/alerts_platform/backend/tests/api/test_platform_alert.py
+++ b/products/alerts_platform/backend/tests/api/test_platform_alert.py
@@ -1,6 +1,8 @@
from datetime import UTC, datetime
+from typing import Any
from uuid import UUID, uuid4
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -389,3 +391,89 @@ class TestPlatformAlertAPI(APIBaseTest):
configuration.refresh_from_db()
assert (configuration.check_status, configuration.consecutive_failures) == ("ok", 0)
assert configuration.next_check_at is not None
+
+ def _grouped_configuration(self, owner: str = "platform") -> PlatformAlertConfiguration:
+ configuration = self._create_configuration(self.team, "API errors", owner=owner)
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(id=configuration.id).update(
+ grouping={"mode": "by_result_labels", "keys": ["service_name"]}
+ )
+ for key in ("checkout", "api"):
+ PlatformAlert.objects.create(
+ team=self.team, configuration=configuration, grouping_key=key, state=PlatformAlert.State.FIRING
+ )
+ return configuration
+
+ def _snoozes(self, configuration: PlatformAlertConfiguration) -> dict[str, datetime | None]:
+ with team_scope(self.team.id):
+ return dict(
+ PlatformAlert.objects.filter(configuration=configuration).values_list("grouping_key", "snooze_until")
+ )
+
+ def test_snoozing_a_group_mutes_only_that_group_and_clearing_it_unmutes(self) -> None:
+ self._set_flag(True)
+ configuration = self._grouped_configuration()
+ url = f"{self._edit_url(configuration)}snooze_group/"
+ until = datetime(2026, 10, 1, 12, tzinfo=UTC)
+ # A key rather than a session, because a custom action without a declared scope refuses keys.
+ self.client.logout()
+ self.client.credentials(
+ HTTP_AUTHORIZATION=f"Bearer {self.create_personal_api_key_with_scopes(['alert:write', 'logs:write'])}"
+ )
+
+ with time_machine.travel(datetime(2026, 10, 1, 10, tzinfo=UTC), tick=False):
+ snoozed = self.client.post(url, {"grouping_key": "checkout", "snooze_until": until}, format="json")
+
+ assert snoozed.status_code == status.HTTP_200_OK, snoozed.json()
+ assert (snoozed.json()["grouping_key"], snoozed.json()["snooze_until"]) == ("checkout", "2026-10-01T12:00:00Z")
+ assert self._snoozes(configuration) == {"checkout": until, "api": None}
+ with team_scope(self.team.id):
+ assert set(PlatformAlert.objects.filter(configuration=configuration).values_list("state", flat=True)) == {
+ "firing"
+ }
+
+ cleared = self.client.post(url, {"grouping_key": "checkout", "snooze_until": None}, format="json")
+
+ assert cleared.status_code == status.HTTP_200_OK, cleared.json()
+ assert self._snoozes(configuration) == {"checkout": None, "api": None}
+
+ @parameterized.expand(
+ [
+ ("owned_by_its_source", {"owner": "source"}, {}, status.HTTP_409_CONFLICT, None),
+ ("unknown_group", {}, {"grouping_key": "web"}, status.HTTP_404_NOT_FOUND, None),
+ (
+ "time_in_the_past",
+ {},
+ {"snooze_until": "2026-10-01T09:00:00Z"},
+ status.HTTP_400_BAD_REQUEST,
+ "snooze_until",
+ ),
+ (
+ "time_past_the_limit",
+ {},
+ {"snooze_until": "2026-11-15T12:00:00Z"},
+ status.HTTP_400_BAD_REQUEST,
+ "snooze_until",
+ ),
+ ("ungrouped_alert", {"grouped": False}, {}, status.HTTP_400_BAD_REQUEST, "grouping_key"),
+ ]
+ )
+ def test_a_refused_group_snooze_changes_nothing(
+ self, _name: str, setup: dict[str, Any], body: dict[str, Any], expected: int, field: str | None
+ ) -> None:
+ self._set_flag(True)
+ configuration = self._grouped_configuration(owner=setup.get("owner", "platform"))
+ if setup.get("grouped") is False:
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(id=configuration.id).update(grouping={"mode": "single"})
+ url = f"{self._edit_url(configuration)}snooze_group/"
+
+ with time_machine.travel(datetime(2026, 10, 1, 10, tzinfo=UTC), tick=False):
+ response = self.client.post(
+ url, {"grouping_key": "checkout", "snooze_until": "2026-10-01T12:00:00Z", **body}, format="json"
+ )
+
+ assert response.status_code == expected, response.json()
+ if field is not None:
+ assert response.json()["attr"] == field
+ assert self._snoozes(configuration) == {"checkout": None, "api": None}
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index 6b99674cc8df..602b98d6be60 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -49,6 +49,7 @@ from products.alerts_platform.backend.facade.grouping import (
)
from products.alerts_platform.backend.facade.lifecycle import LOGS_ALERT_POLICY, AlertSnapshot, AlertState
from products.alerts_platform.backend.facade.payload import MAX_BATCH_PAYLOAD_BYTES, payload_bytes
+from products.alerts_platform.backend.logic.platform_alert_events import announcement
from products.alerts_platform.backend.logic.platform_lifecycle import CONFIGURATION_ROW_ALERT_ID
from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
from products.alerts_platform.backend.models.platform_alert_events_sql import SHARDED_PLATFORM_ALERT_EVENTS_TABLE
@@ -436,6 +437,69 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
self.cutoff,
)
+ @parameterized.expand([("group_snooze", True), ("alert_snooze", False)])
+ def test_a_snooze_set_while_a_check_runs_holds_what_the_check_announces(
+ self, _name: str, group_snooze: bool
+ ) -> 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),
+ ),
+ self._group("web"),
+ )
+ )
+ due = self._next_due()
+ # Straight to the rows, as the snooze lands after the check read them. An alert snooze set
+ # this way stands for a source's copied snooze, which leaves the schedule where it was.
+ with team_scope(self.team.id):
+ if group_snooze:
+ PlatformAlert.objects.filter(configuration=self.configuration).update(
+ snooze_until=due + timedelta(hours=1)
+ )
+ else:
+ PlatformAlertConfiguration.objects.filter(id=self.configuration.id).update(
+ snooze_until=due + timedelta(hours=1)
+ )
+
+ self._record(
+ at=due,
+ groups=(
+ GroupOutcome(
+ grouping_key="api",
+ kind=AlertEventKind.RESOLVED,
+ new_state="not_firing",
+ notified=True,
+ firing_episode=FiringEpisode(started_at=self.cutoff, ended=True),
+ ),
+ GroupOutcome(
+ grouping_key="web",
+ kind=AlertEventKind.FIRING,
+ new_state="firing",
+ notified=True,
+ firing_episode=FiringEpisode(started_at=due, ended=False),
+ ),
+ ),
+ )
+
+ evaluation_key = f"window:{due.isoformat()}"
+ recorded = sync_execute(
+ "SELECT grouping_key, kind, state, muted_notification FROM platform_alert_events "
+ "WHERE team_id = %(team_id)s AND configuration_id = %(configuration_id)s "
+ "AND evaluation_key = %(evaluation_key)s ORDER BY grouping_key",
+ {"team_id": self.team.id, "configuration_id": self.configuration.id, "evaluation_key": evaluation_key},
+ )
+ assert recorded == [("api", "check", "not_firing", "resolve"), ("web", "check", "firing", "fire")]
+ assert announcement(self.team.id, str(self.configuration.id), evaluation_key, source=SourceKind.LOGS) is None
+ api, web = self._alert("api"), self._alert("web")
+ assert (api.state, api.firing_started_at, api.last_notified_at) == ("not_firing", None, self.cutoff)
+ # A notification behind the firing's start is what makes the next unmuted check announce it.
+ assert (web.state, web.firing_started_at, web.last_notified_at) == ("firing", due, None)
+
def _group(self, key: str, *, state: str = "not_firing") -> GroupOutcome:
return GroupOutcome(grouping_key=key, kind=AlertEventKind.CHECK, new_state=state, notified=False)
diff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.ts
index 95efaf57526a..e46fdd687175 100644
--- a/products/alerts_platform/frontend/generated/api.schemas.ts
+++ b/products/alerts_platform/frontend/generated/api.schemas.ts
@@ -769,6 +769,19 @@ export interface PatchedLogsPlatformAlertConfigurationEditApi {
export type PatchedPlatformAlertConfigurationEditApi = PatchedLogsPlatformAlertConfigurationEditApi
+export interface PlatformAlertGroupSnoozeApi {
+ /**
+ * Key of the group to snooze, as the grouping_key of one of the alert's instances.
+ * @maxLength 255
+ */
+ grouping_key: string
+ /**
+ * Time until which this group's notifications are muted. Must be in the future and at most 30 days away. Null clears the group's snooze. The group keeps being checked, and its firing stays open.
+ * @nullable
+ */
+ snooze_until: string | null
+}
+
export type PlatformAlertsListParams = {
/**
* Number of results to return per page.
diff --git a/products/alerts_platform/frontend/generated/api.ts b/products/alerts_platform/frontend/generated/api.ts
index 56486b9f09a5..351423d93dd5 100644
--- a/products/alerts_platform/frontend/generated/api.ts
+++ b/products/alerts_platform/frontend/generated/api.ts
@@ -11,8 +11,10 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
PaginatedPlatformAlertConfigurationListApi,
PatchedPlatformAlertConfigurationEditApi,
+ PlatformAlertApi,
PlatformAlertConfigurationApi,
PlatformAlertConfigurationEditApi,
+ PlatformAlertGroupSnoozeApi,
PlatformAlertsListParams,
} from './api.schemas'
@@ -93,3 +95,24 @@ export const platformAlertsPartialUpdate = async (
body: JSON.stringify(patchedPlatformAlertConfigurationEditApi),
})
}
+
+export const getPlatformAlertsSnoozeGroupCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/platform_alerts/${id}/snooze_group/`
+}
+
+/**
+ * @summary Snooze one group of a grouped alert
+ */
+export const platformAlertsSnoozeGroupCreate = async (
+ projectId: string,
+ id: string,
+ platformAlertGroupSnoozeApi: PlatformAlertGroupSnoozeApi,
+ options?: RequestInit
+): Promise<PlatformAlertApi> => {
+ return apiMutator<PlatformAlertApi>(getPlatformAlertsSnoozeGroupCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(platformAlertGroupSnoozeApi),
+ })
+}
diff --git a/products/alerts_platform/frontend/generated/api.zod.ts b/products/alerts_platform/frontend/generated/api.zod.ts
index 75fb53b932e6..2ad517a85ea2 100644
--- a/products/alerts_platform/frontend/generated/api.zod.ts
+++ b/products/alerts_platform/frontend/generated/api.zod.ts
@@ -318,3 +318,21 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod
.describe('Minimum minutes between notifications for the same alert.'),
})
.describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.')
+
+/**
+ * @summary Snooze one group of a grouped alert
+ */
+export const platformAlertsSnoozeGroupCreateBodyGroupingKeyMax = 255
+
+export const PlatformAlertsSnoozeGroupCreateBody = /* @__PURE__ */ zod.object({
+ grouping_key: zod
+ .string()
+ .max(platformAlertsSnoozeGroupCreateBodyGroupingKeyMax)
+ .describe("Key of the group to snooze, as the grouping_key of one of the alert's instances."),
+ snooze_until: zod.iso
+ .datetime({ offset: true })
+ .nullable()
+ .describe(
+ "Time until which this group's notifications are muted. Must be in the future and at most 30 days away. Null clears the group's snooze. The group keeps being checked, and its firing stays open."
+ ),
+})
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 3b261f412e17..d0727771d2b7 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -5,6 +5,7 @@ from typing import Any
from uuid import UUID, uuid4
import pytest
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -21,7 +22,13 @@ from posthog.models.team import Team
from posthog.temporal.alerts.admission import admit_evaluation_slots
from products.alerts_platform.backend.facade import testing as platform_testing
-from products.alerts_platform.backend.facade.api import due_checks, list_configurations, record_outcomes, slot_of
+from products.alerts_platform.backend.facade.api import (
+ due_checks,
+ list_configurations,
+ record_outcomes,
+ slot_of,
+ snooze_group,
+)
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
AlertEventKind,
@@ -469,6 +476,33 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert open_group is not None and open_group.state == "firing"
assert ungrouped is None
+ def test_a_snoozed_group_holds_its_resolve_while_the_other_group_announces(self) -> None:
+ configuration = self._configuration(owner="platform", grouping=_BY_SERVICE.to_stored())
+ self._add_incident_destination(configuration)
+ self._record(self._run_grouped(configuration, {"checkout": 500, "api": 500}))
+ checkout, api = (grouping_key_of({"service_name": service}) for service in ("checkout", "api"))
+ with time_machine.travel(self.cutoff, tick=False):
+ snooze_group(
+ team_id=self.team.id,
+ source_kinds=[SourceKind.LOGS.value],
+ configuration_id=configuration.id,
+ grouping_key=checkout,
+ snooze_until=self.cutoff + timedelta(hours=2),
+ )
+ with team_scope(self.team.id):
+ platform_testing.set_due_at(configuration.id, self.cutoff - timedelta(minutes=1))
+
+ cleared = self._run_grouped(configuration, {})
+
+ (outcome,) = cleared.outcomes
+ assert {g.grouping_key: (g.kind, g.muted_notification) for g in outcome.groups} == {
+ checkout: (AlertEventKind.CHECK, "resolve"),
+ api: (AlertEventKind.RESOLVED, ""),
+ }
+ # The snooze left the firing open, so the clear check closes the incident it opened.
+ (delivery,) = cleared.deliveries
+ assert delivery.incident_actions == {checkout: IncidentAction.RESOLVE, api: IncidentAction.RESOLVE}
+
@parameterized.expand(
[
("filter_group", {"condition": CONDITION, "filterGroup": {"type": "nonsense"}}),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6434a4743858..b14fa2f94302 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -89602,6 +89602,19 @@ export namespace Schemas {
export type PlatformAlertConfigurationEdit = LogsPlatformAlertConfigurationEdit;
+ export interface PlatformAlertGroupSnooze {
+ /**
+ * Key of the group to snooze, as the grouping_key of one of the alert's instances.
+ * @maxLength 255
+ */
+ grouping_key: string;
+ /**
+ * Time until which this group's notifications are muted. Must be in the future and at most 30 days away. Null clears the group's snooze. The group keeps being checked, and its firing stays open.
+ * @nullable
+ */
+ snooze_until: string | null;
+ }
+
/**
* * `running` - Running
* * `completed` - Completed