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): shadow-evaluate logs alerts the platform owns (#116595)

Jimmy Zhu3b6955d292ba
diff --git a/products/logs/backend/alert_incidents.py b/products/logs/backend/alert_incidents.py
index 07a5259117bd..222a8f16664e 100644
--- a/products/logs/backend/alert_incidents.py
+++ b/products/logs/backend/alert_incidents.py
@@ -3,7 +3,9 @@
from __future__ import annotations
from datetime import UTC, datetime
-from typing import TYPE_CHECKING, Any
+from typing import Any
+
+from django.db import transaction
from products.alerts.backend.facade.destinations import (
alert_internal_event_delivered,
@@ -11,11 +13,10 @@ from products.alerts.backend.facade.destinations import (
flush_alert_internal_events,
produce_alert_internal_event,
)
+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
from products.logs.backend.alert_destinations import LOGS_ALERT_INCIDENT_CLOSED_EVENT, LOGS_ALERT_INCIDENT_OPENED_EVENT
from products.logs.backend.alert_state_machine import IncidentCloseReason
-
-if TYPE_CHECKING:
- from products.logs.backend.models import LogsAlertConfiguration
+from products.logs.backend.models import LogsAlertConfiguration
def has_incident_destination(alert: LogsAlertConfiguration) -> bool:
@@ -55,12 +56,25 @@ def close_incident(
close was queued. A web request passes none, because the flush waits on the process-wide producer.
"""
now = datetime.now(UTC)
- produce_result = produce_alert_internal_event(
- team_id=alert.team_id,
- event_name=LOGS_ALERT_INCIDENT_CLOSED_EVENT,
- properties=incident_closed_properties(alert, reason, now),
- timestamp=now,
- )
+ # The owner is read and the close enqueued under the row lock a cutover also takes, so a
+ # cutover cannot land between the two.
+ with transaction.atomic():
+ owner = (
+ LogsAlertConfiguration.objects.select_for_update()
+ .filter(pk=alert.pk)
+ .values_list("owner", flat=True)
+ .first()
+ )
+ if owner == PlatformAlertOwner.PLATFORM:
+ # The platform closes the incident of an alert it owns. Reported as handed off, so a
+ # caller that waits for the close before a state change does not wait forever.
+ return True
+ produce_result = produce_alert_internal_event(
+ team_id=alert.team_id,
+ event_name=LOGS_ALERT_INCIDENT_CLOSED_EVENT,
+ properties=incident_closed_properties(alert, reason, now),
+ timestamp=now,
+ )
if produce_result is None:
return False
if flush_timeout_seconds is None:
diff --git a/products/logs/backend/alert_utils.py b/products/logs/backend/alert_utils.py
index ae0cda896bc4..2c217932b380 100644
--- a/products/logs/backend/alert_utils.py
+++ b/products/logs/backend/alert_utils.py
@@ -7,6 +7,7 @@ from django.db.models import Q
import structlog
+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
from products.alerts_platform.backend.facade.scheduling import (
advance_next_check_at,
compute_team_shard_offset_seconds,
@@ -77,10 +78,20 @@ def next_allowed_check_at(
return retry_candidate.replace(second=0, microsecond=0)
+# How long the logs stack keeps evaluating an alert after the platform takes it over, so the two
+# stacks' checks can be compared. It sends nothing for the alert in that time.
+PLATFORM_SHADOW = timedelta(days=7)
+
+
def due_alerts_q(now: datetime, *, broken_state: str, snoozed_state: str) -> Q:
return (
Q(enabled=True)
& (Q(next_check_at__lte=now) | Q(next_check_at__isnull=True))
& ~Q(state=broken_state)
& ~Q(state=snoozed_state, snooze_until__gt=now)
+ # A platform-owned row with no cutover time has no shadow to finish, so it is not evaluated.
+ & ~(
+ Q(owner=PlatformAlertOwner.PLATFORM.value)
+ & (Q(owner_changed_at__isnull=True) | Q(owner_changed_at__lt=now - PLATFORM_SHADOW))
+ )
)
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index d0fab9cb8f19..9615dd650bcd 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -252,9 +252,8 @@ class LogsAlertConfiguration(ModelActivityMixin, CreatedMetaFields, UpdatedMetaF
consecutive_failures = models.PositiveIntegerField(default=0)
first_enabled_at = models.DateTimeField(null=True, blank=True)
- # Which stack evaluates and delivers this alert. The platform's copy records the same owner,
- # and only the cutover and rollback commands write the two. After a cutover the logs stack
- # keeps evaluating the alert for a shadow window from `owner_changed_at`, and sends nothing.
+ # The platform's copy records the same owner, and only the cutover and rollback commands
+ # write the two, so each stack can decide from its own row.
owner = models.CharField(
max_length=16,
choices=PlatformAlertOwner.choices,
@@ -272,6 +271,12 @@ class LogsAlertConfiguration(ModelActivityMixin, CreatedMetaFields, UpdatedMetaF
),
]
+ @property
+ def platform_owned(self) -> bool:
+ """The platform evaluates and delivers this alert. The logs stack may still evaluate it to
+ compare, but it sends nothing for it."""
+ return self.owner == PlatformAlertOwner.PLATFORM
+
def __str__(self) -> str:
return f"{self.name} (Team: {self.team})"
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index ef2b2c57b0d5..0cfbc735d938 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -308,6 +308,7 @@ class _DispatchedAlert:
produce_result: ProduceResult | None = None
incident_produce_result: ProduceResult | None = None
suppressed_by_quiet_hours: bool = False
+ shadowed: bool = False
@property
def produced(self) -> bool:
@@ -733,7 +734,8 @@ async def evaluate_cohort_batch_activity(input: EvaluateCohortBatchInput) -> Eva
delivery_slo_handles: dict[str, SloHandle] = {}
for evaluation in evaluations:
delivery_action = evaluation.outcome.notification
- if delivery_action != NotificationAction.NONE:
+ # A shadowed alert sends nothing, so it has no delivery to measure.
+ if delivery_action != NotificationAction.NONE and not evaluation.alert.platform_owned:
alert_id = str(evaluation.alert.id)
delivery_slo_handles[alert_id] = slo_stack.enter_context(
alert_delivery_slo(
@@ -1094,26 +1096,33 @@ def _dispatch_for_alert(evaluation: _AlertEvaluation, now: datetime) -> _Dispatc
suppressed_by_quiet_hours=True,
)
- produce_result = _dispatch_notification(
- evaluation.outcome,
- evaluation.alert,
- evaluation.check_result,
- now,
- date_from=evaluation.date_from,
- date_to=evaluation.date_to,
- )
- edge = incident_edge(evaluation.state_before, evaluation.outcome.new_state)
- incident_expected = edge is not None and has_incident_destination(evaluation.alert)
- incident_produce_result = _dispatch_incident_edge(edge, evaluation, now) if edge and incident_expected else None
- enqueue_failed = (evaluation.outcome.notification != NotificationAction.NONE and produce_result is None) or (
- incident_expected and incident_produce_result is None
- )
- return _DispatchedAlert(
- evaluation=evaluation,
- notification_failed=enqueue_failed,
- produce_result=produce_result,
- incident_produce_result=incident_produce_result,
- )
+ # Decided and enqueued under the row lock a cutover also takes, so a cutover cannot land
+ # between the two. Counted as delivered, so state and cooldown move as they would have. An
+ # owner change since the check read the alert also sends nothing: the row now carries the
+ # other stack's state, which this check never saw, and the save skips it too.
+ if current_alert.platform_owned or current_alert.owner_changed_at != evaluation.alert.owner_changed_at:
+ return _DispatchedAlert(evaluation=evaluation, notification_failed=False, shadowed=True)
+
+ produce_result = _dispatch_notification(
+ evaluation.outcome,
+ evaluation.alert,
+ evaluation.check_result,
+ now,
+ date_from=evaluation.date_from,
+ date_to=evaluation.date_to,
+ )
+ edge = incident_edge(evaluation.state_before, evaluation.outcome.new_state)
+ incident_expected = edge is not None and has_incident_destination(evaluation.alert)
+ incident_produce_result = _dispatch_incident_edge(edge, evaluation, now) if edge and incident_expected else None
+ enqueue_failed = (evaluation.outcome.notification != NotificationAction.NONE and produce_result is None) or (
+ incident_expected and incident_produce_result is None
+ )
+ return _DispatchedAlert(
+ evaluation=evaluation,
+ notification_failed=enqueue_failed,
+ produce_result=produce_result,
+ incident_produce_result=incident_produce_result,
+ )
def _dispatch_incident_edge(edge: IncidentEdge, evaluation: _AlertEvaluation, now: datetime) -> ProduceResult | None:
@@ -1277,20 +1286,28 @@ def _save_cohort_outcomes(
update_ms: int | None = None
saved: list[_DispatchedAlert] = list(dispatched)
failed: list[_DispatchedAlert] = []
+ superseded: list[_DispatchedAlert] = []
try:
with transaction.atomic():
- current_restrictions = dict(
- LogsAlertConfiguration.objects.select_for_update()
+ current = {
+ alert_id: (restriction, owner_changed_at)
+ for alert_id, restriction, owner_changed_at in LogsAlertConfiguration.objects.select_for_update()
.filter(id__in=[d.evaluation.alert.id for d in dispatched])
- .values_list("id", "schedule_restriction")
- )
+ .values_list("id", "schedule_restriction", "owner_changed_at")
+ }
# The worker can evaluate an alert while a user saves quiet hours. Locking
# before staging makes either write order safe: this worker uses the saved
# restriction, or the API waits and then reschedules after this check.
staged: list[tuple[_DispatchedAlert, list[str], LogsAlertEvent | None]] = []
for d in dispatched:
- d.evaluation.alert.schedule_restriction = current_restrictions.get(d.evaluation.alert.id)
+ restriction, owner_changed_at = current.get(d.evaluation.alert.id, (None, None))
+ # A cutover or rollback carried another stack's state onto this row after the check
+ # read it, so this check's state and schedule are stale and are not saved.
+ if owner_changed_at != d.evaluation.alert.owner_changed_at:
+ superseded.append(d)
+ continue
+ d.evaluation.alert.schedule_restriction = restriction
update_fields, event = _stage_alert_for_save(d, now)
staged.append((d, update_fields, event))
@@ -1315,6 +1332,7 @@ def _save_cohort_outcomes(
capture_exception(e, {"cohort_size": len(dispatched), "fallback": "per_alert"})
increment_cohort_save_fallback("integrity_error")
saved, failed = _save_staged_per_alert(staged)
+ saved += superseded
save_ms = int((time.perf_counter() - save_start) * 1000)
with _safe_record_block("cohort save metrics"):
@@ -1342,9 +1360,17 @@ def _save_staged_per_alert(
for d, update_fields, event in staged:
try:
with transaction.atomic():
- if event is not None:
- event.save()
- d.evaluation.alert.save(update_fields=update_fields)
+ # The bulk attempt's locks are gone, so an owner change can have landed since.
+ current_owner_changed_at = (
+ LogsAlertConfiguration.objects.select_for_update()
+ .filter(id=d.evaluation.alert.id)
+ .values_list("owner_changed_at", flat=True)
+ .first()
+ )
+ if current_owner_changed_at == d.evaluation.alert.owner_changed_at:
+ if event is not None:
+ event.save()
+ d.evaluation.alert.save(update_fields=update_fields)
saved.append(d)
except Exception as e:
logger.exception(
@@ -1411,7 +1437,7 @@ def _build_notified_from_saved(saved: list[_DispatchedAlert]) -> list[NotifiedAl
"""
notified: list[NotifiedAlert] = []
for d in saved:
- if d.notification_failed:
+ if d.notification_failed or d.shadowed:
continue
mapping = signal_action_and_weight(d.evaluation.outcome.notification)
if mapping is None:
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index 74279cae2ce6..890eaf7790b6 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -665,27 +665,29 @@ class TestLogsAlertAPI(APIBaseTest):
@parameterized.expand(
[
- ("disable", lambda: {"enabled": False}, True, "disabled"),
+ ("disable", lambda: {"enabled": False}, True, "disabled", "source"),
(
"snooze",
lambda: {"snooze_until": (datetime.now(UTC) + timedelta(hours=1)).isoformat()},
True,
"snoozed",
+ "source",
),
- ("threshold_change", lambda: {"threshold_count": 50}, True, "config_changed"),
- ("filter_change", lambda: {"filters": {"severityLevels": ["warn"]}}, True, "config_changed"),
- ("window_change", lambda: {"window_minutes": 10}, True, None),
- ("rename", lambda: {"name": "Renamed"}, True, None),
- ("disable_without_pagerduty", lambda: {"enabled": False}, False, None),
+ ("threshold_change", lambda: {"threshold_count": 50}, True, "config_changed", "source"),
+ ("filter_change", lambda: {"filters": {"severityLevels": ["warn"]}}, True, "config_changed", "source"),
+ ("window_change", lambda: {"window_minutes": 10}, True, None, "source"),
+ ("rename", lambda: {"name": "Renamed"}, True, None, "source"),
+ ("disable_without_pagerduty", lambda: {"enabled": False}, False, None, "source"),
+ ("disable_owned_by_the_platform", lambda: {"enabled": False}, True, None, "platform"),
]
)
def test_leaving_firing_through_the_api_closes_the_incident(
- self, _name, make_payload, has_pagerduty, expected_reason
+ self, _name, make_payload, has_pagerduty, expected_reason, owner
):
created = self._create_via_api()
if has_pagerduty:
self._add_pagerduty_destination(created["id"])
- LogsAlertConfiguration.objects.filter(pk=created["id"]).update(state="firing")
+ LogsAlertConfiguration.objects.filter(pk=created["id"]).update(state="firing", owner=owner)
payload = make_payload()
with (
diff --git a/products/logs/backend/test/test_due_alerts_q.py b/products/logs/backend/test/test_due_alerts_q.py
index f6027970d64c..503548cdbd6a 100644
--- a/products/logs/backend/test/test_due_alerts_q.py
+++ b/products/logs/backend/test/test_due_alerts_q.py
@@ -34,6 +34,22 @@ class TestDueAlertsQ(BaseTest):
{"state": State.FIRING, "snooze_until": FUTURE},
True,
),
+ (
+ "platform_owned_inside_the_shadow",
+ {"owner": "platform", "owner_changed_at": NOW - timedelta(days=6)},
+ True,
+ ),
+ (
+ "platform_owned_after_the_shadow",
+ {"owner": "platform", "owner_changed_at": NOW - timedelta(days=8)},
+ False,
+ ),
+ ("platform_owned_without_a_cutover_time", {"owner": "platform", "owner_changed_at": None}, False),
+ (
+ "source_owned_long_after_a_rollback",
+ {"owner": "source", "owner_changed_at": NOW - timedelta(days=30)},
+ True,
+ ),
]
)
def test_due_alerts_q(self, _name: str, overrides: dict, expected_due: bool) -> None:
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index d7d5e835165b..f62ca6847917 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -123,6 +123,7 @@ class TestNotifiedAlertCollection(APIBaseTest):
alert: LogsAlertConfiguration,
notification: NotificationAction,
notification_failed: bool,
+ shadowed: bool = False,
) -> _DispatchedAlert:
evaluation = _AlertEvaluation(
alert=alert,
@@ -138,7 +139,7 @@ class TestNotifiedAlertCollection(APIBaseTest):
date_to=datetime(2025, 1, 1, tzinfo=UTC),
state_before="not_firing",
)
- return _DispatchedAlert(evaluation=evaluation, notification_failed=notification_failed)
+ return _DispatchedAlert(evaluation=evaluation, notification_failed=notification_failed, shadowed=shadowed)
def _make_alert(self) -> LogsAlertConfiguration:
return LogsAlertConfiguration.objects.create(
@@ -163,15 +164,16 @@ class TestNotifiedAlertCollection(APIBaseTest):
@parameterized.expand(
[
- ("no_notification", NotificationAction.NONE, False),
- ("not_signalable", NotificationAction.RESOLVE, False),
- ("notification_failed", NotificationAction.FIRE, True),
+ ("no_notification", NotificationAction.NONE, False, False),
+ ("not_signalable", NotificationAction.RESOLVE, False, False),
+ ("notification_failed", NotificationAction.FIRE, True, False),
+ ("shadowed_for_the_platform", NotificationAction.FIRE, False, True),
]
)
- def test_build_notified_from_saved_excludes(self, _name, notification, notification_failed):
+ def test_build_notified_from_saved_excludes(self, _name, notification, notification_failed, shadowed):
alert = self._make_alert()
- notified = _build_notified_from_saved([self._dispatched(alert, notification, notification_failed)])
+ notified = _build_notified_from_saved([self._dispatched(alert, notification, notification_failed, shadowed)])
assert notified == []
@@ -263,6 +265,20 @@ class TestSaveCohortOutcomesFallback(APIBaseTest):
)
return _DispatchedAlert(evaluation=evaluation, notification_failed=False)
+ def test_a_check_read_before_an_ownership_change_saves_nothing_over_the_carried_state(self):
+ alert = self._make_alert(next_check_at=datetime(2025, 1, 1, 0, 0, tzinfo=UTC))
+ dispatched = self._make_dispatched(alert)
+ handed_over_at = datetime(2025, 1, 1, 0, 0, 30, tzinfo=UTC)
+ LogsAlertConfiguration.objects.filter(id=alert.id).update(
+ state="broken", owner="platform", owner_changed_at=handed_over_at
+ )
+
+ saved, failed = _save_cohort_outcomes([dispatched], datetime(2025, 1, 1, 0, 1, tzinfo=UTC))
+
+ assert (saved, failed) == ([dispatched], [])
+ alert.refresh_from_db()
+ assert (alert.state, alert.last_checked_at) == ("broken", None)
+
@patch("products.logs.backend.temporal.activities.LogsAlertConfiguration.objects.bulk_update")
def test_integrity_error_falls_back_to_per_alert(self, mock_bulk_update):
# First call raises IntegrityError (bulk path); per-alert fallback then saves each alert.
@@ -273,15 +289,24 @@ class TestSaveCohortOutcomesFallback(APIBaseTest):
dispatched = [self._make_dispatched(a) for a in alerts]
now = datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC)
+ from products.logs.backend.temporal import activities
+
+ save_per_alert = activities._save_staged_per_alert
+
+ def cut_over_then_save(staged):
+ # A cutover after the bulk attempt released its locks carries the platform's state onto one row.
+ LogsAlertConfiguration.objects.filter(id=alerts[0].id).update(owner="platform", owner_changed_at=now)
+ return save_per_alert(staged)
+
# Should not raise.
- _save_cohort_outcomes(dispatched, now)
+ with patch.object(activities, "_save_staged_per_alert", side_effect=cut_over_then_save):
+ _save_cohort_outcomes(dispatched, now)
- # All three alerts should have been saved via per-alert fallback —
- # advance_next_check_at writes a future next_check_at, so we can verify
- # the fallback ran by checking each alert was persisted.
+ # The other two were saved via per-alert fallback — advance_next_check_at writes a future
+ # next_check_at, so we can verify the fallback ran by checking each alert was persisted.
for alert in alerts:
alert.refresh_from_db()
- assert alert.last_checked_at == now
+ assert [alert.last_checked_at for alert in alerts] == [None, now, now]
@patch("products.logs.backend.temporal.activities.LogsAlertConfiguration.objects.bulk_update")
def test_operational_error_propagates(self, mock_bulk_update):
@@ -730,18 +755,19 @@ class TestEvaluateSingleAlert(APIBaseTest):
@parameterized.expand(
[
- ("without_incident_destination", False, ["$logs_alert_firing"]),
- ("with_incident_destination", True, ["$logs_alert_firing", "$logs_alert_incident_opened"]),
+ ("without_incident_destination", False, "source", ["$logs_alert_firing"]),
+ ("with_incident_destination", True, "source", ["$logs_alert_firing", "$logs_alert_incident_opened"]),
+ ("owned_by_the_platform", True, "platform", []),
]
)
@time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.logs.backend.temporal.activities.produce_alert_internal_event")
def test_threshold_breached_transitions_to_firing(
- self, _name, has_incident_destination, expected_events, mock_produce, mock_query_cls
+ self, _name, has_incident_destination, owner, expected_events, mock_produce, mock_query_cls
):
_mock_buckets(mock_query_cls, [50])
- alert = self._make_alert()
+ alert = self._make_alert(owner=owner)
if has_incident_destination:
_add_incident_destination(alert)
stats = {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}
@@ -751,10 +777,26 @@ class TestEvaluateSingleAlert(APIBaseTest):
alert.refresh_from_db()
assert alert.state == LogsAlertConfiguration.State.FIRING
+ assert alert.last_notified_at == now
assert stats["checked"] == 1
assert stats["fired"] == 1
assert _produced_events(mock_produce) == expected_events
+ @time_machine.travel("2025-01-01T00:01:00Z", tick=False)
+ @patch("products.logs.backend.temporal.activities.AlertCheckQuery")
+ @patch("products.logs.backend.temporal.activities.produce_alert_internal_event")
+ def test_a_check_read_before_a_handback_sends_nothing(self, mock_produce, mock_query_cls):
+ _mock_buckets(mock_query_cls, [50])
+ alert = self._make_alert(owner="platform", owner_changed_at=datetime(2024, 12, 20, tzinfo=UTC))
+ now = datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC)
+ evaluation = _evaluate_single_alert(alert, now)
+ LogsAlertConfiguration.objects.filter(pk=alert.pk).update(owner="source", owner_changed_at=now)
+
+ dispatched = _dispatch_for_alert(evaluation, now)
+
+ assert dispatched.shadowed
+ assert _produced_events(mock_produce) == []
+
@time_machine.travel("2025-01-01T00:01:00Z", tick=False)
@patch("products.logs.backend.temporal.activities.AlertCheckQuery")
@patch("products.logs.backend.temporal.activities.produce_alert_internal_event")
@@ -2216,6 +2258,20 @@ class TestDiscoverCohortsActivity(NonAtomicBaseTest):
assert _produced_events(mock_produce) == ["$logs_alert_incident_closed"]
assert mock_produce.call_args.kwargs["properties"]["alert_id"] == str(broken.id)
+ def test_a_close_for_an_alert_cut_over_after_it_was_read_sends_nothing(self) -> None:
+ from products.logs.backend.alert_incidents import close_incident
+ from products.logs.backend.alert_state_machine import IncidentCloseReason
+
+ alert = LogsAlertConfiguration.objects.create(
+ team=self.team, name="read before cutover", filters={"serviceNames": ["ok"]}, state="firing"
+ )
+ LogsAlertConfiguration.objects.filter(pk=alert.pk).update(owner="platform")
+
+ with patch("products.logs.backend.alert_incidents.produce_alert_internal_event") as mock_produce:
+ assert close_incident(alert, IncidentCloseReason.BROKEN) is True
+
+ mock_produce.assert_not_called()
+
class TestCohortFromManifest(unittest.TestCase):
def test_reconstructs_cohort_from_manifest_and_alerts(self):