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): delete logs alerts through the platform api (#120014)

Jimmy Zhu688e163dfbee
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index 79c2d6f4112f..4fe419a2ce65 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -229,6 +229,17 @@ def update_owned_copy(
)
+def delete_configuration(*, team_id: int, source_kinds: Sequence[str], configuration_id: UUID) -> bool:
+ """Deletes a configuration the platform owns, with its source's own row. False when the caller
+ cannot read it.
+
+ Raises `PlatformAlertNotEditable` for a configuration its source owns, or of a kind the API cannot delete.
+ """
+ return platform_writes.delete_configuration(
+ team_id=team_id, source_kinds=source_kinds, configuration_id=configuration_id
+ )
+
+
def delete_owned_copy(*, team_id: int, legacy_configuration_id: UUID) -> None:
platform_writes.delete_owned_copy(team_id=team_id, legacy_configuration_id=legacy_configuration_id)
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index f452492b4f61..52238a5949ae 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -915,19 +915,32 @@ class SourceCreate(Protocol):
def __call__(self, *, team_id: int, edit: PlatformAlertConfigurationEdit, created_by_id: int | None) -> UUID: ...
+class SourceDelete(Protocol):
+ """Deletes an alert the platform owns through the platform API, on a source that keeps its own row.
+
+ It removes the source's row and the platform's copy, and closes the alert's open incidents
+ before either goes, while the destinations the resolves go to still exist. So it runs outside
+ any transaction. It raises `PlatformAlertNotEditable` when the source's row belongs to another
+ team than the copy, because the platform API checked access to the copy's team only.
+ """
+
+ def __call__(self, *, team_id: int, legacy_configuration_id: UUID) -> None: ...
+
+
@frozen
class SourceConfigSpec:
"""A source kind's schema for `source_config` and its rules for a whole edit.
`model` validates `source_config`. `validate` raises `InvalidPlatformAlertEdit` for a rule that
spans fields, such as one that reads `enabled`. `mirror` runs in the edit's transaction. Without
- `create`, the API cannot create alerts of the kind.
+ `create` or `delete`, the API cannot create or delete alerts of the kind.
"""
model: type[BaseModel]
validate: Callable[[PlatformAlertConfigurationEdit], None]
mirror: SourceEditMirror | None = None
create: SourceCreate | None = None
+ delete: SourceDelete | None = None
# Where the source's incident destinations listen for a close, and the alert's page in the
# source's product. A control-plane close needs both to address its resolve.
incident_event_ids: Mapping[str, str] | None = None
diff --git a/products/alerts_platform/backend/logic/platform_writes.py b/products/alerts_platform/backend/logic/platform_writes.py
index 42b757fdc2c4..408e1d09cf32 100644
--- a/products/alerts_platform/backend/logic/platform_writes.py
+++ b/products/alerts_platform/backend/logic/platform_writes.py
@@ -270,6 +270,31 @@ def close_owned_firings_now(*, team_id: int, legacy_configuration_id: UUID) -> N
control_plane.announce_now(pending)
+def delete_configuration(*, team_id: int, source_kinds: Sequence[str], configuration_id: UUID) -> bool:
+ """Deletes a configuration the platform owns through the hook its source registered. False when
+ the configuration does not exist or its kind is not among `source_kinds`.
+
+ Raises `PlatformAlertNotEditable` for a configuration its source owns, or of a kind the API
+ cannot delete. Runs outside any transaction, because the source sends its resolves first.
+ """
+ found = (
+ PlatformAlertConfiguration.objects.for_team(team_id, canonical=True)
+ .filter(id=configuration_id, source_kind__in=list(source_kinds))
+ .values_list("source_kind", "legacy_configuration_id", "owner")
+ .first()
+ )
+ if found is None:
+ return False
+ source_kind, legacy_configuration_id, owner = found
+ if owner != PlatformAlertOwner.PLATFORM:
+ raise PlatformAlertNotEditable(f"This alert is managed by the {source_kind} product. Delete it there.")
+ spec = source_configs.spec(SourceKind(source_kind))
+ if spec is None or spec.delete is None or legacy_configuration_id is None:
+ raise PlatformAlertNotEditable(f"{source_kind} alerts cannot be deleted through this API.")
+ spec.delete(team_id=team_id, legacy_configuration_id=legacy_configuration_id)
+ return True
+
+
def delete_owned_copy(*, team_id: int, legacy_configuration_id: UUID) -> None:
"""Deletes the copy of a source alert the platform owns, with its instances and threads."""
copies = PlatformAlertConfiguration.objects.for_team(team_id).filter(
@@ -277,9 +302,10 @@ def delete_owned_copy(*, team_id: int, legacy_configuration_id: UUID) -> None:
)
with transaction.atomic():
# The configuration before its children, the order `record_outcomes` locks them in. The
- # cascade deletes the children first, so without this the two can deadlock.
- list(copies.select_for_update())
- copies.delete()
+ # cascade deletes the children first, so without this the two can deadlock. Each row goes
+ # through the model's own delete, because a queryset delete skips the activity log.
+ for configuration in copies.select_for_update():
+ configuration.delete()
def _locked_owned_copy(team_id: int, legacy_configuration_id: UUID) -> PlatformAlertConfiguration | None:
diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
index c3a38bd1d3c9..3424ee1ae2a0 100644
--- a/products/alerts_platform/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -109,6 +109,8 @@ class PlatformAlertConfiguration(ModelActivityMixin, TeamScopedRootMixin, UUIDMo
)
owner_changed_at = models.DateTimeField(null=True, blank=True)
+ activity_logging_on_delete = True
+
def _should_log_activity_for_update(self, **kwargs: Any) -> tuple[bool, Any]:
# A copy its source owns is not logged, so its writes skip the read of the row before the update.
# Backfills and source edits write those copies one row at a time.
diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.py
index 0de8b80c9f4e..35b479571046 100644
--- a/products/alerts_platform/backend/presentation/views/platform_alert.py
+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py
@@ -540,6 +540,32 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Generic
def partial_update(self, request: Request, pk: str, **kwargs) -> Response:
return self._edit(request, pk, partial=True)
+ @extend_schema(
+ responses={
+ 204: OpenApiResponse(description="The alert, its source's own row and its destinations are deleted."),
+ 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."),
+ 409: OpenApiResponse(description="The source product owns this alert, so only its own API deletes it."),
+ }
+ )
+ def destroy(self, request: Request, pk: str, **kwargs) -> Response:
+ configuration_id = serializers.UUIDField().run_validation(pk)
+ team_id = self._canonical_team_id()
+ current = self._writable_configuration(team_id, configuration_id, "delete")
+ # Checked again by the delete, under the source row's lock.
+ if current.owner != PlatformAlertOwner.PLATFORM:
+ raise Conflict(f"This alert is managed by the {current.source_kind} product. Delete it there.")
+ try:
+ deleted = platform_api.delete_configuration(
+ team_id=team_id, source_kinds=self._writable_source_kinds, configuration_id=configuration_id
+ )
+ except PlatformAlertNotEditable as error:
+ raise Conflict(str(error)) from error
+ if not deleted:
+ raise NotFound()
+ transaction.on_commit(lambda: self._track("deleted", current), robust=True)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
@validated_request(
PlatformAlertGroupSnoozeSerializer,
responses={
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 22f8606f9fe9..b5c527380612 100644
--- a/products/alerts_platform/backend/tests/api/test_platform_alert.py
+++ b/products/alerts_platform/backend/tests/api/test_platform_alert.py
@@ -288,13 +288,17 @@ class TestPlatformAlertAPI(APIBaseTest):
with team_scope(self.team.id):
assert not PlatformAlertThread.objects.filter(configuration=configuration).exists()
- def test_an_alert_its_source_owns_is_not_edited_here(self) -> None:
+ @parameterized.expand([("edit",), ("delete",)])
+ def test_an_alert_its_source_owns_is_not_written_here(self, write: str) -> None:
self._set_flag(True)
configuration = self._create_configuration(self.team, "API errors")
- response = self.client.patch(
- self._edit_url(configuration), {"name": "Renamed", "evaluation_periods": 0}, format="json"
- )
+ if write == "edit":
+ response = self.client.patch(
+ self._edit_url(configuration), {"name": "Renamed", "evaluation_periods": 0}, format="json"
+ )
+ else:
+ response = self.client.delete(self._edit_url(configuration))
assert response.status_code == status.HTTP_409_CONFLICT, response.json()
configuration.refresh_from_db()
diff --git a/products/alerts_platform/frontend/generated/api.ts b/products/alerts_platform/frontend/generated/api.ts
index ab43f12d336c..5b1a4dfe8144 100644
--- a/products/alerts_platform/frontend/generated/api.ts
+++ b/products/alerts_platform/frontend/generated/api.ts
@@ -114,6 +114,17 @@ export const platformAlertsPartialUpdate = async (
})
}
+export const getPlatformAlertsDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/platform_alerts/${id}/`
+}
+
+export const platformAlertsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getPlatformAlertsDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getPlatformAlertsSnoozeGroupCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/platform_alerts/${id}/snooze_group/`
}
diff --git a/products/logs/backend/alert_deletion.py b/products/logs/backend/alert_deletion.py
new file mode 100644
index 000000000000..851a17b5b35d
--- /dev/null
+++ b/products/logs/backend/alert_deletion.py
@@ -0,0 +1,61 @@
+"""Deletes a logs alert, for every route that deletes one."""
+
+from uuid import UUID
+
+from django.db import transaction
+
+from products.alerts.backend.facade.destinations import soft_delete_all_alert_destinations
+from products.alerts_platform.backend.facade.contracts import PlatformAlertNotEditable
+from products.logs.backend.alert_destinations import LOGS_ALERT_EVENT_IDS
+from products.logs.backend.models import LogsAlertConfiguration
+from products.logs.backend.platform_ownership import before_delete, on_deleted
+
+
+def delete_alert(*, team_id: int, alert_id: UUID, only_platform_owned: bool = False) -> bool:
+ """Deletes the alert, its destinations and any platform copy. False when it was already gone.
+
+ With `only_platform_owned`, raises `PlatformAlertNotEditable` when the alert is not, or stops
+ being, owned by the platform, such as after a rollback hands it back mid-delete.
+ """
+ alert = LogsAlertConfiguration.objects.filter(team_id=team_id, id=alert_id).first()
+ if alert is None:
+ return False
+ if only_platform_owned:
+ _require_platform_owned(alert)
+ # Before the transaction, so the resolve is sent while the destinations it goes to still exist.
+ before_delete(alert)
+ with transaction.atomic():
+ locked = LogsAlertConfiguration.objects.select_for_update().filter(team_id=team_id, id=alert_id).first()
+ if locked is None:
+ return False
+ if only_platform_owned:
+ # Checked again under the lock, because the cutover and rollback commands take the same lock.
+ _require_platform_owned(locked)
+ soft_delete_all_alert_destinations(
+ team_id=locked.team_id, alert_id=str(locked.id), allowed_event_ids=LOGS_ALERT_EVENT_IDS
+ )
+ if locked.platform_owned:
+ on_deleted(team_id=locked.team_id, alert_id=locked.id)
+ locked.delete()
+ return True
+
+
+def delete_platform_owned(*, team_id: int, legacy_configuration_id: UUID) -> None:
+ """Deletes a logs alert through the platform API, both rows and its destinations, as the logs API does."""
+ alert = LogsAlertConfiguration.objects.filter(id=legacy_configuration_id).first()
+ if alert is None:
+ # A copy whose logs row is already gone has nothing left to close or to delete on the logs side.
+ on_deleted(team_id=team_id, alert_id=legacy_configuration_id)
+ return
+ if alert.team_id != team_id:
+ # A copy lives on the project, and its logs row on the environment. The platform API checked
+ # access to the project only.
+ raise PlatformAlertNotEditable(
+ "This alert belongs to one of this project's environments. Delete it on that environment's logs alerts page."
+ )
+ delete_alert(team_id=team_id, alert_id=alert.id, only_platform_owned=True)
+
+
+def _require_platform_owned(alert: LogsAlertConfiguration) -> None:
+ if not alert.platform_owned:
+ raise PlatformAlertNotEditable("This alert is managed by the logs product. Delete it there.")
diff --git a/products/logs/backend/facade/platform_ownership.py b/products/logs/backend/facade/platform_ownership.py
index a3956ced378f..04e961a7b793 100644
--- a/products/logs/backend/facade/platform_ownership.py
+++ b/products/logs/backend/facade/platform_ownership.py
@@ -8,9 +8,10 @@ from uuid import UUID
from products.alerts_platform.backend.facade.contracts import Grouping
from products.logs.backend import platform_ownership
+from products.logs.backend.alert_deletion import delete_alert
from products.logs.backend.models import LogsAlertConfiguration
-__all__ = ["before_delete", "on_created", "on_deleted", "on_updated"]
+__all__ = ["delete_alert", "on_created", "on_updated"]
def _alert(team_id: int, alert_id: UUID) -> LogsAlertConfiguration | None:
@@ -38,15 +39,3 @@ def on_updated(*, team_id: int, alert_id: UUID, snooze_changed: bool, grouping:
alert = _alert(team_id, alert_id)
if alert is not None:
platform_ownership.on_updated(alert, snooze_changed=snooze_changed, grouping=grouping)
-
-
-def on_deleted(*, team_id: int, alert_id: UUID) -> None:
- platform_ownership.on_deleted(team_id=team_id, alert_id=alert_id)
-
-
-def before_delete(*, team_id: int, alert_id: UUID) -> None:
- """Closes the incident of a firing alert while its destinations still exist, on whichever stack
- owns it."""
- alert = _alert(team_id, alert_id)
- if alert is not None:
- platform_ownership.before_delete(alert)
diff --git a/products/logs/backend/platform_source_config_schema.py b/products/logs/backend/platform_source_config_schema.py
index 0f88f5bcd1a1..ff6e779c59e1 100644
--- a/products/logs/backend/platform_source_config_schema.py
+++ b/products/logs/backend/platform_source_config_schema.py
@@ -16,6 +16,7 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformAlertConfigurationEdit,
SourceConfigSpec,
)
+from products.logs.backend.alert_deletion import delete_platform_owned
from products.logs.backend.alert_group_columns import grouping_problem
from products.logs.backend.alert_source_cycle import EVENT_IDS_BY_INCIDENT_ACTION
from products.logs.backend.models import LogsAlertConfiguration
@@ -69,6 +70,7 @@ LOGS_SOURCE_CONFIG = SourceConfigSpec(
validate=validate_logs_edit,
mirror=mirror_platform_edit,
create=create_platform_owned,
+ delete=delete_platform_owned,
incident_event_ids=EVENT_IDS_BY_INCIDENT_ACTION,
alert_url=logs_alert_url,
)
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index 9a0e965c16e7..c804770cb860 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -45,7 +45,6 @@ from products.alerts.backend.facade.destinations import (
owned_alert_destination_ids,
redact_destination_data,
soft_delete_alert_destinations,
- soft_delete_all_alert_destinations,
validate_destination_data,
)
from products.alerts_platform.backend.facade.api import (
@@ -108,7 +107,7 @@ from products.logs.backend.facade.api import (
next_allowed_check_at,
platform_check_rows,
)
-from products.logs.backend.facade.platform_ownership import before_delete, on_created, on_deleted, on_updated
+from products.logs.backend.facade.platform_ownership import delete_alert, on_created, on_updated
from products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfiguration, LogsAlertEvent
MAX_SIMULATE_LOOKBACK_DAYS = 30
@@ -1829,21 +1828,6 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
self._track("updated", serializer.save())
def perform_destroy(self, instance: LogsAlertConfiguration) -> None:
- before_delete(team_id=instance.team_id, alert_id=instance.id)
- with transaction.atomic():
- locked_instance = (
- LogsAlertConfiguration.objects.select_for_update()
- .filter(team_id=instance.team_id, id=instance.id)
- .first()
- )
- if locked_instance is None:
- return
- soft_delete_all_alert_destinations(
- team_id=locked_instance.team_id,
- alert_id=str(locked_instance.id),
- allowed_event_ids=LOGS_ALERT_EVENT_IDS,
- )
- if locked_instance.platform_owned:
- on_deleted(team_id=locked_instance.team_id, alert_id=locked_instance.id)
- super().perform_destroy(locked_instance)
- transaction.on_commit(lambda: self._track("deleted", locked_instance), robust=True)
+ if delete_alert(team_id=instance.team_id, alert_id=instance.id):
+ # Robust, so an analytics failure, such as a malformed Referer, cannot fail a committed delete.
+ transaction.on_commit(lambda: self._track("deleted", instance), robust=True)
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index 103ff0b6b520..f715dc2440fb 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -2850,7 +2850,14 @@ class TestLogsAlertAPI(APIBaseTest):
(request,) = [call.args[0] for call in deliver_evaluation.call_args_list]
assert request.incident_actions == {"": IncidentAction.RESOLVE}
- def test_deleting_a_platform_firing_resolves_its_incident_while_its_destinations_exist(self) -> None:
+ def _delete_through(self, route: str, alert_id: str) -> Any:
+ if route == "logs":
+ return self.client.delete(f"{self.base_url}{alert_id}/")
+ with patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True):
+ return self.client.delete(f"/api/projects/{self.team.id}/platform_alerts/{self._copy(alert_id).id}/")
+
+ @parameterized.expand([("logs",), ("platform",)])
+ def test_deleting_a_platform_firing_resolves_its_incident_while_its_destinations_exist(self, route: str) -> None:
created, _copy = self._firing_on_the_platform_with_pagerduty()
destinations_when_sent: list[int] = []
@@ -2858,19 +2865,35 @@ class TestLogsAlertAPI(APIBaseTest):
destinations_when_sent.append(HogFunction.objects.filter(team=self.team, deleted=False).count())
with patch(f"{_WEB_START}.deliver_evaluation", side_effect=deliver) as deliver_evaluation:
- response = self.client.delete(f"{self.base_url}{created['id']}/")
+ response = self._delete_through(route, created["id"])
assert response.status_code == status.HTTP_204_NO_CONTENT
(request,) = [call.args[0] for call in deliver_evaluation.call_args_list]
assert request.incident_actions == {"": IncidentAction.RESOLVE}
assert destinations_when_sent[0] > 0
- def test_deleting_an_alert_the_platform_owns_deletes_its_copy(self) -> None:
+ def test_a_platform_delete_after_a_handback_refuses_and_keeps_the_logs_row(self) -> None:
created = self._owned_by_the_platform()
+ # The state a rollback leaves when it hands the alert back after the platform read its owner.
+ LogsAlertConfiguration.objects.filter(id=created["id"]).update(owner="source")
- response = self.client.delete(f"{self.base_url}{created['id']}/")
+ response = self._delete_through("platform", created["id"])
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()
+ assert LogsAlertConfiguration.objects.filter(id=created["id"]).exists()
+
+ @parameterized.expand([("logs",), ("platform",)])
+ def test_deleting_an_alert_the_platform_owns_deletes_both_rows(self, route: str) -> None:
+ created = self._owned_by_the_platform()
+ copy_id = self._copy(created["id"]).id
+
+ response = self._delete_through(route, created["id"])
assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not LogsAlertConfiguration.objects.filter(id=created["id"]).exists()
+ assert ActivityLog.objects.filter(
+ scope="PlatformAlertConfiguration", item_id=str(copy_id), activity="deleted", user=self.user
+ ).exists()
with team_scope(self.team.id):
assert (
list_configurations(