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): add a per-team command that hands logs alerts to the alerts platform (#116695)

Jimmy Zhu1f4f6952b094
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index 75253874acc4..8c37389c3af9 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -17,6 +17,7 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformAlertConfigurationView,
PlatformAlertOutcome,
PlatformAlertUpsert,
+ PlatformOwnershipHandover,
SourceKind,
)
from products.alerts_platform.backend.logic import platform_lifecycle, platform_reads
@@ -44,6 +45,11 @@ def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
return platform_lifecycle.upsert_configuration(upsert)
+def take_ownership(handover: PlatformOwnershipHandover) -> bool:
+ """Makes the platform the owner of a copied alert, carrying on from the source's state."""
+ return platform_lifecycle.take_ownership(handover)
+
+
def disable_configurations(source_kind: SourceKind, *, team_id: int | None = None) -> int:
"""Switch off a source's copies, or one team's. Returns how many it switched off."""
return platform_lifecycle.disable_configurations(source_kind.value, team_id=team_id)
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index b9234bdda2b0..8fbf245dfdcb 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -17,6 +17,8 @@ from uuid import UUID
from posthog.dataclasses import frozen
from posthog.enums import LabeledStrEnum
+from products.alerts_platform.backend.facade.enums import PlatformAlertState
+
if TYPE_CHECKING:
# facade.lifecycle imports this module, so the policy type stays off the runtime import path.
from products.alerts_platform.backend.facade.lifecycle import AlertPolicy
@@ -158,6 +160,20 @@ class PlatformAlertUpsert:
anchor_time: str | None = None
+@frozen
+class PlatformOwnershipHandover:
+ """A source alert handed to the platform, with the runtime state the platform carries on from."""
+
+ legacy_configuration_id: UUID
+ team_id: int
+ state: PlatformAlertState
+ last_notified_at: datetime | None
+ consecutive_failures: int
+ # The platform checks no earlier than a minute after the handover, whatever this says.
+ next_check_at: datetime
+ at: datetime
+
+
class SkipReason(StrEnum):
"""Why a check reached an outcome without a query answering it.
@@ -379,6 +395,7 @@ class PlatformConfigurationSnapshot:
id: UUID
next_check_at: datetime | None
consecutive_failures: int
+ owner: str
@frozen
diff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.py
index 7faa9c34471f..3a17c2acf032 100644
--- a/products/alerts_platform/backend/facade/testing.py
+++ b/products/alerts_platform/backend/facade/testing.py
@@ -24,7 +24,7 @@ from products.alerts_platform.backend.models import PlatformAlert, PlatformAlert
def _configuration_snapshot(row: PlatformAlertConfiguration) -> PlatformConfigurationSnapshot:
return PlatformConfigurationSnapshot(
- id=row.id, next_check_at=row.next_check_at, consecutive_failures=row.consecutive_failures
+ id=row.id, next_check_at=row.next_check_at, consecutive_failures=row.consecutive_failures, owner=row.owner
)
@@ -44,6 +44,14 @@ def configuration(configuration_id: UUID) -> PlatformConfigurationSnapshot:
return _configuration_snapshot(PlatformAlertConfiguration.objects.get(id=configuration_id))
+def copy_of(legacy_configuration_id: UUID) -> PlatformConfigurationSnapshot:
+ """The platform copy of a source's configuration, which a source's test made through its own code."""
+ # nosemgrep: idor-lookup-without-team — fail-closed model; the caller holds the team scope
+ return _configuration_snapshot(
+ PlatformAlertConfiguration.objects.get(legacy_configuration_id=legacy_configuration_id)
+ )
+
+
def set_due_at(configuration_id: UUID, due_at: datetime) -> None:
"""Move a configuration's due time, so a test can run two checks against one schedule."""
# nosemgrep: idor-lookup-without-team — fail-closed model; the caller holds the team scope
@@ -56,6 +64,16 @@ def count_still_due(configuration_ids: Iterable[UUID], *, at: datetime) -> int:
return PlatformAlertConfiguration.objects.filter(id__in=list(configuration_ids), next_check_at__lte=at).count()
+def start_firing(configuration_id: UUID, *, team_id: int, at: datetime) -> None:
+ """Put a configuration's instance inside a firing, as live delivery can leave one."""
+ PlatformAlert.objects.update_or_create(
+ team_id=team_id,
+ configuration_id=configuration_id,
+ grouping_key="",
+ defaults={"state": "firing", "firing_started_at": at},
+ )
+
+
def alert_for(configuration_id: UUID, *, grouping_key: str = "") -> PlatformAlertSnapshot | None:
"""The instance row a check wrote, or None when no check has written one."""
row = PlatformAlert.objects.filter(configuration_id=configuration_id, grouping_key=grouping_key).first()
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 8873be96881e..6a0d77dade9c 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -5,7 +5,7 @@ and every write to these rows, stays here. A source never holds one of these mod
"""
from collections.abc import Collection, Sequence
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Final
from django.db import transaction
@@ -17,8 +17,10 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformAlertCheckInput,
PlatformAlertOutcome,
PlatformAlertUpsert,
+ PlatformOwnershipHandover,
source_condition,
)
+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertState
from products.alerts_platform.backend.facade.platform_metrics import increment_history_rows_dropped, safe_record
from products.alerts_platform.backend.facade.scheduling import (
advance_schedule,
@@ -242,8 +244,14 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:
by_id = {str(o.configuration_id): o for o in outcomes}
with transaction.atomic():
+ # Locked in a fixed order, so an ownership handover waits for this write or this write
+ # re-reads the row after it and finds it no longer due.
configurations = list(
- PlatformAlertConfiguration.objects.for_team(team_id).filter(id__in=by_id).filter(due_q(now))
+ PlatformAlertConfiguration.objects.for_team(team_id)
+ .select_for_update()
+ .filter(id__in=by_id)
+ .filter(due_q(now))
+ .order_by("id")
)
if not configurations:
return 0
@@ -351,6 +359,47 @@ def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:
return created
+# Firing episodes are keyed per stack, so a firing alert stays with its source until it resolves.
+_HANDOVER_STATES: Final = frozenset(
+ {PlatformAlertState.NOT_FIRING, PlatformAlertState.ERRORED, PlatformAlertState.BROKEN}
+)
+_HANDOVER_FENCE: Final = timedelta(minutes=1)
+
+
+def take_ownership(handover: PlatformOwnershipHandover) -> bool:
+ """Makes the platform the owner of a copied alert, carrying on from the source's state.
+
+ The second writer of an alert's state beside `record_outcomes`. The caller holds the source's
+ 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.
+ Raises `PlatformAlertConfiguration.DoesNotExist` when the alert was never copied.
+ """
+ if handover.state not in _HANDOVER_STATES:
+ raise ValueError(f"an alert in state {handover.state} stays with its source until it resolves")
+ with transaction.atomic():
+ configuration = (
+ PlatformAlertConfiguration.objects.for_team(handover.team_id)
+ .select_for_update()
+ .get(legacy_configuration_id=handover.legacy_configuration_id)
+ )
+ alert = _alerts_for_write(handover.team_id, [configuration])[str(configuration.id)]
+ if alert.state == PlatformAlertState.FIRING or alert.firing_started_at is not None:
+ return False
+ configuration.owner = PlatformAlertOwner.PLATFORM
+ configuration.owner_changed_at = handover.at
+ configuration.consecutive_failures = handover.consecutive_failures
+ # A platform check that started before the handover records only rows still due, so a
+ # schedule after the handover keeps it from recording over the carried state.
+ configuration.next_check_at = max(handover.next_check_at, handover.at + _HANDOVER_FENCE)
+ configuration.save(update_fields=["owner", "owner_changed_at", "consecutive_failures", "next_check_at"])
+
+ alert.state = handover.state
+ alert.last_notified_at = handover.last_notified_at
+ alert.save(update_fields=["state", "last_notified_at"])
+ return True
+
+
def disable_configurations(source_kind: str, *, team_id: int | None = None) -> int:
"""Switches off a source's copies, or one team's, and returns how many it switched off.
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index cfa60e734986..d444bf78e584 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -14,6 +14,7 @@ from products.alerts_platform.backend.facade.api import (
disable_configurations,
due_checks,
record_outcomes,
+ take_ownership,
upsert_configuration,
)
from products.alerts_platform.backend.facade.contracts import (
@@ -21,8 +22,10 @@ from products.alerts_platform.backend.facade.contracts import (
FiringEpisode,
PlatformAlertOutcome,
PlatformAlertUpsert,
+ PlatformOwnershipHandover,
SourceKind,
)
+from products.alerts_platform.backend.facade.enums import PlatformAlertState
from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
from products.alerts_platform.backend.models.platform_alert_events_sql import SHARDED_PLATFORM_ALERT_EVENTS_TABLE
@@ -80,6 +83,54 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
)
assert self._alert().firing_started_at is None
+ def test_a_check_that_started_before_a_handover_records_nothing(self) -> None:
+ legacy_id = uuid4()
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(id=self.configuration.id).update(
+ legacy_configuration_id=legacy_id
+ )
+ 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=2),
+ at=self.cutoff + timedelta(seconds=30),
+ )
+ )
+
+ self._record()
+
+ assert self._alert().state == "not_firing"
+
+ def test_a_copy_inside_its_own_firing_is_not_taken_over(self) -> None:
+ legacy_id = uuid4()
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(id=self.configuration.id).update(
+ legacy_configuration_id=legacy_id
+ )
+ PlatformAlert.objects.create(
+ team=self.team, configuration=self.configuration, state="firing", firing_started_at=self.cutoff
+ )
+
+ taken = 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=2),
+ at=self.cutoff,
+ )
+ )
+
+ assert not taken
+ self.configuration.refresh_from_db()
+ assert (self.configuration.owner, self._alert().state) == ("source", "firing")
+
def test_a_disabling_outcome_stops_the_configuration_being_discovered(self) -> None:
self._record(new_state="broken", notified=False, consecutive_failures=5, disable=True)
diff --git a/products/logs/backend/management/commands/cut_over_logs_alerts_to_platform.py b/products/logs/backend/management/commands/cut_over_logs_alerts_to_platform.py
new file mode 100644
index 000000000000..b761c037c7fe
--- /dev/null
+++ b/products/logs/backend/management/commands/cut_over_logs_alerts_to_platform.py
@@ -0,0 +1,21 @@
+from collections import Counter
+from typing import Any
+
+from django.core.management.base import BaseCommand
+
+from products.logs.backend.platform_cutover import cut_over_team
+
+
+class Command(BaseCommand):
+ help = "Hand one team's logs alerts to the alerts platform. Safe to run again."
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--team-id", type=int, required=True, help="The team to move.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ results = cut_over_team(options["team_id"])
+ for result in results:
+ if result.skipped is not None:
+ self.stdout.write(f"alert={result.alert_id} skipped={result.skipped}")
+ outcomes = Counter(str(result.skipped or "moved") for result in results)
+ self.stdout.write(f"team={options['team_id']} {dict(outcomes) or 'no alerts'}")
diff --git a/products/logs/backend/platform_alert_backfill.py b/products/logs/backend/platform_alert_backfill.py
index 7814cfd652d4..3dd7b1c20bc5 100644
--- a/products/logs/backend/platform_alert_backfill.py
+++ b/products/logs/backend/platform_alert_backfill.py
@@ -7,12 +7,15 @@ keeps the copy in sync afterwards. Run it again to pick up changes.
rather than duplicates, and a later comparison can line the two stacks up per alert.
"""
+from typing import Final
+
import structlog
from posthog.dataclasses import frozen
from products.alerts_platform.backend.facade.api import upsert_configuration
from products.alerts_platform.backend.facade.contracts import SOURCE_CONDITION_KEY, PlatformAlertUpsert, SourceKind
+from products.alerts_platform.backend.facade.enums import PlatformAlertState
from products.logs.backend.alert_source_cycle import LogsAlertCondition
from products.logs.backend.models import LogsAlertConfiguration
@@ -25,6 +28,43 @@ class BackfillCounts:
updated: int
+def platform_upsert_of(alert: LogsAlertConfiguration) -> PlatformAlertUpsert:
+ """The platform copy of a logs alert, which the backfill writes and every check reads again."""
+ return PlatformAlertUpsert(
+ legacy_configuration_id=alert.id,
+ team_id=alert.team_id,
+ name=alert.name,
+ enabled=alert.enabled,
+ source_kind=SourceKind.LOGS,
+ source_config={
+ **alert.filters,
+ SOURCE_CONDITION_KEY: LogsAlertCondition(
+ threshold_count=alert.threshold_count,
+ threshold_operator=alert.threshold_operator,
+ window_minutes=alert.window_minutes,
+ ).as_source_config(),
+ },
+ check_interval_minutes=alert.check_interval_minutes,
+ evaluation_periods=alert.evaluation_periods,
+ datapoints_to_alarm=alert.datapoints_to_alarm,
+ cooldown_minutes=alert.cooldown_minutes,
+ schedule_restriction=alert.schedule_restriction,
+ next_check_at=alert.next_check_at,
+ snooze_until=alert.snooze_until,
+ )
+
+
+# A muted logs alert is a state of its own. On the platform a mute only silences notifications,
+# so the copy keeps checking with the snooze carried on `snooze_until`. Firing states have no entry,
+# because a firing alert stays with logs until it resolves.
+PLATFORM_HANDOVER_STATE: Final[dict[str, PlatformAlertState]] = {
+ LogsAlertConfiguration.State.NOT_FIRING: PlatformAlertState.NOT_FIRING,
+ LogsAlertConfiguration.State.SNOOZED: PlatformAlertState.NOT_FIRING,
+ LogsAlertConfiguration.State.ERRORED: PlatformAlertState.ERRORED,
+ LogsAlertConfiguration.State.BROKEN: PlatformAlertState.BROKEN,
+}
+
+
def backfill_platform_alert_configurations(*, team_id: int | None = None) -> BackfillCounts:
"""Copies every logs alert configuration, or one team's."""
source = LogsAlertConfiguration.objects.all()
@@ -34,30 +74,7 @@ def backfill_platform_alert_configurations(*, team_id: int | None = None) -> Bac
created = 0
updated = 0
for configuration in source.iterator():
- was_created = upsert_configuration(
- PlatformAlertUpsert(
- legacy_configuration_id=configuration.id,
- team_id=configuration.team_id,
- name=configuration.name,
- enabled=configuration.enabled,
- source_kind=SourceKind.LOGS,
- source_config={
- **configuration.filters,
- SOURCE_CONDITION_KEY: LogsAlertCondition(
- threshold_count=configuration.threshold_count,
- threshold_operator=configuration.threshold_operator,
- window_minutes=configuration.window_minutes,
- ).as_source_config(),
- },
- check_interval_minutes=configuration.check_interval_minutes,
- evaluation_periods=configuration.evaluation_periods,
- datapoints_to_alarm=configuration.datapoints_to_alarm,
- cooldown_minutes=configuration.cooldown_minutes,
- schedule_restriction=configuration.schedule_restriction,
- next_check_at=configuration.next_check_at,
- snooze_until=configuration.snooze_until,
- )
- )
+ was_created = upsert_configuration(platform_upsert_of(configuration))
if was_created:
created += 1
else:
diff --git a/products/logs/backend/platform_cutover.py b/products/logs/backend/platform_cutover.py
new file mode 100644
index 000000000000..571956406612
--- /dev/null
+++ b/products/logs/backend/platform_cutover.py
@@ -0,0 +1,96 @@
+"""Hands a team's logs alerts to the alerts platform, one alert at a time.
+
+Each alert moves in its own transaction, under its own row lock. An alert that cannot move now is
+skipped with a reason, and a later run picks it up. The command is safe to run again.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from enum import StrEnum
+from uuid import UUID
+
+from django.db import transaction
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+
+from products.alerts_platform.backend.facade.api import take_ownership, upsert_configuration
+from products.alerts_platform.backend.facade.contracts import PlatformOwnershipHandover
+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
+from products.logs.backend.alert_state_machine import FIRING_STATES
+from products.logs.backend.alert_utils import due_alerts_q
+from products.logs.backend.models import LogsAlertConfiguration
+from products.logs.backend.platform_alert_backfill import PLATFORM_HANDOVER_STATE, platform_upsert_of
+
+State = LogsAlertConfiguration.State
+
+
+class CutoverSkip(StrEnum):
+ """Why an alert stays with the logs stack for now."""
+
+ ALREADY_MOVED = "already_moved"
+ # The two stacks key incidents differently, so a firing moves only after it resolves.
+ FIRING = "firing"
+ # The logs scheduler owes this alert a check, which may already be running and could notify
+ # after the move.
+ CHECK_DUE = "check_due"
+ # A team on live delivery can have the platform copy inside a firing of its own.
+ PLATFORM_FIRING = "platform_firing"
+
+
+@frozen
+class AlertCutover:
+ alert_id: UUID
+ skipped: CutoverSkip | None
+
+
+def cut_over_team(team_id: int, *, now: datetime | None = None) -> tuple[AlertCutover, ...]:
+ """Hands every logs alert of one team to the platform, or says why one stays."""
+ alert_ids = list(
+ LogsAlertConfiguration.objects.filter(team_id=team_id).order_by("created_at", "id").values_list("id", flat=True)
+ )
+ return tuple(AlertCutover(alert_id=alert_id, skipped=_cut_over_alert(alert_id, now)) for alert_id in alert_ids)
+
+
+def _cut_over_alert(alert_id: UUID, now: datetime | None) -> CutoverSkip | None:
+ with transaction.atomic():
+ alert = LogsAlertConfiguration.objects.select_for_update().get(id=alert_id)
+ # Read after the lock, so a check that became due while earlier alerts moved is seen as due.
+ at = now or timezone.now()
+ if alert.platform_owned:
+ return CutoverSkip.ALREADY_MOVED
+ if alert.state in FIRING_STATES:
+ return CutoverSkip.FIRING
+ # A logs check advances `next_check_at` when it saves, so an alert the scheduler does not
+ # owe a check under this lock has no logs check between reading it and notifying for it.
+ if (
+ LogsAlertConfiguration.objects.filter(id=alert.id)
+ .filter(due_alerts_q(at, broken_state=State.BROKEN, snoozed_state=State.SNOOZED))
+ .exists()
+ ):
+ return CutoverSkip.CHECK_DUE
+
+ savepoint = transaction.savepoint()
+ upsert_configuration(platform_upsert_of(alert))
+ taken = take_ownership(
+ PlatformOwnershipHandover(
+ legacy_configuration_id=alert.id,
+ team_id=alert.team_id,
+ state=PLATFORM_HANDOVER_STATE[alert.state],
+ last_notified_at=alert.last_notified_at,
+ consecutive_failures=alert.consecutive_failures,
+ next_check_at=alert.next_check_at or at,
+ at=at,
+ )
+ )
+ if not taken:
+ # The copy stays as live delivery left it. A copy disabled here would drop out of
+ # discovery and never resolve the firing it is inside.
+ transaction.savepoint_rollback(savepoint)
+ return CutoverSkip.PLATFORM_FIRING
+ transaction.savepoint_commit(savepoint)
+ LogsAlertConfiguration.objects.filter(id=alert.id).update(
+ owner=PlatformAlertOwner.PLATFORM, owner_changed_at=at
+ )
+ return None
diff --git a/products/logs/backend/test/test_platform_cutover.py b/products/logs/backend/test/test_platform_cutover.py
new file mode 100644
index 000000000000..5934a8c53deb
--- /dev/null
+++ b/products/logs/backend/test/test_platform_cutover.py
@@ -0,0 +1,118 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+
+from posthog.models.scoping import team_scope
+
+from products.alerts_platform.backend.facade import testing as platform_testing
+from products.alerts_platform.backend.facade.api import get_configuration, upsert_configuration
+from products.alerts_platform.backend.facade.contracts import SourceKind
+from products.logs.backend.models import LogsAlertConfiguration
+from products.logs.backend.platform_alert_backfill import platform_upsert_of
+from products.logs.backend.platform_cutover import CutoverSkip, cut_over_team
+
+NOW = datetime(2026, 10, 13, 12, 0, tzinfo=UTC)
+State = LogsAlertConfiguration.State
+
+
+class TestPlatformCutover(APIBaseTest):
+ def _alert(self, **overrides: Any) -> LogsAlertConfiguration:
+ fields: dict[str, Any] = {
+ "team": self.team,
+ "name": "Errors",
+ "filters": {"severityLevels": ["error"]},
+ "next_check_at": NOW + timedelta(minutes=3),
+ "last_notified_at": NOW - timedelta(days=1),
+ **overrides,
+ }
+ return LogsAlertConfiguration.objects.create(**fields)
+
+ @parameterized.expand(
+ [
+ ("quiet", {}, "not_firing"),
+ (
+ "snoozed_keeps_checking_muted",
+ {"state": State.SNOOZED, "snooze_until": NOW + timedelta(hours=1)},
+ "not_firing",
+ ),
+ ("broken", {"state": State.BROKEN, "consecutive_failures": 5}, "broken"),
+ ("broken_never_scheduled", {"state": State.BROKEN, "next_check_at": None}, "broken"),
+ ("disabled", {"enabled": False, "next_check_at": None}, "not_firing"),
+ ("broken_past_due", {"state": State.BROKEN, "next_check_at": NOW - timedelta(hours=1)}, "broken"),
+ (
+ "snoozed_past_due",
+ {"state": State.SNOOZED, "snooze_until": NOW + timedelta(hours=1), "next_check_at": NOW},
+ "not_firing",
+ ),
+ ]
+ )
+ def test_an_alert_moves_with_its_state_and_schedule(
+ self, _name: str, overrides: dict[str, Any], platform_state: str
+ ) -> None:
+ alert = self._alert(**overrides)
+
+ (result,) = cut_over_team(self.team.id, now=NOW)
+
+ assert result.skipped is None
+ alert.refresh_from_db()
+ assert (alert.owner, alert.owner_changed_at) == ("platform", NOW)
+ with team_scope(self.team.id):
+ copy = platform_testing.copy_of(alert.id)
+ instance = platform_testing.alert_for(copy.id)
+ assert (copy.owner, copy.consecutive_failures, copy.next_check_at) == (
+ "platform",
+ alert.consecutive_failures,
+ max(alert.next_check_at or NOW, NOW + timedelta(minutes=1)),
+ )
+ assert instance is not None
+ assert (instance.state, instance.last_notified_at, instance.snooze_until) == (
+ platform_state,
+ alert.last_notified_at,
+ alert.snooze_until,
+ )
+
+ @parameterized.expand(
+ [
+ ("firing", {"state": State.FIRING}, CutoverSkip.FIRING),
+ ("pending_resolve", {"state": State.PENDING_RESOLVE}, CutoverSkip.FIRING),
+ ("check_due", {"next_check_at": NOW}, CutoverSkip.CHECK_DUE),
+ ("never_scheduled", {"next_check_at": None}, CutoverSkip.CHECK_DUE),
+ ]
+ )
+ def test_an_alert_that_cannot_move_now_stays_with_logs(
+ self, _name: str, overrides: dict[str, Any], reason: CutoverSkip
+ ) -> None:
+ alert = self._alert(**overrides)
+
+ (result,) = cut_over_team(self.team.id, now=NOW)
+
+ assert result.skipped == reason
+ alert.refresh_from_db()
+ assert alert.owner == "source"
+
+ def test_a_refused_cutover_leaves_the_firing_platform_copy_as_it_was(self) -> None:
+ alert = self._alert()
+ upsert_configuration(platform_upsert_of(alert))
+ with team_scope(self.team.id):
+ copy = platform_testing.copy_of(alert.id)
+ platform_testing.start_firing(copy.id, team_id=self.team.id, at=NOW - timedelta(hours=1))
+ LogsAlertConfiguration.objects.filter(id=alert.id).update(enabled=False, next_check_at=None)
+
+ (result,) = cut_over_team(self.team.id, now=NOW)
+
+ assert result.skipped == CutoverSkip.PLATFORM_FIRING
+ view = get_configuration(team_id=self.team.id, source_kinds=[SourceKind.LOGS], configuration_id=copy.id)
+ assert view is not None and view.enabled
+ with team_scope(self.team.id):
+ assert platform_testing.copy_of(alert.id).owner == "source"
+
+ def test_a_second_run_leaves_a_moved_alert_alone(self) -> None:
+ self._alert()
+ cut_over_team(self.team.id, now=NOW)
+
+ (result,) = cut_over_team(self.team.id, now=NOW + timedelta(minutes=1))
+
+ assert result.skipped == CutoverSkip.ALREADY_MOVED