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): create and delete alerts that have no source row (#123588)

Jimmy Zhu363cbcbc7e64
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index dcc95448bac2..0000f2301425 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -979,17 +979,51 @@ class SourceDelete(Protocol):
def __call__(self, *, team_id: int, legacy_configuration_id: UUID) -> None: ...
+class SourceConfigTeamCheck(Protocol):
+ """Checks a `source_config` against the project it is written in, which `validate` cannot see.
+
+ For example, that its ids name rows of that project. It raises `InvalidPlatformAlertEdit`.
+ """
+
+ def __call__(self, *, team_id: int, edit: PlatformAlertConfigurationEdit) -> None: ...
+
+
+class NativeAlertRemoveDestinations(Protocol):
+ """Removes the destinations of an alert that is about to be deleted.
+
+ The alert's open incidents are closed before this runs, while the destinations their resolves go
+ to still exist. It runs in the delete's transaction, so a delete that fails keeps them.
+ """
+
+ def __call__(self, *, team_id: int, configuration_id: UUID) -> None: ...
+
+
+@frozen
+class NativeAlertLifecycle:
+ """How the platform creates and deletes alerts of a kind whose source keeps no row for them.
+
+ The configuration is the alert's only record, and its own id is the id the alert's destinations
+ are matched on.
+ """
+
+ check_interval_minutes: int
+ remove_destinations: NativeAlertRemoveDestinations
+
+
@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` or `delete`, the API cannot create or delete alerts of the kind.
+ spans fields, such as one that reads `enabled`. `check_in_team` runs when a create or an edit
+ sets `source_config`. `mirror` runs in the edit's transaction. Without
+ `create` or `delete`, the API cannot create or delete alerts of the kind, unless the kind is
+ `native`: then the platform creates and deletes them itself, and the source keeps no row.
"""
model: type[BaseModel]
validate: Callable[[PlatformAlertConfigurationEdit], None]
+ check_in_team: SourceConfigTeamCheck | None = None
mirror: SourceEditMirror | None = None
create: SourceCreate | None = None
delete: SourceDelete | None = None
@@ -997,6 +1031,16 @@ class SourceConfigSpec:
# source's product. A control-plane close needs both to address its resolve.
incident_event_ids: Mapping[str, str] | None = None
alert_url: Callable[[int, UUID], str] | None = None
+ native: NativeAlertLifecycle | None = None
+
+ def __post_init__(self) -> None:
+ # The source-row hooks write a row a native kind does not have.
+ if self.native is not None and (self.mirror or self.create or self.delete):
+ raise ValueError("A native kind keeps no source row, so it cannot register mirror, create or delete.")
+
+ @property
+ def creatable(self) -> bool:
+ return self.native is not None or self.create is not None
SourceConfigLoader = Callable[[], SourceConfigSpec]
diff --git a/products/alerts_platform/backend/logic/control_plane.py b/products/alerts_platform/backend/logic/control_plane.py
index 76034af1e0ba..a3d9eccf8f24 100644
--- a/products/alerts_platform/backend/logic/control_plane.py
+++ b/products/alerts_platform/backend/logic/control_plane.py
@@ -56,7 +56,7 @@ class PendingClose:
team_id: int
source_kind: str
configuration_id: UUID
- legacy_configuration_id: UUID | None
+ destination_alert_id: UUID
rows: tuple[PlatformAlertEventRow, ...]
@@ -90,7 +90,7 @@ def end_firings(configuration: PlatformAlertConfiguration, *, reason: str, now:
team_id=configuration.team_id,
source_kind=configuration.source_kind,
configuration_id=configuration.id,
- legacy_configuration_id=configuration.legacy_configuration_id,
+ destination_alert_id=configuration.destination_alert_id,
rows=rows,
)
@@ -129,7 +129,7 @@ def _announce(pending: PendingClose, *, inline: bool) -> None:
def _resolve_delivery(pending: PendingClose) -> AlertDeliveryRequest | None:
spec = source_configs.spec(SourceKind(pending.source_kind))
- if spec is None or spec.incident_event_ids is None or pending.legacy_configuration_id is None:
+ if spec is None or spec.incident_event_ids is None:
return None
grouping_keys = [row.grouping_key for row in pending.rows]
return AlertDeliveryRequest(
@@ -137,13 +137,13 @@ def _resolve_delivery(pending: PendingClose) -> AlertDeliveryRequest | None:
team_id=pending.team_id,
configuration_id=str(pending.configuration_id),
evaluation_key=pending.rows[0].evaluation_key,
- # The id the source's destinations are matched on, as on every check's delivery.
- destination_alert_id=str(pending.legacy_configuration_id),
+ # The id the alert's destinations are matched on, as on every check's delivery.
+ destination_alert_id=str(pending.destination_alert_id),
event_ids_by_kind={},
incident_actions=dict.fromkeys(grouping_keys, IncidentAction.RESOLVE),
sends_messages=False,
event_ids_by_incident_action=dict(spec.incident_event_ids),
- source_alert_url=spec.alert_url(pending.team_id, pending.legacy_configuration_id) if spec.alert_url else None,
+ source_alert_url=spec.alert_url(pending.team_id, pending.destination_alert_id) if spec.alert_url else None,
owned_by_platform=True,
parts=parts_for(len(grouping_keys)),
)
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 5e9b6f502121..66b7fbf23476 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -31,6 +31,7 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformAlertUpsert,
PlatformHandback,
PlatformOwnershipHandover,
+ SourceKind,
source_condition,
)
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertState
@@ -797,6 +798,33 @@ def write_edit(
if reenabled:
configuration.next_check_at = now + _REVIVE_FENCE
update_fields.append("next_check_at")
+ _assign_edit(configuration, edit)
+ configuration.save(update_fields=update_fields)
+
+
+def create_native_configuration(
+ *,
+ team_id: int,
+ source_kind: SourceKind,
+ edit: PlatformAlertConfigurationEdit,
+ check_interval_minutes: int,
+ now: datetime,
+) -> PlatformAlertConfiguration:
+ """Creates an alert the platform owns from the start, for a kind whose source keeps no row for it."""
+ configuration = PlatformAlertConfiguration(
+ team_id=team_id,
+ source_kind=source_kind.value,
+ check_interval_minutes=check_interval_minutes,
+ next_check_at=now,
+ owner=PlatformAlertOwner.PLATFORM,
+ )
+ _assign_edit(configuration, edit)
+ # The model's own save logs the creation.
+ configuration.save()
+ return configuration
+
+
+def _assign_edit(configuration: PlatformAlertConfiguration, edit: PlatformAlertConfigurationEdit) -> None:
configuration.name = edit.name
configuration.enabled = edit.enabled
configuration.source_config = edit.source_config
@@ -805,7 +833,6 @@ def write_edit(
configuration.evaluation_periods = edit.evaluation_periods
configuration.datapoints_to_alarm = edit.datapoints_to_alarm
configuration.cooldown_minutes = edit.cooldown_minutes
- configuration.save(update_fields=update_fields)
def end_firing_instances(configuration: PlatformAlertConfiguration, *, now: datetime) -> list[PlatformAlert]:
diff --git a/products/alerts_platform/backend/logic/platform_writes.py b/products/alerts_platform/backend/logic/platform_writes.py
index 408e1d09cf32..b5c957229d66 100644
--- a/products/alerts_platform/backend/logic/platform_writes.py
+++ b/products/alerts_platform/backend/logic/platform_writes.py
@@ -11,6 +11,7 @@ from typing import Final
from uuid import UUID
from django.db import transaction
+from django.db.models import QuerySet
from django.utils import timezone as django_timezone
from pydantic import ValidationError as PydanticValidationError
@@ -25,10 +26,12 @@ from products.alerts_platform.backend.facade.contracts import (
Grouping,
GroupingMode,
InvalidPlatformAlertEdit,
+ NativeAlertLifecycle,
PlatformAlertConfigurationEdit,
PlatformAlertConfigurationView,
PlatformAlertNotEditable,
PlatformAlertSnapshot,
+ SourceCreate,
SourceKind,
UnknownPlatformAlertGroup,
)
@@ -56,7 +59,11 @@ def edit_of(configuration: PlatformAlertConfiguration) -> PlatformAlertConfigura
def _validated(
- source_kind: SourceKind, current: PlatformAlertConfigurationEdit | None, edit: PlatformAlertConfigurationEdit
+ source_kind: SourceKind,
+ current: PlatformAlertConfigurationEdit | None,
+ edit: PlatformAlertConfigurationEdit,
+ *,
+ team_id: int,
) -> PlatformAlertConfigurationEdit:
spec = source_configs.spec(source_kind)
if spec is None:
@@ -76,8 +83,10 @@ def _validated(
except ValueError as error:
raise InvalidPlatformAlertEdit("schedule_restriction", str(error)) from error
source_config = edit.source_config
- # Settings the edit leaves alone may predate the schema, and must not block an unrelated change.
- if current is None or source_config != current.source_config:
+ # Settings the edit leaves alone may predate the schema, or name rows deleted since, and must not
+ # block an unrelated change.
+ sets_source_config = current is None or source_config != current.source_config
+ if sets_source_config:
try:
parsed = spec.model.model_validate(source_config)
except PydanticValidationError as error:
@@ -87,6 +96,8 @@ def _validated(
source_config = parsed.model_dump(mode="json", exclude_unset=True)
validated = replace(edit, source_config=source_config, schedule_restriction=schedule_restriction)
spec.validate(validated)
+ if sets_source_config and spec.check_in_team is not None:
+ spec.check_in_team(team_id=team_id, edit=validated)
return validated
@@ -135,17 +146,44 @@ def update_configuration(
def create_configuration(
*, team_id: int, source_kind: SourceKind, edit: PlatformAlertConfigurationEdit, created_by_id: int | None
) -> PlatformAlertConfigurationView:
- """Creates an alert the platform owns, through the hook its source registered.
+ """Creates an alert the platform owns: itself for a native kind, and otherwise through the hook
+ its source registered.
Raises `PlatformAlertNotEditable` for a kind the API cannot create, `InvalidPlatformAlertEdit` for
settings its source kind rejects, and `PlatformAlertCreateRefused` when the source refuses.
"""
spec = source_configs.spec(source_kind)
- if spec is None or spec.create is None:
+ if spec is None or not spec.creatable:
raise PlatformAlertNotEditable(f"{source_kind} alerts cannot be created through this API.")
- validated = _validated(source_kind, None, edit)
+ validated = _validated(source_kind, None, edit, team_id=team_id)
+ if spec.native is not None:
+ configuration = platform_lifecycle.create_native_configuration(
+ team_id=team_id,
+ source_kind=source_kind,
+ edit=validated,
+ check_interval_minutes=spec.native.check_interval_minutes,
+ now=django_timezone.now(),
+ )
+ else:
+ assert spec.create is not None
+ configuration = _create_through_source(team_id, source_kind, spec.create, validated, created_by_id)
+
+ view = platform_reads.get_configuration(
+ team_id=team_id, source_kinds=[source_kind.value], configuration_id=configuration.id
+ )
+ assert view is not None
+ return view
+
+
+def _create_through_source(
+ team_id: int,
+ source_kind: SourceKind,
+ create: SourceCreate,
+ validated: PlatformAlertConfigurationEdit,
+ created_by_id: int | None,
+) -> PlatformAlertConfiguration:
with transaction.atomic():
- legacy_configuration_id = spec.create(team_id=team_id, edit=validated, created_by_id=created_by_id)
+ legacy_configuration_id = create(team_id=team_id, edit=validated, created_by_id=created_by_id)
configuration = _locked_owned_copy(team_id, legacy_configuration_id)
if configuration is None:
raise MissingPlatformCopy(f"The {source_kind} source created no platform copy of {legacy_configuration_id}")
@@ -162,12 +200,7 @@ def create_configuration(
# The source wrote the settings it shares with the copy. This writes the rest, such as grouping.
_, pending = _apply(configuration, lambda _: validated, now=django_timezone.now())
control_plane.announce_after_commit(pending)
-
- view = platform_reads.get_configuration(
- team_id=team_id, source_kinds=[source_kind.value], configuration_id=configuration.id
- )
- assert view is not None
- return view
+ return configuration
# A snoozed group keeps its slot under `max_instances`, so a forgotten long snooze would hold it.
@@ -260,8 +293,12 @@ def close_owned_firings_now(*, team_id: int, legacy_configuration_id: UUID) -> N
For a delete, which removes the destinations a delivery after commit would look up. Call it
outside the delete's transaction, so the history it reads and the state it moved have committed.
"""
+ _close_firings_now(lambda: _locked_owned_copy(team_id, legacy_configuration_id))
+
+
+def _close_firings_now(locked: Callable[[], PlatformAlertConfiguration | None]) -> None:
with transaction.atomic():
- configuration = _locked_owned_copy(team_id, legacy_configuration_id)
+ configuration = locked()
pending = (
None
if configuration is None
@@ -271,11 +308,12 @@ def close_owned_firings_now(*, team_id: int, legacy_configuration_id: UUID) -> N
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`.
+ """Deletes a configuration the platform owns, itself for a native kind and otherwise 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.
+ cannot delete. Runs outside any transaction, because the resolves go out first.
"""
found = (
PlatformAlertConfiguration.objects.for_team(team_id, canonical=True)
@@ -289,22 +327,46 @@ def delete_configuration(*, team_id: int, source_kinds: Sequence[str], configura
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:
+ if spec is not None and spec.native is not None:
+ _delete_native(team_id, configuration_id, spec.native)
+ elif spec is not None and spec.delete is not None and legacy_configuration_id is not None:
+ spec.delete(team_id=team_id, legacy_configuration_id=legacy_configuration_id)
+ else:
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_native(team_id: int, configuration_id: UUID, native: NativeAlertLifecycle) -> None:
+ configurations = PlatformAlertConfiguration.objects.for_team(team_id, canonical=True).filter(id=configuration_id)
+ # Before the destinations go, so an incident manager still gets the resolve for an open firing.
+ _close_firings_now(lambda: configurations.select_for_update().first())
+ # In the delete's transaction, so a delete that fails keeps the alert's destinations.
+ _delete_each(
+ configurations,
+ before_delete=lambda: native.remove_destinations(team_id=team_id, configuration_id=configuration_id),
+ )
+
+
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(
- legacy_configuration_id=legacy_configuration_id, owner=PlatformAlertOwner.PLATFORM
+ _delete_each(
+ PlatformAlertConfiguration.objects.for_team(team_id).filter(
+ legacy_configuration_id=legacy_configuration_id, owner=PlatformAlertOwner.PLATFORM
+ )
)
+
+
+def _delete_each(
+ configurations: QuerySet[PlatformAlertConfiguration], *, before_delete: Callable[[], None] | None = None
+) -> 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. Each row goes
# through the model's own delete, because a queryset delete skips the activity log.
- for configuration in copies.select_for_update():
+ locked = list(configurations.select_for_update())
+ if before_delete is not None:
+ before_delete()
+ for configuration in locked:
configuration.delete()
@@ -339,7 +401,7 @@ def _apply(
f"This alert is managed by the {configuration.source_kind} product. Edit it there."
)
current = edit_of(configuration)
- edit = _validated(SourceKind(configuration.source_kind), current, change(current))
+ edit = _validated(SourceKind(configuration.source_kind), current, change(current), team_id=configuration.team_id)
regrouped = not edit.grouping.splits_like(current.grouping)
ending = control_plane.ending_reason(current, edit, regrouped=regrouped, snoozing=snoozing)
diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
index 83c05b8031b5..2cc009653f8e 100644
--- a/products/alerts_platform/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -9,6 +9,7 @@ source configures on the shared platform, rather than one product's own table.
"""
from typing import Any
+from uuid import UUID
from django.contrib.postgres.fields import ArrayField
from django.db import models
@@ -123,6 +124,12 @@ class PlatformAlertConfiguration(ModelActivityMixin, TeamScopedRootMixin, UUIDMo
activity_logging_on_delete = True
+ @property
+ def destination_alert_id(self) -> UUID:
+ """The id the alert's destinations are matched on: the source row's for a copy, and the
+ configuration's own for an alert whose source keeps no row."""
+ return self.legacy_configuration_id or self.id
+
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 20e688a80e11..38fee6982a40 100644
--- a/products/alerts_platform/backend/presentation/views/platform_alert.py
+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py
@@ -345,8 +345,8 @@ def _typed_create_serializer(
@cache
def create_serializers() -> dict[str, type[PlatformAlertConfigurationEditSerializer]]:
- """One create serializer per kind whose source registered a create hook."""
- creatable = {source.value for source, spec in editable_source_configs().items() if spec.create is not None}
+ """One create serializer per kind the API can create."""
+ creatable = {source.value for source, spec in editable_source_configs().items() if spec.creatable}
return {
source_kind: _typed_create_serializer(serializer)
for source_kind, serializer in edit_serializers().items()
diff --git a/products/alerts_platform/backend/tests/test_native_alerts.py b/products/alerts_platform/backend/tests/test_native_alerts.py
new file mode 100644
index 000000000000..b37b6304310f
--- /dev/null
+++ b/products/alerts_platform/backend/tests/test_native_alerts.py
@@ -0,0 +1,163 @@
+from contextlib import nullcontext
+from dataclasses import replace
+from datetime import UTC, datetime
+from uuid import UUID
+
+import pytest
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from pydantic import BaseModel, ConfigDict
+
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.scoping import team_scope
+
+from products.alerts_platform.backend.facade import testing as platform_testing
+from products.alerts_platform.backend.facade.contracts import (
+ Grouping,
+ IncidentAction,
+ InvalidPlatformAlertEdit,
+ NativeAlertLifecycle,
+ PlatformAlertConfigurationEdit,
+ SourceConfigSpec,
+ SourceKind,
+)
+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
+from products.alerts_platform.backend.logic import platform_writes
+from products.alerts_platform.backend.models import PlatformAlertConfiguration
+
+_SOURCE_CONFIGS = "products.alerts_platform.backend.logic.source_configs.spec"
+_DELIVER_INLINE = "products.alerts_platform.backend.temporal.web_start.deliver_inline"
+
+
+class _WatchedRows(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ row_ids: list[str] = []
+
+
+def _edit(**changes: object) -> PlatformAlertConfigurationEdit:
+ edit = PlatformAlertConfigurationEdit(
+ name="Sync failures",
+ enabled=True,
+ source_config={"row_ids": ["a"]},
+ grouping=Grouping(),
+ schedule_restriction=None,
+ evaluation_periods=1,
+ datapoints_to_alarm=1,
+ cooldown_minutes=0,
+ )
+ return replace(edit, **changes) # type: ignore[arg-type]
+
+
+class TestNativeAlerts(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.check_in_team = MagicMock()
+ self.remove_destinations = MagicMock()
+ self.spec = SourceConfigSpec(
+ model=_WatchedRows,
+ validate=lambda edit: None,
+ check_in_team=self.check_in_team,
+ incident_event_ids={
+ IncidentAction.TRIGGER: "$x_alert_incident_opened",
+ IncidentAction.RESOLVE: "$x_alert_incident_closed",
+ },
+ alert_url=lambda team_id, alert_id: f"https://example.com/{team_id}/{alert_id}",
+ native=NativeAlertLifecycle(
+ check_interval_minutes=5,
+ remove_destinations=self.remove_destinations,
+ ),
+ )
+ patcher = patch(_SOURCE_CONFIGS, return_value=self.spec)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def _create(self) -> UUID:
+ with team_scope(self.team.id):
+ view = platform_writes.create_configuration(
+ team_id=self.team.id, source_kind=SourceKind.LOGS, edit=_edit(), created_by_id=self.user.id
+ )
+ return view.id
+
+ def test_a_native_create_writes_one_platform_owned_configuration_and_no_source_row(self) -> None:
+ configuration_id = self._create()
+
+ with team_scope(self.team.id):
+ configuration = PlatformAlertConfiguration.objects.get(id=configuration_id)
+ assert (
+ configuration.owner,
+ configuration.legacy_configuration_id,
+ configuration.check_interval_minutes,
+ configuration.source_config,
+ ) == (PlatformAlertOwner.PLATFORM, None, 5, {"row_ids": ["a"]})
+ self.check_in_team.assert_called_once_with(team_id=self.team.id, edit=_edit())
+ assert (
+ ActivityLog.objects.filter(
+ scope="PlatformAlertConfiguration", item_id=str(configuration_id), activity="created"
+ ).count()
+ == 1
+ )
+
+ @parameterized.expand(
+ [
+ ("rename", {"name": "Renamed"}, False),
+ ("source_config", {"source_config": {"row_ids": ["b"]}}, True),
+ ]
+ )
+ def test_a_native_edit_checks_the_project_only_when_source_config_changes(
+ self, _name: str, changes: dict[str, object], checked: bool
+ ) -> None:
+ configuration_id = self._create()
+ self.check_in_team.reset_mock()
+ self.check_in_team.side_effect = InvalidPlatformAlertEdit("source_config", "Not in this project.")
+
+ with pytest.raises(InvalidPlatformAlertEdit) if checked else nullcontext(), team_scope(self.team.id):
+ platform_writes.update_configuration(
+ team_id=self.team.id,
+ source_kinds=[SourceKind.LOGS.value],
+ configuration_id=configuration_id,
+ change=lambda current: replace(current, **changes), # type: ignore[arg-type]
+ )
+
+ assert self.check_in_team.called is checked
+
+ def test_deleting_a_firing_native_alert_resolves_by_its_own_id_before_its_destinations_go(self) -> None:
+ configuration_id = self._create()
+ with team_scope(self.team.id):
+ platform_testing.start_firing(configuration_id, team_id=self.team.id, at=datetime(2026, 1, 1, tzinfo=UTC))
+ calls: list[str] = []
+
+ with patch(_DELIVER_INLINE, side_effect=lambda request: calls.append(request.destination_alert_id)):
+ self.remove_destinations.side_effect = lambda **_: calls.append("destinations removed")
+ with team_scope(self.team.id):
+ deleted = platform_writes.delete_configuration(
+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], configuration_id=configuration_id
+ )
+
+ assert deleted
+ assert calls == [str(configuration_id), "destinations removed"]
+ self.remove_destinations.assert_called_once_with(team_id=self.team.id, configuration_id=configuration_id)
+ with team_scope(self.team.id):
+ assert not PlatformAlertConfiguration.objects.filter(id=configuration_id).exists()
+
+ def test_a_native_delete_that_fails_keeps_what_removing_the_destinations_wrote(self) -> None:
+ configuration_id = self._create()
+
+ def remove_destinations(**_: object) -> None:
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(id=configuration_id).update(name="Destinations removed")
+
+ self.remove_destinations.side_effect = remove_destinations
+ with (
+ patch.object(PlatformAlertConfiguration, "delete", side_effect=RuntimeError("delete failed")),
+ pytest.raises(RuntimeError),
+ team_scope(self.team.id),
+ ):
+ platform_writes.delete_configuration(
+ team_id=self.team.id, source_kinds=[SourceKind.LOGS.value], configuration_id=configuration_id
+ )
+
+ with team_scope(self.team.id):
+ assert PlatformAlertConfiguration.objects.get(id=configuration_id).name == "Sync failures"