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 back from the platform (#116698)

Jimmy Zhu90c3116363b4
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index c50b0f21f729..fb1d2184018c 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -12,11 +12,13 @@ from datetime import datetime
from uuid import UUID
from products.alerts_platform.backend.facade.contracts import (
+ HandbackRefusal,
PlatformAlertCheckInput,
PlatformAlertConfigurationPage,
PlatformAlertConfigurationView,
PlatformAlertOutcome,
PlatformAlertUpsert,
+ PlatformHandback,
PlatformOwnershipHandover,
SourceKind,
)
@@ -70,6 +72,15 @@ def take_ownership(handover: PlatformOwnershipHandover) -> bool:
return platform_lifecycle.take_ownership(handover)
+def give_back_ownership(
+ *, team_id: int, legacy_configuration_id: UUID, at: datetime
+) -> PlatformHandback | HandbackRefusal:
+ """Hands a copied alert back to its source, or says why the platform keeps it."""
+ return platform_lifecycle.give_back_ownership(
+ team_id=team_id, legacy_configuration_id=legacy_configuration_id, at=at
+ )
+
+
def disable_configurations(
source_kind: SourceKind, *, team_id: int | None = None, legacy_configuration_ids: Collection[UUID] | None = None
) -> int:
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 7eb1ea171f00..401df1112478 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -318,6 +318,27 @@ class PlatformOwnershipHandover:
at: datetime
+class HandbackRefusal(StrEnum):
+ """Why the platform keeps an alert its source asked for back."""
+
+ # Firing episodes are keyed per stack, so a firing alert stays until it resolves.
+ FIRING = "firing"
+ # A platform check may be running and could record or notify after the handback.
+ CHECK_DUE = "check_due"
+ # A handback carries one alert on an interval cadence. A calendar schedule or grouped alerts stay.
+ NOT_PORTABLE = "not_portable"
+
+
+@frozen
+class PlatformHandback:
+ """The runtime state the source carries on from when the platform hands an alert back."""
+
+ state: PlatformAlertState
+ last_notified_at: datetime | None
+ consecutive_failures: int
+ next_check_at: datetime | None
+
+
class SkipReason(StrEnum):
"""Why a check reached an outcome without a query answering it.
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 2dcf111cf3e4..e4e015ae14bf 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -21,10 +21,12 @@ from products.alerts_platform.backend.facade.contracts import (
Grouping,
GroupingMode,
GroupOutcome,
+ HandbackRefusal,
InstanceCheckState,
PlatformAlertCheckInput,
PlatformAlertOutcome,
PlatformAlertUpsert,
+ PlatformHandback,
PlatformOwnershipHandover,
source_condition,
)
@@ -705,6 +707,47 @@ def take_ownership(handover: PlatformOwnershipHandover) -> bool:
return True
+def give_back_ownership(
+ *, team_id: int, legacy_configuration_id: UUID, at: datetime
+) -> PlatformHandback | HandbackRefusal:
+ """Hands a copied alert back to its source, or says why the platform keeps it.
+
+ The caller holds the source's row lock and writes the source's owner and state in the same
+ transaction. Raises `PlatformAlertConfiguration.DoesNotExist` when the alert was never copied,
+ and `ValueError` when the platform does not own it, because both owners change together.
+ """
+ with transaction.atomic():
+ configurations = PlatformAlertConfiguration.objects.for_team(team_id).select_for_update()
+ configuration = configurations.get(legacy_configuration_id=legacy_configuration_id)
+ 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):
+ 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):
+ return HandbackRefusal.FIRING
+ # The same rule discovery reads, so an alert discovery skips is never waited on. A check
+ # advances `next_check_at` when it records, so a row not due under this lock has no
+ # platform check between reading the alert and recording it.
+ if configurations.filter(pk=configuration.pk, enabled=True).filter(due_q(at)).exclude(suppressed()).exists():
+ return HandbackRefusal.CHECK_DUE
+
+ handback = PlatformHandback(
+ state=PlatformAlertState(_composed(configuration, alert).state),
+ last_notified_at=alert.last_notified_at if alert is not None else None,
+ consecutive_failures=configuration.consecutive_failures,
+ next_check_at=configuration.next_check_at,
+ )
+ configuration.owner = PlatformAlertOwner.SOURCE
+ configuration.owner_changed_at = at
+ # A check can still be running for a copy that is disabled or not due, and it records only
+ # rows still due, so this keeps it from recording and delivering after the handback.
+ configuration.next_check_at = max(configuration.next_check_at or at, at + _HANDOVER_FENCE)
+ configuration.save(update_fields=["owner", "owner_changed_at", "next_check_at"])
+ return handback
+
+
def disable_configurations(
source_kind: str, *, team_id: int | None = None, legacy_configuration_ids: Collection[UUID] | None = None
) -> int:
diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
index b84419dd2ee2..29c99ebff0c8 100644
--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py
+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py
@@ -15,6 +15,7 @@ from products.alerts_platform.backend.facade import testing as platform_testing
from products.alerts_platform.backend.facade.api import (
disable_configurations,
due_checks,
+ give_back_ownership,
record_outcomes,
slot_of,
take_ownership,
@@ -28,6 +29,7 @@ from products.alerts_platform.backend.facade.contracts import (
Grouping,
GroupingMode,
GroupOutcome,
+ HandbackRefusal,
InstanceCheckState,
PlatformAlertCheckInput,
PlatformAlertOutcome,
@@ -151,6 +153,65 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):
self.configuration.refresh_from_db()
assert (self.configuration.owner, self._alert().state) == ("source", "firing")
+ @parameterized.expand(
+ [
+ ("firing", {}, {"state": "firing"}, HandbackRefusal.FIRING),
+ (
+ "snoozed_inside_a_firing",
+ {},
+ {"state": "snoozed", "firing_started_at": datetime(2026, 9, 16, 9, tzinfo=UTC)},
+ HandbackRefusal.FIRING,
+ ),
+ (
+ "broken_is_never_due",
+ {"next_check_at": datetime(2026, 9, 16, 9, tzinfo=UTC), "check_status": "broken"},
+ {},
+ None,
+ ),
+ (
+ "disabled_while_a_check_runs",
+ {"enabled": False, "next_check_at": datetime(2026, 9, 16, 9, tzinfo=UTC)},
+ {},
+ None,
+ ),
+ ("check_due", {"next_check_at": datetime(2026, 9, 16, 9, tzinfo=UTC)}, {}, HandbackRefusal.CHECK_DUE),
+ (
+ "calendar_schedule",
+ {"recurrence_unit": "daily", "anchor_time": "09:00"},
+ {},
+ HandbackRefusal.NOT_PORTABLE,
+ ),
+ ("grouped", {}, {"grouping_key": "service=api"}, HandbackRefusal.NOT_PORTABLE),
+ ]
+ )
+ def test_the_platform_keeps_an_alert_its_source_cannot_take_back(
+ self,
+ _name: str,
+ configuration_fields: dict[str, Any],
+ alert_fields: dict[str, Any],
+ refusal: HandbackRefusal | None,
+ ) -> None:
+ legacy_id = uuid4()
+ with team_scope(self.team.id):
+ PlatformAlertConfiguration.objects.filter(id=self.configuration.id).update(
+ **{
+ "legacy_configuration_id": legacy_id,
+ "owner": "platform",
+ "next_check_at": self.cutoff + timedelta(minutes=5),
+ **configuration_fields,
+ }
+ )
+ PlatformAlert.objects.create(team=self.team, configuration=self.configuration, **alert_fields)
+
+ handback = give_back_ownership(team_id=self.team.id, legacy_configuration_id=legacy_id, at=self.cutoff)
+
+ assert (handback if isinstance(handback, HandbackRefusal) else None) == refusal
+ self.configuration.refresh_from_db()
+ assert self.configuration.owner == ("platform" if refusal else "source")
+ if refusal is None:
+ # A check that started before the handback finds the row no longer due and records nothing.
+ assert self.configuration.next_check_at is not None and self.configuration.next_check_at > self.cutoff
+
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/roll_back_logs_alerts_from_platform.py b/products/logs/backend/management/commands/roll_back_logs_alerts_from_platform.py
new file mode 100644
index 000000000000..4cf4c1590cca
--- /dev/null
+++ b/products/logs/backend/management/commands/roll_back_logs_alerts_from_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 roll_back_team
+
+
+class Command(BaseCommand):
+ help = "Hand one team's logs alerts back from 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 back.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ results = roll_back_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_back") for result in results)
+ self.stdout.write(f"team={options['team_id']} {dict(outcomes) or 'no alerts'}")
diff --git a/products/logs/backend/migrations/0027_logsalertevent_handback_kind.py b/products/logs/backend/migrations/0027_logsalertevent_handback_kind.py
new file mode 100644
index 000000000000..85d9eac60551
--- /dev/null
+++ b/products/logs/backend/migrations/0027_logsalertevent_handback_kind.py
@@ -0,0 +1,31 @@
+# Generated by Django 5.2.18 on 2026-10-14 18:58
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("logs", "0026_logsalertconfiguration_owner"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="logsalertevent",
+ name="kind",
+ field=models.CharField(
+ choices=[
+ ("check", "Check"),
+ ("reset", "Reset"),
+ ("enable", "Enable"),
+ ("disable", "Disable"),
+ ("snooze", "Snooze"),
+ ("unsnooze", "Unsnooze"),
+ ("threshold_change", "Threshold change"),
+ ("broken_config", "Broken config"),
+ ("handback", "Handback"),
+ ],
+ default="check",
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/products/logs/backend/migrations/max_migration.txt b/products/logs/backend/migrations/max_migration.txt
index b26ac163d0cb..24dc7f895262 100644
--- a/products/logs/backend/migrations/max_migration.txt
+++ b/products/logs/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0026_logsalertconfiguration_owner
+0027_logsalertevent_handback_kind
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index 9615dd650bcd..da48dac6dfec 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -374,6 +374,8 @@ class LogsAlertEvent(UUIDModel):
UNSNOOZE = "unsnooze", "Unsnooze"
THRESHOLD_CHANGE = "threshold_change", "Threshold change"
BROKEN_CONFIG = "broken_config", "Broken config"
+ # An operator handed the alert back from the alerts platform, carrying its state over.
+ HANDBACK = "handback", "Handback"
alert = models.ForeignKey(
LogsAlertConfiguration,
diff --git a/products/logs/backend/platform_alert_backfill.py b/products/logs/backend/platform_alert_backfill.py
index 76cb0e210971..8a5f906bc0df 100644
--- a/products/logs/backend/platform_alert_backfill.py
+++ b/products/logs/backend/platform_alert_backfill.py
@@ -10,6 +10,7 @@ rather than duplicates, and a later comparison can line the two stacks up per al
"""
from collections.abc import Collection
+from datetime import datetime
from typing import Final
from uuid import UUID
@@ -20,6 +21,7 @@ from posthog.dataclasses import frozen
from products.alerts_platform.backend.facade.api import disable_configurations, upsert_configuration, upsert_if_running
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_state_machine import AlertState
from products.logs.backend.models import LogsAlertConfiguration
logger = structlog.get_logger(__name__)
@@ -74,6 +76,31 @@ PLATFORM_HANDOVER_STATE: Final[dict[str, PlatformAlertState]] = {
}
+def logs_state_after_handback(
+ alert: LogsAlertConfiguration, platform_state: PlatformAlertState, at: datetime
+) -> AlertState:
+ """The logs state for an alert the platform hands back, the inverse of `PLATFORM_HANDOVER_STATE`.
+
+ The platform keeps a mute on `snooze_until` rather than as a state, and the logs API kept
+ writing snoozes to the logs row, so an active one stays the logs state.
+ """
+ if (
+ alert.state == LogsAlertConfiguration.State.SNOOZED
+ and alert.snooze_until is not None
+ and alert.snooze_until > at
+ ):
+ return AlertState.SNOOZED
+ return _LOGS_STATE_AFTER_HANDBACK[platform_state]
+
+
+_LOGS_STATE_AFTER_HANDBACK: Final[dict[PlatformAlertState, AlertState]] = {
+ PlatformAlertState.NOT_FIRING: AlertState.NOT_FIRING,
+ PlatformAlertState.SNOOZED: AlertState.NOT_FIRING,
+ PlatformAlertState.ERRORED: AlertState.ERRORED,
+ PlatformAlertState.BROKEN: AlertState.BROKEN,
+}
+
+
def _is_team_sampled(team_id: int, sample_percent: int) -> bool:
"""Whether a team falls inside a sample.
diff --git a/products/logs/backend/platform_cutover.py b/products/logs/backend/platform_cutover.py
index 9ddf667420b0..3096a8a231d3 100644
--- a/products/logs/backend/platform_cutover.py
+++ b/products/logs/backend/platform_cutover.py
@@ -1,4 +1,4 @@
-"""Hands a team's logs alerts to the alerts platform, one alert at a time.
+"""Hands a team's logs alerts to the alerts platform and back, 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.
@@ -15,14 +15,18 @@ 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.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.enums import PlatformAlertOwner
-from products.logs.backend.alert_state_machine import FIRING_STATES
+from products.logs.backend.alert_state_machine import FIRING_STATES, ControlPlaneOutcome, apply_outcome
from products.logs.backend.alert_utils import due_alerts_q
from products.logs.backend.cutover_gate import CutoverRefused, TeamGate
-from products.logs.backend.models import LogsAlertConfiguration
-from products.logs.backend.platform_alert_backfill import PLATFORM_HANDOVER_STATE, platform_upsert_of
+from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
+from products.logs.backend.platform_alert_backfill import (
+ PLATFORM_HANDOVER_STATE,
+ logs_state_after_handback,
+ platform_upsert_of,
+)
State = LogsAlertConfiguration.State
@@ -48,6 +52,22 @@ class AlertCutover:
skipped: CutoverSkip | None
+def _team_alert_ids(team_id: int) -> list[UUID]:
+ return list(
+ LogsAlertConfiguration.objects.filter(team_id=team_id).order_by("created_at", "id").values_list("id", flat=True)
+ )
+
+
+def _logs_check_owed(alert_id: UUID, at: datetime) -> bool:
+ # A logs check advances `next_check_at` when it saves, so an alert the scheduler does not owe
+ # a check under the caller's lock has no logs check between reading it and notifying for it.
+ return (
+ LogsAlertConfiguration.objects.filter(id=alert_id)
+ .filter(due_alerts_q(at, broken_state=State.BROKEN, snoozed_state=State.SNOOZED))
+ .exists()
+ )
+
+
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.
@@ -58,11 +78,9 @@ def cut_over_team(team_id: int, *, now: datetime | None = None) -> tuple[AlertCu
refusals = gate.refusals()
if refusals:
raise CutoverRefused(team_id, refusals)
- 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, gate, now)) for alert_id in alert_ids
+ AlertCutover(alert_id=alert_id, skipped=_cut_over_alert(alert_id, gate, now))
+ for alert_id in _team_alert_ids(team_id)
)
@@ -75,13 +93,7 @@ def _cut_over_alert(alert_id: UUID, gate: TeamGate, now: datetime | None) -> Cut
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()
- ):
+ if _logs_check_owed(alert.id, at):
return CutoverSkip.CHECK_DUE
# Locks the alert's destinations, so no edit lands between this check and the move.
if gate.alert_refusals(alert.id, lock=True):
@@ -110,3 +122,66 @@ def _cut_over_alert(alert_id: UUID, gate: TeamGate, now: datetime | None) -> Cut
owner=PlatformAlertOwner.PLATFORM, owner_changed_at=at
)
return None
+
+
+class RollbackSkip(StrEnum):
+ """Why an alert stays with the platform for now."""
+
+ NOT_MOVED = "not_moved"
+ # During the shadow the logs stack still checks the alert, and a check it started would save
+ # over the state carried back.
+ LOGS_CHECK_DUE = "logs_check_due"
+ PLATFORM_FIRING = "platform_firing"
+ PLATFORM_CHECK_DUE = "platform_check_due"
+ NOT_PORTABLE = "not_portable"
+
+
+_ROLLBACK_SKIP: dict[HandbackRefusal, RollbackSkip] = {
+ HandbackRefusal.FIRING: RollbackSkip.PLATFORM_FIRING,
+ HandbackRefusal.CHECK_DUE: RollbackSkip.PLATFORM_CHECK_DUE,
+ HandbackRefusal.NOT_PORTABLE: RollbackSkip.NOT_PORTABLE,
+}
+
+
+@frozen
+class AlertRollback:
+ alert_id: UUID
+ skipped: RollbackSkip | None
+
+
+def roll_back_team(team_id: int, *, now: datetime | None = None) -> tuple[AlertRollback, ...]:
+ """Hands every logs alert of one team back from the platform, or says why one stays."""
+ return tuple(
+ AlertRollback(alert_id=alert_id, skipped=_roll_back_alert(alert_id, now))
+ for alert_id in _team_alert_ids(team_id)
+ )
+
+
+def _roll_back_alert(alert_id: UUID, now: datetime | None) -> RollbackSkip | None:
+ with transaction.atomic():
+ alert = LogsAlertConfiguration.objects.select_for_update().get(id=alert_id)
+ # Read after the lock, for the same reason as the cutover.
+ at = now or timezone.now()
+ if not alert.platform_owned:
+ return RollbackSkip.NOT_MOVED
+ if _logs_check_owed(alert.id, at):
+ return RollbackSkip.LOGS_CHECK_DUE
+
+ handback = give_back_ownership(team_id=alert.team_id, legacy_configuration_id=alert.id, at=at)
+ if isinstance(handback, HandbackRefusal):
+ return _ROLLBACK_SKIP[handback]
+
+ update_fields = apply_outcome(
+ alert,
+ ControlPlaneOutcome(
+ new_state=logs_state_after_handback(alert, handback.state, at),
+ consecutive_failures=handback.consecutive_failures,
+ ),
+ kind=LogsAlertEvent.Kind.HANDBACK,
+ )
+ alert.owner = PlatformAlertOwner.SOURCE
+ alert.owner_changed_at = at
+ alert.last_notified_at = handback.last_notified_at
+ alert.next_check_at = handback.next_check_at
+ alert.save(update_fields=[*update_fields, "owner", "owner_changed_at", "last_notified_at", "next_check_at"])
+ return None
diff --git a/products/logs/backend/test/test_platform_cutover.py b/products/logs/backend/test/test_platform_cutover.py
index b43bbd9747ff..d4bd2ff3689a 100644
--- a/products/logs/backend/test/test_platform_cutover.py
+++ b/products/logs/backend/test/test_platform_cutover.py
@@ -17,9 +17,9 @@ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.models.hog_functions.hog_function_revision import HogFunctionRevision
from products.logs.backend.alert_destinations import LOGS_ALERT_EVENT_IDS
from products.logs.backend.cutover_gate import CutoverRefused, GateRefusal, TeamGate
-from products.logs.backend.models import LogsAlertConfiguration
+from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
from products.logs.backend.platform_alert_backfill import platform_upsert_of
-from products.logs.backend.platform_cutover import CutoverSkip, cut_over_team
+from products.logs.backend.platform_cutover import CutoverSkip, RollbackSkip, cut_over_team, roll_back_team
NOW = datetime(2026, 10, 13, 12, 0, tzinfo=UTC)
State = LogsAlertConfiguration.State
@@ -136,6 +136,67 @@ class TestPlatformCutover(APIBaseTest):
assert result.skipped == CutoverSkip.ALREADY_MOVED
+ def _moved(self, **overrides: Any) -> LogsAlertConfiguration:
+ alert = self._alert(**overrides)
+ cut_over_team(self.team.id, now=NOW)
+ alert.refresh_from_db()
+ return alert
+
+ def test_rolling_back_after_the_shadow_carries_the_platform_state_back(self) -> None:
+ alert = self._moved(state=State.BROKEN, consecutive_failures=5)
+ later = NOW + timedelta(days=8)
+ with team_scope(self.team.id):
+ platform_testing.set_due_at(platform_testing.copy_of(alert.id).id, later + timedelta(minutes=2))
+
+ (result,) = roll_back_team(self.team.id, now=later)
+
+ assert result.skipped is None
+ alert.refresh_from_db()
+ assert (alert.owner, alert.owner_changed_at, alert.state, alert.consecutive_failures, alert.next_check_at) == (
+ "source",
+ later,
+ State.BROKEN,
+ 5,
+ later + timedelta(minutes=2),
+ )
+ assert list(alert.events.values_list("kind", "state_before", "state_after")) == [
+ (LogsAlertEvent.Kind.HANDBACK, State.BROKEN, State.BROKEN)
+ ]
+ with team_scope(self.team.id):
+ assert platform_testing.copy_of(alert.id).owner == "source"
+
+ def test_rolling_back_keeps_an_active_logs_snooze(self) -> None:
+ alert = self._moved()
+ LogsAlertConfiguration.objects.filter(id=alert.id).update(
+ state=State.SNOOZED, snooze_until=NOW + timedelta(days=30)
+ )
+ later = NOW + timedelta(days=8)
+ with team_scope(self.team.id):
+ platform_testing.set_due_at(platform_testing.copy_of(alert.id).id, later + timedelta(minutes=2))
+
+ (result,) = roll_back_team(self.team.id, now=later)
+
+ assert result.skipped is None
+ alert.refresh_from_db()
+ assert (alert.owner, alert.state) == ("source", State.SNOOZED)
+
+ @parameterized.expand(
+ [
+ ("never_moved", False, NOW + timedelta(days=8), RollbackSkip.NOT_MOVED),
+ ("logs_check_due_during_shadow", True, NOW + timedelta(minutes=10), RollbackSkip.LOGS_CHECK_DUE),
+ ]
+ )
+ def test_an_alert_that_cannot_move_back_now_stays(
+ self, _name: str, moved: bool, at: datetime, reason: RollbackSkip
+ ) -> None:
+ alert = self._moved() if moved else self._alert()
+
+ (result,) = roll_back_team(self.team.id, now=at)
+
+ assert result.skipped == reason
+ alert.refresh_from_db()
+ assert alert.owner == ("platform" if moved else "source")
+
def _destination(
self, alert_id: UUID | None, template_id: str, inputs: dict[str, Any], edit: dict[str, Any] | None = None
) -> HogFunction:
diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
index d13d6351f09e..c8dcd5ad7c3d 100644
--- a/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertEventHistory.tsx
@@ -134,6 +134,7 @@ const CONTROL_PLANE_DESCRIPTIONS: Record<
[LogsAlertEventKindEnumApi.Unsnooze]: { label: 'Unsnoozed', type: 'highlight' },
[LogsAlertEventKindEnumApi.ThresholdChange]: { label: 'Threshold changed', type: 'completion' },
[LogsAlertEventKindEnumApi.BrokenConfig]: { label: 'Broken config', type: 'caution' },
+ [LogsAlertEventKindEnumApi.Handback]: { label: 'State restored', type: 'default' },
}
function describeEvent(event: LogsAlertEventApi): EventDescription {
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 51ade1a41c63..576ca0951ce8 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -998,6 +998,7 @@ export interface LogsAlertDeleteDestinationApi {
* * `unsnooze` - Unsnooze
* * `threshold_change` - Threshold change
* * `broken_config` - Broken config
+ * * `handback` - Handback
*/
export type LogsAlertEventKindEnumApi = (typeof LogsAlertEventKindEnumApi)[keyof typeof LogsAlertEventKindEnumApi]
@@ -1010,6 +1011,7 @@ export const LogsAlertEventKindEnumApi = {
Unsnooze: 'unsnooze',
ThresholdChange: 'threshold_change',
BrokenConfig: 'broken_config',
+ Handback: 'handback',
} as const
export interface LogsAlertEventApi {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 48c3b40fae55..9f8cfcfb1daa 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -63045,6 +63045,7 @@ export namespace Schemas {
* * `unsnooze` - Unsnooze
* * `threshold_change` - Threshold change
* * `broken_config` - Broken config
+ * * `handback` - Handback
*/
export type LogsAlertEventKindEnum = typeof LogsAlertEventKindEnum[keyof typeof LogsAlertEventKindEnum];
@@ -63058,6 +63059,7 @@ export namespace Schemas {
Unsnooze: 'unsnooze',
ThresholdChange: 'threshold_change',
BrokenConfig: 'broken_config',
+ Handback: 'handback',
} as const;
export interface LogsAlertEvent {