Skip to content

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

feat(logs): set a logs alert's grouping through the logs alert api (#119988)

Jimmy Zhu5a2c80773a99
diff --git a/products/alerts/frontend/AlertsScene.stories.tsx b/products/alerts/frontend/AlertsScene.stories.tsx
index 416b0c066ff0..59ce643951a9 100644
--- a/products/alerts/frontend/AlertsScene.stories.tsx
+++ b/products/alerts/frontend/AlertsScene.stories.tsx
@@ -123,6 +123,7 @@ const logAlerts = [
},
],
destination_types: ['slack'],
+ platform_owned: false,
first_enabled_at: '2026-07-10T15:00:00Z',
created_at: '2026-07-10T14:45:00Z',
created_by: createdBy,
@@ -156,6 +157,7 @@ const logAlerts = [
},
],
destination_types: [],
+ platform_owned: false,
first_enabled_at: '2026-07-12T10:00:00Z',
created_at: '2026-07-12T09:45:00Z',
created_by: createdBy,
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index be1c3bfd5aac..e5466b7614e8 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -356,6 +356,9 @@ class PlatformAlertUpsert:
snooze_until: datetime | None
recurrence_unit: str | None = None
anchor_time: str | None = None
+ # Written only when the upsert creates the copy. An existing copy keeps the grouping its own
+ # edits set, because a source row stores none.
+ grouping: Grouping = Grouping()
@frozen
@@ -395,12 +398,14 @@ class PlatformHandback:
@frozen
class PlatformAlertRuntime:
- """Where an alert the platform owns stands, for a source whose API still shows the alert."""
+ """Where an alert the platform owns stands, and how it splits into instances, for a source whose
+ API still shows the alert."""
state: PlatformAlertState
last_notified_at: datetime | None
consecutive_failures: int
next_check_at: datetime | None
+ grouping: Grouping
@frozen
diff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.py
index dc9f7d86ac3b..3b4852338a38 100644
--- a/products/alerts_platform/backend/facade/testing.py
+++ b/products/alerts_platform/backend/facade/testing.py
@@ -72,7 +72,12 @@ def count_still_due(configuration_ids: Iterable[UUID], *, at: datetime) -> int:
def start_firing(
- configuration_id: UUID, *, team_id: int, at: datetime, delivered_via: DeliveryPath | None = None
+ configuration_id: UUID,
+ *,
+ team_id: int,
+ at: datetime,
+ delivered_via: DeliveryPath | None = None,
+ grouping_key: str = "",
) -> None:
"""Put a configuration's instance inside a firing, as live delivery can leave one.
@@ -81,14 +86,14 @@ def start_firing(
PlatformAlert.objects.update_or_create(
team_id=team_id,
configuration_id=configuration_id,
- grouping_key="",
+ grouping_key=grouping_key,
defaults={"state": "firing", "firing_started_at": at},
)
if delivered_via is not None:
PlatformAlertDeliveryPath.objects.for_team(team_id).create(
team_id=team_id,
configuration_id=str(configuration_id),
- grouping_key="",
+ grouping_key=grouping_key,
episode_started_at=at,
path=delivered_via.value,
)
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 5a342a4167d5..8a4948954687 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -684,7 +684,9 @@ def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -
upsert.next_check_at or django_timezone.now(), django_timezone.now() + _REVIVE_FENCE
)
configuration, created = PlatformAlertConfiguration.objects.unscoped().update_or_create(
- legacy_configuration_id=upsert.legacy_configuration_id, defaults=defaults
+ legacy_configuration_id=upsert.legacy_configuration_id,
+ defaults=defaults,
+ create_defaults={**defaults, "grouping": upsert.grouping.to_stored()},
)
if revived:
PlatformAlert.objects.for_team(upsert.team_id).filter(configuration=configuration).update(
@@ -846,6 +848,8 @@ def take_ownership(handover: PlatformOwnershipHandover) -> bool:
row lock and writes the source's owner in the same transaction, so both rows change together.
Returns False, changing nothing, when the copy is inside a firing of its own: a team on live
delivery can have one open while its source is quiet, and replacing it would orphan the incident.
+ A grouped copy carries only the configuration's fields. Its source holds one state for the whole
+ alert, which no group inherits, and each group's row comes from the check that finds it.
Raises `PlatformAlertConfiguration.DoesNotExist` when the alert was never copied.
"""
if handover.state not in _HANDOVER_STATES:
@@ -856,10 +860,18 @@ def take_ownership(handover: PlatformOwnershipHandover) -> bool:
.select_for_update()
.get(legacy_configuration_id=handover.legacy_configuration_id)
)
- key = _InstanceKey(configuration_id=str(configuration.id), grouping_key="")
- alert = _alerts_for_write(handover.team_id, [configuration], [key])[key]
+ alert: PlatformAlert | None = None
+ if Grouping.from_stored(configuration.grouping).mode == GroupingMode.SINGLE:
+ key = _InstanceKey(configuration_id=str(configuration.id), grouping_key="")
+ alert = _alerts_for_write(handover.team_id, [configuration], [key])[key]
+ alerts = [alert]
+ else:
+ # No grouped check writes the empty key, so a row for it would only hold a slot of the cap.
+ alerts = _instances_by_configuration(handover.team_id, [configuration]).get(str(configuration.id), [])
# A failing check status means the machine already ended the firing the row still holds.
- live_firing = alert.state == PlatformAlertState.FIRING or alert.firing_started_at is not None
+ live_firing = any(
+ instance.state == PlatformAlertState.FIRING or instance.firing_started_at is not None for instance in alerts
+ )
if live_firing and configuration.check_status == PlatformAlertConfiguration.CheckStatus.OK:
return False
# ERRORED and BROKEN are the configuration's check status, so the instance starts at rest.
@@ -877,10 +889,11 @@ def take_ownership(handover: PlatformOwnershipHandover) -> bool:
update_fields=["owner", "owner_changed_at", "consecutive_failures", "next_check_at", "check_status"]
)
- alert.state = PlatformAlertState.NOT_FIRING if failing else handover.state
- alert.firing_started_at = None
- alert.last_notified_at = handover.last_notified_at
- alert.save(update_fields=["state", "firing_started_at", "last_notified_at"])
+ if alert is not None:
+ alert.state = PlatformAlertState.NOT_FIRING if failing else handover.state
+ alert.firing_started_at = None
+ alert.last_notified_at = handover.last_notified_at
+ alert.save(update_fields=["state", "firing_started_at", "last_notified_at"])
return True
@@ -899,7 +912,12 @@ def give_back_ownership(
if configuration.owner != PlatformAlertOwner.PLATFORM:
raise ValueError("the platform does not own this alert, so its owner disagrees with its source's")
alerts = list(PlatformAlert.objects.for_team(team_id).filter(configuration=configuration))
- if configuration.recurrence_unit is not None or any(alert.grouping_key for alert in alerts):
+ # A grouped copy with no group open yet still splits its results, which its source cannot do.
+ if (
+ configuration.recurrence_unit is not None
+ or Grouping.from_stored(configuration.grouping).mode != GroupingMode.SINGLE
+ or any(alert.grouping_key for alert in alerts)
+ ):
return HandbackRefusal.NOT_PORTABLE
alert = alerts[0] if alerts else None
if alert is not None and (alert.state == PlatformAlertState.FIRING or alert.firing_started_at is not None):
diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.py
index 2e1f88b8613b..be0de0f70563 100644
--- a/products/alerts_platform/backend/logic/platform_reads.py
+++ b/products/alerts_platform/backend/logic/platform_reads.py
@@ -8,7 +8,7 @@ from collections.abc import Collection, Sequence
from datetime import datetime
from uuid import UUID
-from django.db.models import OuterRef, Prefetch, QuerySet, Subquery
+from django.db.models import Case, Exists, Max, OuterRef, Prefetch, QuerySet, Subquery, Value, When
from products.alerts_platform.backend.facade.contracts import (
Grouping,
@@ -132,18 +132,26 @@ def runtime_by_legacy_id(
"""The runtime state of each named alert the platform owns, keyed by the source's id, in one query.
An alert the platform does not own is left out, because its source's own row is then the one
- that moves. Only the ungrouped instance is read: a source that shows one state per alert has
- no groups, and a copy with no instance yet has not been checked since the handover.
+ that moves. A source shows one state per alert, so a grouped alert fires while any of its groups
+ fires, and was last notified when any group last was. A copy with no instance yet has not been
+ checked since the handover.
"""
if not legacy_configuration_ids:
return {}
- ungrouped = PlatformAlert.objects.for_team(team_id).filter(configuration=OuterRef("pk"), grouping_key="")
+ instances = PlatformAlert.objects.for_team(team_id).filter(configuration=OuterRef("pk"))
+ latest_notified = instances.order_by().values("configuration").annotate(at=Max("last_notified_at")).values("at")
rows = (
PlatformAlertConfiguration.objects.for_team(team_id)
.filter(legacy_configuration_id__in=list(legacy_configuration_ids), owner=PlatformAlertOwner.PLATFORM)
.annotate(
- instance_state=Subquery(ungrouped.values("state")[:1]),
- instance_last_notified_at=Subquery(ungrouped.values("last_notified_at")[:1]),
+ instance_state=Case(
+ When(
+ Exists(instances.filter(state=PlatformAlertState.FIRING)),
+ then=Value(PlatformAlertState.FIRING.value),
+ ),
+ default=Subquery(instances.filter(grouping_key="").values("state")[:1]),
+ ),
+ instance_last_notified_at=Subquery(latest_notified),
)
.values_list(
"legacy_configuration_id",
@@ -152,6 +160,7 @@ def runtime_by_legacy_id(
"instance_last_notified_at",
"consecutive_failures",
"next_check_at",
+ "grouping",
)
)
return {
@@ -167,8 +176,9 @@ def runtime_by_legacy_id(
last_notified_at=last_notified_at,
consecutive_failures=consecutive_failures,
next_check_at=next_check_at,
+ grouping=Grouping.from_stored(grouping),
)
- for legacy_id, state, check_status, last_notified_at, consecutive_failures, next_check_at in rows
+ for legacy_id, state, check_status, last_notified_at, consecutive_failures, next_check_at, grouping in rows
if legacy_id is not None
}
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index 87c8bb4ad78e..6b99674cc8df 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -175,6 +175,35 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
assert taken is expected_taken
assert (self.configuration.owner, alert.state, alert.firing_started_at is not None) == expected
+ def test_a_grouped_copy_taken_over_leaves_its_one_slot_to_the_first_group(self) -> None:
+ legacy_id = uuid4()
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(id=self.configuration.id).update(
+ legacy_configuration_id=legacy_id,
+ grouping=Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service",), max_instances=1).to_stored(),
+ )
+ take_ownership(
+ PlatformOwnershipHandover(
+ legacy_configuration_id=legacy_id,
+ team_id=self.team.id,
+ state=PlatformAlertState.NOT_FIRING,
+ last_notified_at=None,
+ consecutive_failures=0,
+ next_check_at=self.cutoff - timedelta(minutes=1),
+ at=self.cutoff - timedelta(minutes=5),
+ )
+ )
+
+ self._record(
+ groups=(GroupOutcome(grouping_key="api", kind=AlertEventKind.FIRING, new_state="firing", notified=True),)
+ )
+
+ with team_scope(self.team.id):
+ instances = list(
+ PlatformAlert.objects.filter(configuration=self.configuration).values_list("grouping_key", "state")
+ )
+ assert instances == [("api", "firing")]
+
@parameterized.expand(
[
("firing", {}, {"state": "firing"}, HandbackRefusal.FIRING),
@@ -204,6 +233,12 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
HandbackRefusal.NOT_PORTABLE,
),
("grouped", {}, {"grouping_key": "service=api"}, HandbackRefusal.NOT_PORTABLE),
+ (
+ "grouped_with_no_group_open",
+ {"grouping": {"mode": "by_result_labels", "keys": ["service_name"]}},
+ {},
+ HandbackRefusal.NOT_PORTABLE,
+ ),
]
)
def test_the_platform_keeps_an_alert_its_source_cannot_take_back(
diff --git a/products/logs/backend/facade/platform_ownership.py b/products/logs/backend/facade/platform_ownership.py
index 8539006648b4..a3956ced378f 100644
--- a/products/logs/backend/facade/platform_ownership.py
+++ b/products/logs/backend/facade/platform_ownership.py
@@ -6,6 +6,7 @@ Each call reads the logs row by id inside the caller's transaction, after the ca
from datetime import datetime
from uuid import UUID
+from products.alerts_platform.backend.facade.contracts import Grouping
from products.logs.backend import platform_ownership
from products.logs.backend.models import LogsAlertConfiguration
@@ -16,21 +17,27 @@ def _alert(team_id: int, alert_id: UUID) -> LogsAlertConfiguration | None:
return LogsAlertConfiguration.objects.filter(team_id=team_id, id=alert_id).first()
-def on_created(*, team_id: int, alert_id: UUID, at: datetime) -> bool:
- """Hands a new alert to the platform when its team has begun the cutover. False when the alert
- stays with logs."""
+def on_created(*, team_id: int, alert_id: UUID, at: datetime, grouping: Grouping | None = None) -> bool:
+ """Hands a new alert to the platform when its team has begun the cutover, with its copy grouped
+ by `grouping`. False when the alert stays with logs.
+
+ Raises `InvalidPlatformAlertEdit` when the alert cannot take the grouping. Only an alert the
+ platform owns can take one other than single.
+ """
alert = _alert(team_id, alert_id)
- return alert is not None and platform_ownership.on_created(alert, at)
+ return alert is not None and platform_ownership.on_created(alert, at, grouping=grouping)
-def on_updated(*, team_id: int, alert_id: UUID, snooze_changed: bool) -> None:
- """Writes an edit the logs API saved onto the platform's copy.
+def on_updated(*, team_id: int, alert_id: UUID, snooze_changed: bool, grouping: Grouping | None = None) -> None:
+ """Writes an edit the logs API saved onto the platform's copy, with the grouping the edit set.
+ A `grouping` of None keeps the copy's own.
- Raises `InvalidPlatformAlertEdit` when the platform's schema rejects the edit.
+ Raises `InvalidPlatformAlertEdit` when the platform's schema rejects the edit, or when the
+ alert cannot take the grouping. Only an alert the platform owns can take one other than single.
"""
alert = _alert(team_id, alert_id)
if alert is not None:
- platform_ownership.on_updated(alert, snooze_changed=snooze_changed)
+ platform_ownership.on_updated(alert, snooze_changed=snooze_changed, grouping=grouping)
def on_deleted(*, team_id: int, alert_id: UUID) -> None:
diff --git a/products/logs/backend/platform_cutover.py b/products/logs/backend/platform_cutover.py
index a8c5ac6262e9..9cb7d43806ff 100644
--- a/products/logs/backend/platform_cutover.py
+++ b/products/logs/backend/platform_cutover.py
@@ -6,6 +6,7 @@ skipped with a reason, and a later run picks it up. The command is safe to run a
from __future__ import annotations
+from dataclasses import replace
from datetime import datetime
from enum import StrEnum
from uuid import UUID
@@ -16,7 +17,7 @@ from django.utils import timezone
from posthog.dataclasses import frozen
from products.alerts_platform.backend.facade.api import give_back_ownership, take_ownership, upsert_configuration
-from products.alerts_platform.backend.facade.contracts import HandbackRefusal, PlatformOwnershipHandover
+from products.alerts_platform.backend.facade.contracts import Grouping, HandbackRefusal, PlatformOwnershipHandover
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
from products.logs.backend.alert_state_machine import FIRING_STATES, ControlPlaneOutcome, apply_outcome
from products.logs.backend.alert_utils import due_alerts_q
@@ -166,11 +167,14 @@ def in_an_environment(alert: LogsAlertConfiguration) -> bool:
return alert.team.parent_team_id is not None
-def hand_over(alert: LogsAlertConfiguration, at: datetime) -> bool:
+def hand_over(alert: LogsAlertConfiguration, at: datetime, *, grouping: Grouping | None = None) -> bool:
"""Copies a logs alert locked by the caller onto the platform and makes the platform its owner,
- on both rows. False, changing nothing, when the platform copy is inside a firing of its own."""
+ on both rows. False, changing nothing, when the platform copy is inside a firing of its own.
+
+ `grouping` applies only to a copy this creates, because the logs row stores none."""
+ upsert = platform_upsert_of(alert)
savepoint = transaction.savepoint()
- upsert_configuration(platform_upsert_of(alert))
+ upsert_configuration(upsert if grouping is None else replace(upsert, grouping=grouping))
taken = take_ownership(
PlatformOwnershipHandover(
legacy_configuration_id=alert.id,
diff --git a/products/logs/backend/platform_ownership.py b/products/logs/backend/platform_ownership.py
index ff75a2fcc565..0946489dc2c1 100644
--- a/products/logs/backend/platform_ownership.py
+++ b/products/logs/backend/platform_ownership.py
@@ -8,6 +8,7 @@ the other in the same transaction, and every writer locks the logs row before th
from collections.abc import Callable
from dataclasses import replace
from datetime import datetime
+from typing import Final
from uuid import UUID
from django.utils import timezone
@@ -15,9 +16,13 @@ from django.utils import timezone
from products.alerts_platform.backend.facade.api import close_owned_firings_now, delete_owned_copy, update_owned_copy
from products.alerts_platform.backend.facade.contracts import (
SOURCE_CONDITION_KEY,
+ Grouping,
+ GroupingMode,
+ InvalidPlatformAlertEdit,
PlatformAlertConfigurationEdit,
PlatformAlertNotEditable,
)
+from products.logs.backend.alert_group_columns import grouping_problem
from products.logs.backend.alert_state_machine import apply_enabled
from products.logs.backend.facade.api import close_incident_before_delete
from products.logs.backend.models import LogsAlertConfiguration
@@ -25,22 +30,49 @@ from products.logs.backend.platform_alert_backfill import CONDITION_FIELDS, SETT
from products.logs.backend.platform_cutover import hand_over, has_begun_cutover, in_an_environment
from products.logs.backend.platform_source_config import filters_of
+GROUPING_NOT_AVAILABLE: Final = "Grouping isn't available for this alert yet. Set the mode to single to save it."
-def on_created(alert: LogsAlertConfiguration, at: datetime) -> bool:
- """Hands a new alert to the platform when its team has begun the cutover, so the team never has
- to be cut over again for it. False when the alert stays with logs."""
- return not in_an_environment(alert) and has_begun_cutover(alert.team_id) and hand_over(alert, at)
+
+def _refuse_grouping_on_logs(grouping: Grouping | None) -> None:
+ # The logs stack cannot group. A single grouping is what the API reads for such an alert, so a
+ # client that sends back what it read still saves.
+ if grouping is not None and grouping.mode != GroupingMode.SINGLE:
+ raise InvalidPlatformAlertEdit("grouping", GROUPING_NOT_AVAILABLE)
-def on_updated(alert: LogsAlertConfiguration, *, snooze_changed: bool) -> None:
- """Writes an edit the logs API saved onto the platform's copy.
+def on_created(alert: LogsAlertConfiguration, at: datetime, *, grouping: Grouping | None = None) -> bool:
+ """Hands a new alert to the platform when its team has begun the cutover, so the team never has
+ to be cut over again for it, and creates the copy with `grouping`. False when the alert stays
+ with logs.
- Raises `InvalidPlatformAlertEdit` when the platform's schema rejects the edit.
+ Raises `InvalidPlatformAlertEdit` when the alert cannot take the grouping.
"""
+ grouping = grouping if grouping is not None else Grouping()
+ if in_an_environment(alert) or not has_begun_cutover(alert.team_id):
+ _refuse_grouping_on_logs(grouping)
+ return False
+ if grouping.mode != GroupingMode.SINGLE and (problem := grouping_problem(grouping.keys, alert.threshold_operator)):
+ raise InvalidPlatformAlertEdit("grouping", problem)
+ if hand_over(alert, at, grouping=grouping):
+ return True
+ _refuse_grouping_on_logs(grouping)
+ return False
+
+
+def on_updated(alert: LogsAlertConfiguration, *, snooze_changed: bool, grouping: Grouping | None = None) -> None:
+ """Writes an edit the logs API saved onto the platform's copy, with the grouping the edit set.
+ A `grouping` of None keeps the copy's own. An alert logs owns has no copy to write.
+
+ Raises `InvalidPlatformAlertEdit` when the platform's schema rejects the edit, or when the
+ alert cannot take the grouping.
+ """
+ if not alert.platform_owned:
+ _refuse_grouping_on_logs(grouping)
+ return
update_owned_copy(
team_id=alert.team_id,
legacy_configuration_id=alert.id,
- change=_platform_change_of(alert),
+ change=_platform_change_of(alert, grouping),
snooze_until=alert.snooze_until,
snooze_changed=snooze_changed,
)
@@ -51,13 +83,15 @@ def on_deleted(*, team_id: int, alert_id: UUID) -> None:
def _platform_change_of(
- alert: LogsAlertConfiguration,
+ alert: LogsAlertConfiguration, grouping: Grouping | None
) -> Callable[[PlatformAlertConfigurationEdit], PlatformAlertConfigurationEdit]:
- # Only the settings a logs alert has. The platform's own, such as grouping, keep what the copy
- # stores, so an edit through the logs API never resets them.
+ # Only the settings a logs alert has, and a grouping the edit named. The logs row has no grouping,
+ # so an edit that names none keeps what the copy stores rather than resetting it.
upsert = platform_upsert_of(alert)
shared = {field: getattr(upsert, field) for field in SETTINGS_FIELDS}
- return lambda stored: replace(stored, enabled=upsert.enabled, **shared)
+ return lambda stored: replace(
+ stored, enabled=upsert.enabled, grouping=grouping if grouping is not None else stored.grouping, **shared
+ )
def mirror_platform_edit(
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index 3bcc6891fc90..fecb0cf27ab0 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -1,6 +1,6 @@
import os
import datetime as dt
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
from datetime import UTC, datetime
from typing import Any, Final, Literal, TypedDict, cast, overload
from uuid import UUID
@@ -53,6 +53,7 @@ from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertDestinationValidationError,
DestinationType,
+ Grouping,
InvalidPlatformAlertEdit,
PagerDutyRegion,
PagerDutySeverity,
@@ -61,6 +62,7 @@ from products.alerts_platform.backend.facade.contracts import (
)
from products.alerts_platform.backend.facade.enums import PlatformAlertState
from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_restriction
+from products.alerts_platform.backend.presentation.views.platform_alert import GroupingSerializer
from products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionField
from products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCount
from products.logs.backend.alert_destinations import (
@@ -129,6 +131,7 @@ STATE_TIMELINE_LOOKBACK_HOURS = 24
DEFAULT_CHECK_INTERVAL_MINUTES = 5
_SENTINEL: Final = object()
_NOT_ANNOTATED: Final = object()
+_SINGLE_INSTANCE: Final = Grouping()
def _any_field_changed(instance: LogsAlertConfiguration, validated_data: dict, fields: set[str]) -> bool:
@@ -293,6 +296,15 @@ class _TimelineEvent:
state_after: str
+class LogsAlertGroupingSerializer(GroupingSerializer):
+ """How a logs alert splits its results into instances."""
+
+ # The logs row has no grouping column. Every alert reads as single here, and `to_representation`
+ # of the alert serializer replaces it with the platform copy's grouping for an alert the platform owns.
+ def get_attribute(self, instance: LogsAlertConfiguration) -> Grouping:
+ return _SINGLE_INSTANCE
+
+
class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(
read_only=True,
@@ -427,6 +439,24 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
"after creating an alert."
),
)
+ grouping = LogsAlertGroupingSerializer(
+ required=False,
+ help_text=(
+ "How the alert splits its results into instances. Mode single keeps one instance for the whole "
+ "alert. Mode by_result_labels with keys service_name and/or severity_text keeps one instance per "
+ "service or severity, each firing and resolving on its own, and needs threshold_operator above. "
+ "Only an alert the alerts platform evaluates can group. Any other alert reads as single and "
+ "rejects a different value. Omit it on update to keep the current grouping. Changing the keys "
+ "deletes the existing instances and closes their notification threads without a message."
+ ),
+ )
+ platform_owned = serializers.BooleanField(
+ read_only=True,
+ help_text=(
+ "Whether the alerts platform evaluates this alert and sends its notifications. Only such an "
+ "alert can set a grouping other than single."
+ ),
+ )
@extend_schema_field(LogsAlertStateIntervalSerializer(many=True))
def get_state_timeline(self, obj: LogsAlertConfiguration) -> list[StateInterval]:
@@ -646,6 +676,7 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
runtime.state, logs_state=instance.state, snooze_until=instance.snooze_until, at=timezone.now()
).value
data["consecutive_failures"] = runtime.consecutive_failures
+ data["grouping"] = self.fields["grouping"].to_representation(runtime.grouping)
data["next_check_at"] = self.fields["next_check_at"].to_representation(runtime.next_check_at)
data["last_notified_at"] = self.fields["last_notified_at"].to_representation(runtime.last_notified_at)
@@ -688,6 +719,8 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
"last_error_message",
"state_timeline",
"destination_types",
+ "grouping",
+ "platform_owned",
"first_enabled_at",
"created_at",
"created_by",
@@ -704,6 +737,7 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
"last_error_message",
"state_timeline",
"destination_types",
+ "platform_owned",
"first_enabled_at",
"created_at",
"created_by",
@@ -754,6 +788,7 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
validated_data["name"] = "Untitled alert"
snooze_data = validated_data.pop("snooze_until", _SENTINEL)
+ grouping: Grouping | None = validated_data.pop("grouping", None)
threshold_or_filter_fields = {
"threshold_count",
@@ -832,14 +867,15 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
instance.clear_next_check()
updated = super().update(instance, validated_data)
- if updated.platform_owned:
- try:
- on_updated(
- team_id=updated.team_id, alert_id=updated.id, snooze_changed=snooze_data is not _SENTINEL
- )
- except InvalidPlatformAlertEdit as error:
- raise ValidationError({error.field_name: str(error)}) from error
- elif enabled_change is True:
+ _write_platform_edit(
+ lambda: on_updated(
+ team_id=updated.team_id,
+ alert_id=updated.id,
+ snooze_changed=snooze_data is not _SENTINEL,
+ grouping=grouping,
+ )
+ )
+ if not updated.platform_owned and enabled_change is True:
transaction.on_commit(
lambda: follow_logs_alert(team_id=updated.team_id, alert_id=updated.id), robust=True
)
@@ -854,6 +890,7 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
if validated_data.get("enabled", True):
validated_data["first_enabled_at"] = timezone.now()
+ grouping: Grouping | None = validated_data.pop("grouping", None)
with transaction.atomic():
# select_for_update().count() doesn't acquire row locks because
@@ -871,7 +908,10 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
schedule_restriction=schedule_restriction,
)
created = super().create(validated_data)
- if on_created(team_id=created.team_id, alert_id=created.id, at=timezone.now()):
+ # Raised inside the transaction, so a grouping the alert cannot take leaves no alert behind.
+ if _write_platform_edit(
+ lambda: on_created(team_id=created.team_id, alert_id=created.id, at=timezone.now(), grouping=grouping)
+ ):
created.refresh_from_db(fields=["owner", "owner_changed_at"])
elif created.enabled:
transaction.on_commit(
@@ -880,6 +920,13 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
return created
+def _write_platform_edit[T](write: Callable[[], T]) -> T:
+ try:
+ return write()
+ except InvalidPlatformAlertEdit as error:
+ raise ValidationError({error.field_name: str(error)}) from error
+
+
def _validate_filters(filters: dict) -> None:
"""Cross-field requirement that at least one filter is present.
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index 9b7e0839c599..51413e00460e 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -2455,9 +2455,118 @@ class TestLogsAlertAPI(APIBaseTest):
created = self._create_via_api(name="Added after the cutover")
+ assert created["platform_owned"] is True
assert LogsAlertConfiguration.objects.get(pk=created["id"]).platform_owned
assert self._copy(created["id"]).owner == "platform"
+ def _copy_grouping_keys(self, alert_id: str) -> tuple[str, ...]:
+ with team_scope(self.team.id):
+ view = get_configuration(
+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], configuration_id=self._copy(alert_id).id
+ )
+ assert view is not None
+ return view.grouping.keys
+
+ def test_grouping_set_on_the_logs_page_regroups_the_platform_copy(self) -> None:
+ created, copy = self._firing_on_the_platform_with_pagerduty()
+
+ temporal = MagicMock(start_workflow=AsyncMock())
+
+ with (
+ patch(f"{_WEB_START}.async_connect", AsyncMock(return_value=temporal)),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ response = self.client.patch(
+ f"{self.base_url}{created['id']}/",
+ {"grouping": {"mode": "by_result_labels", "keys": ["service_name"]}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ (delivery,) = [call.args[1] for call in temporal.start_workflow.call_args_list]
+ assert delivery.incident_actions == {"": IncidentAction.RESOLVE}
+ assert response.json()["grouping"]["keys"] == ["service_name"]
+ assert self._copy_grouping_keys(created["id"]) == ("service_name",)
+ with team_scope(self.team.id):
+ assert platform_testing.alert_for(copy.id) is None
+ platform_testing.start_firing(
+ copy.id, team_id=self.team.id, at=datetime.now(UTC), grouping_key='{"service_name":"api"}'
+ )
+ assert self.client.get(f"{self.base_url}{created['id']}/").json()["state"] == "firing"
+
+ @parameterized.expand(
+ [
+ ("cut_over", True, "severity_text", status.HTTP_201_CREATED),
+ ("not_cut_over", False, "severity_text", status.HTTP_400_BAD_REQUEST),
+ ("cut_over_unknown_key", True, "host", status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_creating_a_grouped_alert(self, _name: str, cut_over: bool, key: str, expected_status: int) -> None:
+ if cut_over:
+ self._owned_by_the_platform()
+ alerts_before = LogsAlertConfiguration.objects.filter(team=self.team).count()
+
+ response = self.client.post(
+ self.base_url,
+ self._valid_payload(name="Grouped", grouping={"mode": "by_result_labels", "keys": [key]}),
+ format="json",
+ )
+
+ assert response.status_code == expected_status, response.json()
+ if expected_status == status.HTTP_201_CREATED:
+ assert self._copy_grouping_keys(response.json()["id"]) == (key,)
+ else:
+ assert response.json()["attr"] == "grouping"
+ assert LogsAlertConfiguration.objects.filter(team=self.team).count() == alerts_before
+
+ @parameterized.expand(
+ [
+ ("source_owned_grouped", False, {"grouping": {"mode": "by_result_labels", "keys": ["service_name"]}}),
+ ("unknown_key", True, {"grouping": {"mode": "by_result_labels", "keys": ["host"]}}),
+ (
+ "below_threshold",
+ True,
+ {"grouping": {"mode": "by_result_labels", "keys": ["service_name"]}, "threshold_operator": "below"},
+ ),
+ ]
+ )
+ def test_a_grouping_the_alert_cannot_take_is_rejected(
+ self, _name: str, platform_owned: bool, payload: dict
+ ) -> None:
+ created = self._owned_by_the_platform() if platform_owned else self._create_via_api()
+
+ response = self.client.patch(f"{self.base_url}{created['id']}/", payload, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "grouping"
+ assert LogsAlertConfiguration.objects.get(pk=created["id"]).threshold_operator == "above"
+ if platform_owned:
+ assert self._copy_grouping_keys(created["id"]) == ()
+
+ @parameterized.expand(
+ [
+ ("as_read", None),
+ ("with_its_own_cap", {"mode": "single", "max_instances": 50}),
+ ]
+ )
+ def test_a_source_owned_alert_accepts_the_single_grouping_it_reads(self, _name: str, grouping: dict | None) -> None:
+ created = self._create_via_api()
+
+ response = self.client.put(
+ f"{self.base_url}{created['id']}/",
+ self._valid_payload(grouping=grouping or created["grouping"]),
+ format="json",
+ )
+
+ assert created["grouping"] == {
+ "mode": "single",
+ "keys": [],
+ "max_instances": 100,
+ "on_overflow": "degrade_visible",
+ }
+ assert created["platform_owned"] is False
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
def test_turning_a_broken_platform_alert_off_and_on_on_the_logs_page_revives_it(self) -> None:
created = self._owned_by_the_platform()
with team_scope(self.team.id):
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
index 22396ad70913..c2be901decb3 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertFormLogic.test.ts
@@ -53,6 +53,7 @@ const MOCK_ALERT: LogsAlertConfigurationApi = {
consecutive_failures: 0,
last_error_message: null,
destination_types: [],
+ platform_owned: false,
state_timeline: [],
first_enabled_at: null,
created_at: '2024-01-01T00:00:00Z',
diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts
index 7b4b65f00b33..1c0c5f85f50f 100644
--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts
+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts
@@ -65,6 +65,7 @@ const MOCK_ALERT: LogsAlertConfigurationApi = {
last_error_message: null,
state_timeline: [],
destination_types: [],
+ platform_owned: false,
first_enabled_at: null,
created_at: '2026-08-12T12:00:00.000Z',
created_by: {
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 1e14b563b745..15ee75984750 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -517,6 +517,49 @@ export const LogsAlertDestinationTypeEnumApi = {
Pagerduty: 'pagerduty',
} as const
+/**
+ * * `single` - Single
+ * * `by_result_labels` - By result labels
+ */
+export type GroupingModeEnumApi = (typeof GroupingModeEnumApi)[keyof typeof GroupingModeEnumApi]
+
+export const GroupingModeEnumApi = {
+ Single: 'single',
+ ByResultLabels: 'by_result_labels',
+} as const
+
+/**
+ * * `degrade_visible` - Degrade visible
+ */
+export type OnOverflowEnumApi = (typeof OnOverflowEnumApi)[keyof typeof OnOverflowEnumApi]
+
+export const OnOverflowEnumApi = {
+ DegradeVisible: 'degrade_visible',
+} as const
+
+/**
+ * How a logs alert splits its results into instances.
+ */
+export interface LogsAlertGroupingApi {
+ /** single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.
+ *
+ * * `single` - Single
+ * * `by_result_labels` - By result labels */
+ mode: GroupingModeEnumApi
+ /** Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message. */
+ keys?: string[]
+ /**
+ * Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.
+ * @minimum 1
+ * @maximum 100
+ */
+ max_instances?: number
+ /** What happens to groups past max_instances. degrade_visible names how many were left out.
+ *
+ * * `degrade_visible` - Degrade visible */
+ on_overflow?: OnOverflowEnumApi
+}
+
/**
* * `engineering` - Engineering
* * `data` - Data
@@ -659,6 +702,10 @@ export interface LogsAlertConfigurationApi {
readonly state_timeline: readonly LogsAlertStateIntervalApi[]
/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */
readonly destination_types: readonly LogsAlertDestinationTypeEnumApi[]
+ /** How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message. */
+ grouping?: LogsAlertGroupingApi
+ /** Whether the alerts platform evaluates this alert and sends its notifications. Only such an alert can set a grouping other than single. */
+ readonly platform_owned: boolean
/**
* When the alert was first enabled. Null means the alert is still in draft state.
* @nullable
@@ -831,6 +878,10 @@ export interface LogsAlertConfigurationDetailApi {
readonly state_timeline: readonly LogsAlertStateIntervalApi[]
/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */
readonly destination_types: readonly LogsAlertDestinationTypeEnumApi[]
+ /** How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message. */
+ grouping?: LogsAlertGroupingApi
+ /** Whether the alerts platform evaluates this alert and sends its notifications. Only such an alert can set a grouping other than single. */
+ readonly platform_owned: boolean
/**
* When the alert was first enabled. Null means the alert is still in draft state.
* @nullable
@@ -933,6 +984,10 @@ export interface PatchedLogsAlertConfigurationApi {
readonly state_timeline?: readonly LogsAlertStateIntervalApi[]
/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */
readonly destination_types?: readonly LogsAlertDestinationTypeEnumApi[]
+ /** How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message. */
+ grouping?: LogsAlertGroupingApi
+ /** Whether the alerts platform evaluates this alert and sends its notifications. Only such an alert can set a grouping other than single. */
+ readonly platform_owned?: boolean
/**
* When the alert was first enabled. Null means the alert is still in draft state.
* @nullable
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index e45a4a35e690..184e6daaa3be 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -68,6 +68,11 @@ export const logsAlertsCreateBodyDatapointsToAlarmMax = 10
export const logsAlertsCreateBodyCooldownMinutesDefault = 0
export const logsAlertsCreateBodyCooldownMinutesMin = 0
+export const logsAlertsCreateBodyGroupingOneMaxInstancesDefault = 100
+export const logsAlertsCreateBodyGroupingOneMaxInstancesMax = 100
+
+export const logsAlertsCreateBodyGroupingOneOnOverflowDefault = `degrade_visible`
+
export const LogsAlertsCreateBody = /* @__PURE__ */ zod.object({
name: zod
.string()
@@ -173,6 +178,41 @@ export const LogsAlertsCreateBody = /* @__PURE__ */ zod.object({
.datetime({ offset: true })
.nullish()
.describe('ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.'),
+ grouping: zod
+ .object({
+ mode: zod
+ .enum(['single', 'by_result_labels'])
+ .describe('\* `single` - Single\n\* `by_result_labels` - By result labels')
+ .describe(
+ 'single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n\* `single` - Single\n\* `by_result_labels` - By result labels'
+ ),
+ keys: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.'
+ ),
+ max_instances: zod
+ .number()
+ .min(1)
+ .max(logsAlertsCreateBodyGroupingOneMaxInstancesMax)
+ .default(logsAlertsCreateBodyGroupingOneMaxInstancesDefault)
+ .describe(
+ 'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
+ ),
+ on_overflow: zod
+ .enum(['degrade_visible'])
+ .describe('\* `degrade_visible` - Degrade visible')
+ .default(logsAlertsCreateBodyGroupingOneOnOverflowDefault)
+ .describe(
+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
+ ),
+ })
+ .describe('How a logs alert splits its results into instances.')
+ .optional()
+ .describe(
+ 'How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and\/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message.'
+ ),
})
export const logsAlertsUpdateBodyNameMax = 255
@@ -192,6 +232,11 @@ export const logsAlertsUpdateBodyDatapointsToAlarmMax = 10
export const logsAlertsUpdateBodyCooldownMinutesDefault = 0
export const logsAlertsUpdateBodyCooldownMinutesMin = 0
+export const logsAlertsUpdateBodyGroupingOneMaxInstancesDefault = 100
+export const logsAlertsUpdateBodyGroupingOneMaxInstancesMax = 100
+
+export const logsAlertsUpdateBodyGroupingOneOnOverflowDefault = `degrade_visible`
+
export const LogsAlertsUpdateBody = /* @__PURE__ */ zod.object({
name: zod
.string()
@@ -297,6 +342,41 @@ export const LogsAlertsUpdateBody = /* @__PURE__ */ zod.object({
.datetime({ offset: true })
.nullish()
.describe('ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.'),
+ grouping: zod
+ .object({
+ mode: zod
+ .enum(['single', 'by_result_labels'])
+ .describe('\* `single` - Single\n\* `by_result_labels` - By result labels')
+ .describe(
+ 'single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n\* `single` - Single\n\* `by_result_labels` - By result labels'
+ ),
+ keys: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.'
+ ),
+ max_instances: zod
+ .number()
+ .min(1)
+ .max(logsAlertsUpdateBodyGroupingOneMaxInstancesMax)
+ .default(logsAlertsUpdateBodyGroupingOneMaxInstancesDefault)
+ .describe(
+ 'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
+ ),
+ on_overflow: zod
+ .enum(['degrade_visible'])
+ .describe('\* `degrade_visible` - Degrade visible')
+ .default(logsAlertsUpdateBodyGroupingOneOnOverflowDefault)
+ .describe(
+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
+ ),
+ })
+ .describe('How a logs alert splits its results into instances.')
+ .optional()
+ .describe(
+ 'How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and\/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message.'
+ ),
})
export const logsAlertsPartialUpdateBodyNameMax = 255
@@ -316,6 +396,11 @@ export const logsAlertsPartialUpdateBodyDatapointsToAlarmMax = 10
export const logsAlertsPartialUpdateBodyCooldownMinutesDefault = 0
export const logsAlertsPartialUpdateBodyCooldownMinutesMin = 0
+export const logsAlertsPartialUpdateBodyGroupingOneMaxInstancesDefault = 100
+export const logsAlertsPartialUpdateBodyGroupingOneMaxInstancesMax = 100
+
+export const logsAlertsPartialUpdateBodyGroupingOneOnOverflowDefault = `degrade_visible`
+
export const LogsAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
name: zod
.string()
@@ -421,6 +506,41 @@ export const LogsAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
.datetime({ offset: true })
.nullish()
.describe('ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.'),
+ grouping: zod
+ .object({
+ mode: zod
+ .enum(['single', 'by_result_labels'])
+ .describe('\* `single` - Single\n\* `by_result_labels` - By result labels')
+ .describe(
+ 'single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n\* `single` - Single\n\* `by_result_labels` - By result labels'
+ ),
+ keys: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.'
+ ),
+ max_instances: zod
+ .number()
+ .min(1)
+ .max(logsAlertsPartialUpdateBodyGroupingOneMaxInstancesMax)
+ .default(logsAlertsPartialUpdateBodyGroupingOneMaxInstancesDefault)
+ .describe(
+ 'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
+ ),
+ on_overflow: zod
+ .enum(['degrade_visible'])
+ .describe('\* `degrade_visible` - Degrade visible')
+ .default(logsAlertsPartialUpdateBodyGroupingOneOnOverflowDefault)
+ .describe(
+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
+ ),
+ })
+ .describe('How a logs alert splits its results into instances.')
+ .optional()
+ .describe(
+ 'How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and\/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message.'
+ ),
})
/**
diff --git a/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts b/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
index 811429341cac..395d465744ed 100644
--- a/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/__tests__/logsAlertDetailSceneLogic.test.ts
@@ -49,6 +49,7 @@ const MOCK_ALERT: LogsAlertConfigurationApi = {
consecutive_failures: 0,
last_error_message: null,
destination_types: ['slack'],
+ platform_owned: false,
state_timeline: [],
first_enabled_at: null,
created_at: '2024-01-01T00:00:00Z',
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index d853840a4bf1..422d536d5608 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -47,6 +47,8 @@ tools:
- cooldown_minutes
- schedule_restriction
- snooze_until
+ - grouping
+ - platform_owned
- next_check_at
- last_notified_at
- last_checked_at
@@ -171,6 +173,8 @@ tools:
- threshold_operator
- window_minutes
- schedule_restriction
+ - grouping
+ - platform_owned
- created_at
- updated_at
logs-alerts-partial-update:
@@ -213,6 +217,8 @@ tools:
- cooldown_minutes
- schedule_restriction
- snooze_until
+ - grouping
+ - platform_owned
- next_check_at
- last_notified_at
- last_checked_at
@@ -249,6 +255,8 @@ tools:
- cooldown_minutes
- schedule_restriction
- snooze_until
+ - grouping
+ - platform_owned
- next_check_at
- last_notified_at
- last_checked_at
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d134c9a19bf8..a7736ea3589d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -64118,6 +64118,29 @@ export namespace Schemas {
Pagerduty: 'pagerduty',
} as const;
+ /**
+ * How a logs alert splits its results into instances.
+ */
+ export interface LogsAlertGrouping {
+ /** single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.
+ *
+ * * `single` - Single
+ * * `by_result_labels` - By result labels */
+ mode: GroupingModeEnum;
+ /** Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message. */
+ keys?: string[];
+ /**
+ * Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.
+ * @minimum 1
+ * @maximum 100
+ */
+ max_instances?: number;
+ /** What happens to groups past max_instances. degrade_visible names how many were left out.
+ *
+ * * `degrade_visible` - Degrade visible */
+ on_overflow?: OnOverflowEnum;
+ }
+
export interface LogsAlertConfiguration {
/** Unique identifier for this alert. */
readonly id: string;
@@ -64203,6 +64226,10 @@ export namespace Schemas {
readonly state_timeline: readonly LogsAlertStateInterval[];
/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */
readonly destination_types: readonly LogsAlertDestinationTypeEnum[];
+ /** How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message. */
+ grouping?: LogsAlertGrouping;
+ /** Whether the alerts platform evaluates this alert and sends its notifications. Only such an alert can set a grouping other than single. */
+ readonly platform_owned: boolean;
/**
* When the alert was first enabled. Null means the alert is still in draft state.
* @nullable
@@ -64368,6 +64395,10 @@ export namespace Schemas {
readonly state_timeline: readonly LogsAlertStateInterval[];
/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */
readonly destination_types: readonly LogsAlertDestinationTypeEnum[];
+ /** How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message. */
+ grouping?: LogsAlertGrouping;
+ /** Whether the alerts platform evaluates this alert and sends its notifications. Only such an alert can set a grouping other than single. */
+ readonly platform_owned: boolean;
/**
* When the alert was first enabled. Null means the alert is still in draft state.
* @nullable
@@ -83815,6 +83846,10 @@ export namespace Schemas {
readonly state_timeline?: readonly LogsAlertStateInterval[];
/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */
readonly destination_types?: readonly LogsAlertDestinationTypeEnum[];
+ /** How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message. */
+ grouping?: LogsAlertGrouping;
+ /** Whether the alerts platform evaluates this alert and sends its notifications. Only such an alert can set a grouping other than single. */
+ readonly platform_owned?: boolean;
/**
* When the alert was first enabled. Null means the alert is still in draft state.
* @nullable
diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.ts
index 559a377d1d91..5a741eaf6683 100644
--- a/services/mcp/src/generated/logs/api.ts
+++ b/services/mcp/src/generated/logs/api.ts
@@ -79,6 +79,11 @@ export const logsAlertsCreateBodyDatapointsToAlarmMax = 10
export const logsAlertsCreateBodyCooldownMinutesDefault = 0
export const logsAlertsCreateBodyCooldownMinutesMin = 0
+export const logsAlertsCreateBodyGroupingOneMaxInstancesDefault = 100
+export const logsAlertsCreateBodyGroupingOneMaxInstancesMax = 100
+
+export const logsAlertsCreateBodyGroupingOneOnOverflowDefault = `degrade_visible`
+
export const LogsAlertsCreateBody = () => zod.object({
name: zod
.string()
@@ -1829,6 +1834,41 @@ export const LogsAlertsCreateBody = () => zod.object({
.datetime({ offset: true })
.nullish()
.describe('ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.'),
+ grouping: zod
+ .object({
+ mode: zod
+ .enum(['single', 'by_result_labels'])
+ .describe('\* `single` - Single\n\* `by_result_labels` - By result labels')
+ .describe(
+ 'single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n\* `single` - Single\n\* `by_result_labels` - By result labels'
+ ),
+ keys: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.'
+ ),
+ max_instances: zod
+ .number()
+ .min(1)
+ .max(logsAlertsCreateBodyGroupingOneMaxInstancesMax)
+ .default(logsAlertsCreateBodyGroupingOneMaxInstancesDefault)
+ .describe(
+ 'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
+ ),
+ on_overflow: zod
+ .enum(['degrade_visible'])
+ .describe('\* `degrade_visible` - Degrade visible')
+ .default(logsAlertsCreateBodyGroupingOneOnOverflowDefault)
+ .describe(
+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
+ ),
+ })
+ .describe('How a logs alert splits its results into instances.')
+ .optional()
+ .describe(
+ 'How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and\/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message.'
+ ),
})
export const LogsAlertsRetrieveParams = () => zod.object({
@@ -1891,6 +1931,11 @@ export const logsAlertsPartialUpdateBodyDatapointsToAlarmMax = 10
export const logsAlertsPartialUpdateBodyCooldownMinutesMin = 0
+export const logsAlertsPartialUpdateBodyGroupingOneMaxInstancesDefault = 100
+export const logsAlertsPartialUpdateBodyGroupingOneMaxInstancesMax = 100
+
+export const logsAlertsPartialUpdateBodyGroupingOneOnOverflowDefault = `degrade_visible`
+
export const LogsAlertsPartialUpdateBody = () => zod.object({
name: zod
.string()
@@ -3641,6 +3686,41 @@ export const LogsAlertsPartialUpdateBody = () => zod.object({
.datetime({ offset: true })
.nullish()
.describe('ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.'),
+ grouping: zod
+ .object({
+ mode: zod
+ .enum(['single', 'by_result_labels'])
+ .describe('\* `single` - Single\n\* `by_result_labels` - By result labels')
+ .describe(
+ 'single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n\* `single` - Single\n\* `by_result_labels` - By result labels'
+ ),
+ keys: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.'
+ ),
+ max_instances: zod
+ .number()
+ .min(1)
+ .max(logsAlertsPartialUpdateBodyGroupingOneMaxInstancesMax)
+ .default(logsAlertsPartialUpdateBodyGroupingOneMaxInstancesDefault)
+ .describe(
+ 'Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.'
+ ),
+ on_overflow: zod
+ .enum(['degrade_visible'])
+ .describe('\* `degrade_visible` - Degrade visible')
+ .default(logsAlertsPartialUpdateBodyGroupingOneOnOverflowDefault)
+ .describe(
+ 'What happens to groups past max_instances. degrade_visible names how many were left out.\n\n\* `degrade_visible` - Degrade visible'
+ ),
+ })
+ .describe('How a logs alert splits its results into instances.')
+ .optional()
+ .describe(
+ 'How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and\/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message.'
+ ),
})
export const LogsAlertsDestroyParams = () => zod.object({
diff --git a/services/mcp/src/tools/generated/logs.ts b/services/mcp/src/tools/generated/logs.ts
index 156cf597ef9a..d7d02d02ca94 100644
--- a/services/mcp/src/tools/generated/logs.ts
+++ b/services/mcp/src/tools/generated/logs.ts
@@ -50,6 +50,9 @@ const logsAlertsCreate = (): ToolBase<ReturnType<typeof LogsAlertsCreateSchema>,
if (params.snooze_until !== undefined) {
body['snooze_until'] = params.snooze_until
}
+ if (params.grouping !== undefined) {
+ body['grouping'] = params.grouping
+ }
const result = await context.api.request<Schemas.LogsAlertConfiguration>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/alerts/`,
@@ -70,6 +73,8 @@ const logsAlertsCreate = (): ToolBase<ReturnType<typeof LogsAlertsCreateSchema>,
'cooldown_minutes',
'schedule_restriction',
'snooze_until',
+ 'grouping',
+ 'platform_owned',
'next_check_at',
'last_notified_at',
'last_checked_at',
@@ -281,6 +286,8 @@ const logsAlertsList = (): ToolBase<
'threshold_operator',
'window_minutes',
'schedule_restriction',
+ 'grouping',
+ 'platform_owned',
'created_at',
'updated_at',
])
@@ -338,6 +345,9 @@ const logsAlertsPartialUpdate = (): ToolBase<
if (params.snooze_until !== undefined) {
body['snooze_until'] = params.snooze_until
}
+ if (params.grouping !== undefined) {
+ body['grouping'] = params.grouping
+ }
const result = await context.api.request<Schemas.LogsAlertConfiguration>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/alerts/${encodeURIComponent(String(params.id))}/`,
@@ -358,6 +368,8 @@ const logsAlertsPartialUpdate = (): ToolBase<
'cooldown_minutes',
'schedule_restriction',
'snooze_until',
+ 'grouping',
+ 'platform_owned',
'next_check_at',
'last_notified_at',
'last_checked_at',
@@ -402,6 +414,8 @@ const logsAlertsRetrieve = (): ToolBase<
'cooldown_minutes',
'schedule_restriction',
'snooze_until',
+ 'grouping',
+ 'platform_owned',
'next_check_at',
'last_notified_at',
'last_checked_at',
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-create.json
index fd255b5b9d2a..69883ef1fe2b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-create.json
@@ -2897,6 +2897,38 @@
},
"type": "object"
},
+ "grouping": {
+ "description": "How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message.",
+ "properties": {
+ "keys": {
+ "description": "Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "max_instances": {
+ "default": 100,
+ "description": "Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.",
+ "maximum": 100,
+ "minimum": 1,
+ "type": "number"
+ },
+ "mode": {
+ "description": "single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n* `single` - Single\n* `by_result_labels` - By result labels",
+ "enum": ["single", "by_result_labels"],
+ "type": "string"
+ },
+ "on_overflow": {
+ "default": "degrade_visible",
+ "description": "What happens to groups past max_instances. degrade_visible names how many were left out.\n\n* `degrade_visible` - Degrade visible",
+ "enum": ["degrade_visible"],
+ "type": "string"
+ }
+ },
+ "required": ["mode"],
+ "type": "object"
+ },
"name": {
"description": "Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.",
"maxLength": 255,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-partial-update.json
index 7f7121990fb4..e91f49d10f0a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-partial-update.json
@@ -2893,6 +2893,38 @@
},
"type": "object"
},
+ "grouping": {
+ "description": "How the alert splits its results into instances. Mode single keeps one instance for the whole alert. Mode by_result_labels with keys service_name and/or severity_text keeps one instance per service or severity, each firing and resolving on its own, and needs threshold_operator above. Only an alert the alerts platform evaluates can group. Any other alert reads as single and rejects a different value. Omit it on update to keep the current grouping. Changing the keys deletes the existing instances and closes their notification threads without a message.",
+ "properties": {
+ "keys": {
+ "description": "Result labels whose values make a group, such as service_name. Empty for mode single, required for by_result_labels. Changing them deletes the existing instances and closes their notification threads without a message.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "max_instances": {
+ "default": 100,
+ "description": "Most instances the alert keeps at once. Groups past it are not tracked, and the last message says how many were left out.",
+ "maximum": 100,
+ "minimum": 1,
+ "type": "number"
+ },
+ "mode": {
+ "description": "single keeps one instance for the whole alert. by_result_labels keeps one instance per distinct value of the labels in keys, so each group fires and resolves on its own.\n\n* `single` - Single\n* `by_result_labels` - By result labels",
+ "enum": ["single", "by_result_labels"],
+ "type": "string"
+ },
+ "on_overflow": {
+ "default": "degrade_visible",
+ "description": "What happens to groups past max_instances. degrade_visible names how many were left out.\n\n* `degrade_visible` - Degrade visible",
+ "enum": ["degrade_visible"],
+ "type": "string"
+ }
+ },
+ "required": ["mode"],
+ "type": "object"
+ },
"id": {
"description": "A UUID string identifying this logs alert configuration.",
"type": "string"