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): carry incident edges to platform delivery (#112990)

Jimmy Zhu4ca3d0490a0a
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index 6805f203658e..f59325a4a198 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -237,7 +237,7 @@ The alerts product imports nothing from a source: the binding holds a name, and
## Logs source evaluation
-`logs-alert-evaluate` evaluates one batch key, a team's alerts due in one minute, and previews one delivery per notification.
+`logs-alert-evaluate` evaluates one batch key, a team's alerts due in one minute, and previews one delivery per notification or incident edge.
The evaluation is a plain function in `products/logs/backend/alert_source_cycle.py`, so a test calls it without Temporal.
It writes its own state and never the logs product's rows.
@@ -343,6 +343,27 @@ Three consequences worth stating:
`AlertCheckOutcome.muted_notification` carries what was held, and
`alerts_platform_notifications_muted_total{source,reason}` counts it by `snooze` or `quiet_hours`.
+### Incident edges ignore cooldown and mute
+
+A paging destination such as PagerDuty holds an incident open until it receives a resolve, so it needs one
+resolve for every trigger. Cooldown and mute hold back announcements while the state still moves, so a paging
+destination cannot follow announcements.
+
+`decide_incident_action` in `facade/lifecycle.py` reads the state before and after a transition: entering a
+firing is a trigger, leaving it for any reason is a resolve. It shares its firing rule with
+`decide_firing_episode`, so a policy that parks a firing alert in SNOOZED keeps its incident open there, and
+a snooze under any other policy ends the firing and resolves the incident.
+The legacy logs stack's `incident_edge` wraps the same rule.
+
+- The source decides the action under its own policy and puts it on `AlertDeliveryRequest.incident_actions`,
+ keyed by grouping key, because the history row does not record the policy.
+- The source sets an action only when the alert has a destination subscribed to its incident events, so an
+ alert without a paging destination starts no extra delivery.
+- A source sends a delivery whenever a check announces or moves a firing. A delivery that exists only for its
+ incident actions has `sends_messages=False`, and none of its rows reach a message destination.
+- `announcement()` also returns the held CHECK row of a group in `incident_grouping_keys`.
+- A mute never holds an incident edge: a fire inside quiet hours or a snooze triggers the incident.
+
A fire a mute swallowed is still owed an announcement.
`_firing_is_unannounced` in `facade/lifecycle.py` decides that, and its docstring holds the rule.
Without it an alert reaches the end of its quiet hours already FIRING, and `renotify_while_firing`
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.py
index bce7d05903a5..b5a05d05a64c 100644
--- a/products/alerts_platform/backend/delivery/evaluation.py
+++ b/products/alerts_platform/backend/delivery/evaluation.py
@@ -94,7 +94,12 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
if team is None or not destinations_are_live(team):
return DeliveryOutcome(live=False, sent=0, skipped_without_transport=0)
- announced = announcement(request.team_id, request.configuration_id, request.evaluation_key)
+ announced = announcement(
+ request.team_id,
+ request.configuration_id,
+ request.evaluation_key,
+ incident_grouping_keys=request.incident_actions.keys(),
+ )
if announced is None:
return DeliveryOutcome(live=True, sent=0, skipped_without_transport=0)
@@ -153,8 +158,11 @@ def _by_subscription(
"""The transitions this evaluation announced, grouped by the event a destination subscribes to.
A kind the source does not map to an event id reaches nobody: no destination can have asked
- for it.
+ for it. Nor does anything on a delivery the source did not announce, which exists only for
+ its incident actions.
"""
+ if not request.sends_messages:
+ return {}
grouped: dict[str, list[AnnouncedTransition]] = {}
for transition in announced.transitions:
event_id = request.event_ids_by_kind.get(transition.kind.value)
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index b6e672434a48..aef58e2c0a1b 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -303,6 +303,12 @@ class AlertDeliveryRequest:
configuration while the platform runs beside a source's own stack. `event_ids_by_kind` maps
each kind the source can announce onto the event id its destinations filter on. The platform
imports no source, so it cannot derive either.
+
+ `incident_actions` maps a grouping key to whether its transition opened or closed a firing.
+ It is a decision rather than a fact a message states, so it travels here like
+ `event_ids_by_kind`. It is set even when cooldown or mute held the announcement back, which
+ is the case it exists for. `sends_messages` is False on a delivery that exists only for those
+ actions, so its rows reach no message destination even when their kind has an event id.
"""
source: SourceKind
@@ -311,6 +317,8 @@ class AlertDeliveryRequest:
evaluation_key: str
destination_alert_id: str
event_ids_by_kind: dict[str, str]
+ incident_actions: dict[str, IncidentAction] = field(default_factory=dict)
+ sends_messages: bool = True
@frozen
diff --git a/products/alerts_platform/backend/facade/lifecycle.py b/products/alerts_platform/backend/facade/lifecycle.py
index b740bbfdd5d5..a2eb423972dd 100644
--- a/products/alerts_platform/backend/facade/lifecycle.py
+++ b/products/alerts_platform/backend/facade/lifecycle.py
@@ -25,7 +25,7 @@ from datetime import datetime, timedelta
from enum import Enum, StrEnum
from typing import Protocol
-from products.alerts_platform.backend.facade.contracts import FiringEpisode
+from products.alerts_platform.backend.facade.contracts import FiringEpisode, IncidentAction
MAX_CONSECUTIVE_FAILURES = 5
@@ -242,14 +242,9 @@ def decide_firing_episode(
parks in SNOOZED with the firing still running underneath the mute, so a caller reading the
two state strings cannot tell that state from a resolve.
"""
- was_firing = snapshot.state in FIRING_STATES or (
- policy.clear_check_ends_snooze and snapshot.state == AlertState.SNOOZED
- )
- if outcome.new_state == AlertState.SNOOZED:
- if not (policy.clear_check_ends_snooze and was_firing):
- return None
- return FiringEpisode(started_at=snapshot.firing_started_at, ended=False)
- if outcome.new_state in FIRING_STATES:
+ was_firing = _inside_firing(snapshot.state, policy)
+ is_firing = _firing_after(was_firing, outcome.new_state, policy)
+ if is_firing:
# A firing that began before the platform recorded starts keeps an unknown one rather
# than taking `now`, because a start later than `last_notified_at` would read as never
# announced.
@@ -260,6 +255,35 @@ def decide_firing_episode(
return FiringEpisode(started_at=snapshot.firing_started_at, ended=True)
+def _inside_firing(state: AlertState, policy: AlertPolicy) -> bool:
+ return state in FIRING_STATES or (policy.clear_check_ends_snooze and state == AlertState.SNOOZED)
+
+
+def _firing_after(was_firing: bool, new_state: AlertState, policy: AlertPolicy) -> bool:
+ # A move into SNOOZED parks a firing only under clear_check_ends_snooze, and never starts one.
+ return _inside_firing(new_state, policy) and (new_state != AlertState.SNOOZED or was_firing)
+
+
+def decide_incident_action(
+ previous_state: AlertState, new_state: AlertState, *, policy: AlertPolicy
+) -> IncidentAction | None:
+ """Whether a transition opens or closes the incident a paging destination holds for the alert.
+
+ Read from the states and never from the notification. Cooldown and mute hold back the
+ announcement while the state still moves, and an incident manager needs one resolve for every
+ trigger it received, so a held resolve must still close the incident. The firing rule is
+ `decide_firing_episode`'s, so a policy that parks a firing alert in SNOOZED keeps its incident
+ open there.
+ """
+ was_firing = _inside_firing(previous_state, policy)
+ is_firing = _firing_after(was_firing, new_state, policy)
+ if is_firing and not was_firing:
+ return IncidentAction.TRIGGER
+ if was_firing and not is_firing:
+ return IncidentAction.RESOLVE
+ return None
+
+
def evaluate_alert_check(
snapshot: AlertSnapshot,
check: CheckInput,
diff --git a/products/alerts_platform/backend/logic/platform_alert_events.py b/products/alerts_platform/backend/logic/platform_alert_events.py
index 25469e788036..d1bd460fd3bf 100644
--- a/products/alerts_platform/backend/logic/platform_alert_events.py
+++ b/products/alerts_platform/backend/logic/platform_alert_events.py
@@ -13,7 +13,7 @@ engine only remembers a bounded window of them.
import json
import hashlib
-from collections.abc import Sequence
+from collections.abc import Collection, Sequence
from dataclasses import fields
from datetime import datetime
from typing import Any
@@ -150,18 +150,25 @@ FROM {PLATFORM_ALERT_EVENTS_TABLE}
WHERE team_id = %(team_id)s
AND configuration_id = %(configuration_id)s
AND evaluation_key = %(evaluation_key)s
- AND kind != %(check_kind)s
+ AND (kind != %(check_kind)s OR has(%(incident_grouping_keys)s, grouping_key))
ORDER BY grouping_key, occurred_at DESC
LIMIT 1 BY grouping_key
"""
-def announcement(team_id: int, configuration_id: str, evaluation_key: str) -> EvaluationAnnouncement | None:
+def announcement(
+ team_id: int,
+ configuration_id: str,
+ evaluation_key: str,
+ *,
+ incident_grouping_keys: Collection[str] = (),
+) -> EvaluationAnnouncement | None:
"""What one evaluation left for a destination to say, or None when it announced nothing.
Rows whose kind is `CHECK` are excluded here rather than in the caller. They are recorded so
a comparison can read every check, and they say nothing, so a message built from one would
- have no headline.
+ have no headline. The exception is a group in `incident_grouping_keys`: cooldown or mute held
+ its announcement, but its firing still opened or closed, and a paging destination needs that row.
`LIMIT 1 BY grouping_key` is the read's own deduplication. The insert carries a token the
engine drops a repeat under, but it only remembers a bounded window of them, so a retry far
@@ -175,6 +182,7 @@ def announcement(team_id: int, configuration_id: str, evaluation_key: str) -> Ev
"configuration_id": configuration_id,
"evaluation_key": evaluation_key,
"check_kind": AlertEventKind.CHECK.value,
+ "incident_grouping_keys": list(incident_grouping_keys),
},
team_id=team_id,
)
diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
index 41448408fe23..d4bf79d3a47b 100644
--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py
+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
@@ -65,7 +65,7 @@ class HeldTransport(RecordingTransport):
raise ThreadBusy("thread is being posted to by another send")
-def _request(team_id: int) -> AlertDeliveryRequest:
+def _request(team_id: int, *, sends_messages: bool = True) -> AlertDeliveryRequest:
return AlertDeliveryRequest(
source=SourceKind.LOGS,
team_id=team_id,
@@ -73,6 +73,7 @@ def _request(team_id: int) -> AlertDeliveryRequest:
evaluation_key="eval-1",
destination_alert_id="legacy-1",
event_ids_by_kind={"firing": FIRING_EVENT, "resolved": RESOLVED_EVENT},
+ sends_messages=sends_messages,
)
@@ -111,6 +112,7 @@ class TestDeliverEvaluation(APIBaseTest):
by_event: dict[str, list[AlertDestinationGroup]],
live: bool = True,
transports: dict[DestinationType, type] | None = None,
+ sends_messages: bool = True,
) -> Any:
def groups(*, team_id: int, alert_id: str, allowed_event_ids: list[str]) -> list[AlertDestinationGroup]:
return by_event.get(allowed_event_ids[0], [])
@@ -122,7 +124,7 @@ class TestDeliverEvaluation(APIBaseTest):
patch(f"{_MODULE}.DatabaseThreadStore"),
patch.dict(f"{_MODULE}._TRANSPORTS", {DestinationType.SLACK: RecordingTransport, **(transports or {})}),
):
- return deliver_evaluation(_request(self.team.id))
+ return deliver_evaluation(_request(self.team.id, sends_messages=sends_messages))
def test_a_destination_hears_only_about_the_kinds_it_subscribed_to(self) -> None:
# One group fires while another resolves. A destination that asked for firings must not
@@ -154,6 +156,17 @@ class TestDeliverEvaluation(APIBaseTest):
"API errors is resolved",
]
+ def test_a_delivery_that_exists_only_for_its_incident_sends_no_message(self) -> None:
+ # Even a kind its destinations subscribe to reaches none of them when the source announced nothing.
+ outcome = self._run(
+ _announcement(_transition(AlertEventKind.RESOLVED)),
+ {RESOLVED_EVENT: [_group(SLACK)]},
+ sends_messages=False,
+ )
+
+ assert RecordingTransport.sends == []
+ assert outcome.sent == 0
+
def test_a_destination_with_no_transport_is_skipped_rather_than_failing_the_send(self) -> None:
outcome = self._run(
_announcement(_transition(AlertEventKind.FIRING)),
diff --git a/products/alerts_platform/backend/tests/test_platform_announcement.py b/products/alerts_platform/backend/tests/test_platform_announcement.py
index f7367f3e2029..f55831ff08ca 100644
--- a/products/alerts_platform/backend/tests/test_platform_announcement.py
+++ b/products/alerts_platform/backend/tests/test_platform_announcement.py
@@ -85,6 +85,25 @@ class TestAnnouncement(ClickhouseTestMixin, APIBaseTest):
assert self._announcement() is None
+ def test_a_held_check_comes_back_only_for_a_group_whose_firing_moved(self) -> None:
+ insert_events(
+ self.team.id,
+ [
+ self._row(grouping_key="checkout", kind=AlertEventKind.CHECK),
+ self._row(grouping_key="search", kind=AlertEventKind.CHECK),
+ ],
+ )
+
+ result = announcement(
+ self.team.id,
+ str(self.configuration.id),
+ "eval-1",
+ incident_grouping_keys=["checkout"],
+ )
+
+ assert result is not None
+ assert [(t.grouping_key, t.kind) for t in result.transitions] == [("checkout", AlertEventKind.CHECK)]
+
def test_every_group_that_announced_gets_its_own_transition(self) -> None:
insert_events(
self.team.id,
diff --git a/products/alerts_platform/backend/tests/test_state_machine.py b/products/alerts_platform/backend/tests/test_state_machine.py
index a489f7ba382d..7f8052b9f645 100644
--- a/products/alerts_platform/backend/tests/test_state_machine.py
+++ b/products/alerts_platform/backend/tests/test_state_machine.py
@@ -2,6 +2,7 @@ from datetime import UTC, datetime, timedelta
from parameterized import parameterized
+from products.alerts_platform.backend.facade.contracts import IncidentAction
from products.alerts_platform.backend.facade.lifecycle import (
LOGS_ALERT_POLICY,
PLATFORM_LOGS_ALERT_POLICY,
@@ -13,6 +14,7 @@ from products.alerts_platform.backend.facade.lifecycle import (
FiringEpisode,
NotificationAction,
decide_firing_episode,
+ decide_incident_action,
evaluate_alert_check,
)
@@ -481,7 +483,15 @@ class TestFiringEpisode:
AlertState.FIRING,
episode(STARTED),
),
- ("snoozed_at_rest", LOGS_ALERT_POLICY, AlertState.FIRING, STARTED, AlertState.SNOOZED, None),
+ # Without clear_check_ends_snooze a snooze is an exit from firing, so it ends the firing.
+ (
+ "snoozed_at_rest",
+ LOGS_ALERT_POLICY,
+ AlertState.FIRING,
+ STARTED,
+ AlertState.SNOOZED,
+ episode(STARTED, ended=True),
+ ),
("snoozed_while_clear", SNOOZE_UNTIL_CLEAR, AlertState.NOT_FIRING, None, AlertState.SNOOZED, None),
# PENDING_RESOLVE is inside the firing: the condition cleared and the resolution is
# not announced yet, so neither leaving nor entering it starts a second firing.
@@ -518,3 +528,32 @@ class TestFiringEpisode:
)
== expected
)
+
+
+class TestIncidentAction:
+ @parameterized.expand(
+ [
+ ("first_fire", LOGS_ALERT_POLICY, AlertState.NOT_FIRING, AlertState.FIRING, IncidentAction.TRIGGER),
+ ("same_firing", LOGS_ALERT_POLICY, AlertState.FIRING, AlertState.FIRING, None),
+ ("resolved", LOGS_ALERT_POLICY, AlertState.FIRING, AlertState.NOT_FIRING, IncidentAction.RESOLVE),
+ ("broken", LOGS_ALERT_POLICY, AlertState.FIRING, AlertState.BROKEN, IncidentAction.RESOLVE),
+ ("never_fired", LOGS_ALERT_POLICY, AlertState.NOT_FIRING, AlertState.NOT_FIRING, None),
+ ("broken_while_clear", LOGS_ALERT_POLICY, AlertState.NOT_FIRING, AlertState.BROKEN, None),
+ # A firing parked in SNOOZED under clear_check_ends_snooze is still the same firing.
+ ("parked", SNOOZE_UNTIL_CLEAR, AlertState.FIRING, AlertState.SNOOZED, None),
+ ("resumed", SNOOZE_UNTIL_CLEAR, AlertState.SNOOZED, AlertState.FIRING, None),
+ ("snoozed_at_rest", LOGS_ALERT_POLICY, AlertState.FIRING, AlertState.SNOOZED, IncidentAction.RESOLVE),
+ ("snoozed_while_clear", SNOOZE_UNTIL_CLEAR, AlertState.NOT_FIRING, AlertState.SNOOZED, None),
+ ("awaiting_resolve", LOGS_ALERT_POLICY, AlertState.FIRING, AlertState.PENDING_RESOLVE, None),
+ ("refired_while_awaiting", LOGS_ALERT_POLICY, AlertState.PENDING_RESOLVE, AlertState.FIRING, None),
+ ]
+ )
+ def test_which_transitions_open_or_close_an_incident(
+ self,
+ _name: str,
+ policy: AlertPolicy,
+ state: AlertState,
+ new_state: AlertState,
+ expected: IncidentAction | None,
+ ) -> None:
+ assert decide_incident_action(state, new_state, policy=policy) == expected
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 2b718ac197e3..1c2bb6cbc33d 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -26,6 +26,7 @@ import structlog
from posthog.dataclasses import frozen
from posthog.models import Team
+from products.alerts.backend.facade.destinations import configured_destination_template_ids
from products.alerts_platform.backend.facade.api import due_checks, slot_of
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
@@ -48,6 +49,7 @@ from products.alerts_platform.backend.facade.lifecycle import (
Outcome,
apply_broken_config,
decide_firing_episode,
+ decide_incident_action,
evaluate_alert_check,
)
from products.alerts_platform.backend.facade.platform_metrics import (
@@ -69,7 +71,12 @@ from products.logs.backend.alert_check_query import (
resolve_alert_date_to,
rolling_check_lookback_minutes,
)
-from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind
+from products.logs.backend.alert_destinations import (
+ EVENT_KIND_CONFIG,
+ LOGS_ALERT_INCIDENT_CLOSED_EVENT,
+ LOGS_ALERT_INCIDENT_OPENED_EVENT,
+ EventKind,
+)
from products.logs.backend.alert_error_classifier import classify as classify_alert_error
# Private to the production activity. Reimplementing either would let this path drift from
@@ -311,18 +318,49 @@ def _delivery(
),
disable=outcome.disable,
)
- if outcome.notification == NotificationAction.NONE:
- return recorded, None
+ return recorded, _request(check, recorded, outcome, sends_messages=outcome.notification != NotificationAction.NONE)
+
+
+def _request(
+ check: PlatformAlertCheckInput, recorded: PlatformAlertOutcome, outcome: Outcome, *, sends_messages: bool
+) -> AlertDeliveryRequest | None:
+ """The delivery for a recorded outcome, or None when it neither announces nor moves a firing.
- return recorded, AlertDeliveryRequest(
+ A firing that opens or closes needs a delivery even when cooldown or mute held the
+ announcement, because a paging destination needs one resolve for every trigger. An alert
+ with no such destination gets no incident action, so its edges start no delivery.
+ """
+ destination_alert_id = str(check.legacy_configuration_id or check.id)
+ incident_action = decide_incident_action(
+ AlertState(check.state), outcome.new_state, policy=PLATFORM_LOGS_ALERT_POLICY
+ )
+ if incident_action is not None and not _has_incident_destination(check.team_id, destination_alert_id):
+ incident_action = None
+ if not sends_messages and incident_action is None:
+ return None
+ return AlertDeliveryRequest(
source=SourceKind.LOGS,
team_id=check.team_id,
configuration_id=str(check.id),
# The recorded key unchanged, so a delivery can address the row the check wrote. The
# workflow id that has to be unique across alerts joins this to the configuration itself.
evaluation_key=recorded.evaluation_key,
- destination_alert_id=str(check.legacy_configuration_id or check.id),
+ destination_alert_id=destination_alert_id,
event_ids_by_kind=_EVENT_IDS_BY_KIND,
+ # Logs does not group, so its one row has the empty grouping key.
+ incident_actions={"": incident_action} if incident_action is not None else {},
+ sends_messages=sends_messages,
+ )
+
+
+def _has_incident_destination(team_id: int, destination_alert_id: str) -> bool:
+ """Whether a destination of this alert follows the incident events. Read only on a firing edge."""
+ return bool(
+ configured_destination_template_ids(
+ team_id=team_id,
+ alert_id=destination_alert_id,
+ allowed_event_ids=(LOGS_ALERT_INCIDENT_OPENED_EVENT, LOGS_ALERT_INCIDENT_CLOSED_EVENT),
+ )
)
@@ -394,7 +432,7 @@ def _held(
_record_check_metrics(
check, new_state=outcome.new_state.value, notification=NotificationAction.NONE, skip=skip, now=now
)
- return recorded, None
+ return recorded, _request(check, recorded, outcome, sends_messages=False)
def _evaluate_cohort(
diff --git a/products/logs/backend/alert_state_machine.py b/products/logs/backend/alert_state_machine.py
index 4bb9d2df654d..d7a37ad979fb 100644
--- a/products/logs/backend/alert_state_machine.py
+++ b/products/logs/backend/alert_state_machine.py
@@ -21,6 +21,7 @@ from datetime import datetime, timedelta
from enum import StrEnum
from typing import TYPE_CHECKING
+from products.alerts_platform.backend.facade.contracts import IncidentAction
from products.alerts_platform.backend.facade.lifecycle import (
FIRING_STATES,
LOGS_ALERT_POLICY,
@@ -39,6 +40,7 @@ from products.alerts_platform.backend.facade.lifecycle import (
apply_threshold_change,
apply_unsnooze,
apply_user_reset,
+ decide_incident_action,
evaluate_alert_check as shared_evaluate_alert_check,
)
@@ -106,18 +108,11 @@ class IncidentCloseReason(StrEnum):
def incident_edge(state_before: str, new_state: str) -> IncidentEdge | None:
- """Whether a transition starts or ends a firing.
-
- Read from the states, not from the notification, because cooldown can suppress a notification
- while the state still moves. An incident manager needs a resolve for every trigger it received.
- """
- was_firing = state_before in FIRING_STATES
- is_firing = new_state in FIRING_STATES
- if is_firing and not was_firing:
- return IncidentEdge.OPENED
- if was_firing and not is_firing:
- return IncidentEdge.CLOSED
- return None
+ """Whether a transition starts or ends a firing, by the shared rule the alerts platform uses."""
+ action = decide_incident_action(AlertState(state_before), AlertState(new_state), policy=LOGS_ALERT_POLICY)
+ if action is None:
+ return None
+ return IncidentEdge.OPENED if action == IncidentAction.TRIGGER else IncidentEdge.CLOSED
def evaluate_alert_check(
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 2fbc6909e044..046a9bd8a978 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -17,12 +17,14 @@ from products.alerts_platform.backend.facade import testing as platform_testing
from products.alerts_platform.backend.facade.api import due_checks, record_outcomes, slot_of
from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
+ IncidentAction,
PlatformConfigurationSnapshot,
SourceBatchEvaluation,
SourceKind,
)
from products.alerts_platform.backend.facade.lifecycle import AlertState
from products.alerts_platform.backend.facade.temporal import SOURCE_EVALUATION_TIMEOUT
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.logs.backend.alert_check_query import BatchedBucketedResult, BucketedCount
from products.logs.backend.alert_source_cycle import BATCH_QUERY_BUDGET_SECONDS, MAX_QUERY_SECONDS, evaluate_logs_batch
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
@@ -62,9 +64,10 @@ class TestLogsAlertEvaluation(APIBaseTest):
*configurations: PlatformConfigurationSnapshot,
query_error: Exception | None = None,
now: datetime | None = None,
+ count: int = 500,
) -> tuple[SourceBatchEvaluation, MagicMock]:
now = now or self.cutoff
- breaching = {str(c.id): [BucketedCount(timestamp=now, count=500)] for c in configurations}
+ breaching = {str(c.id): [BucketedCount(timestamp=now, count=count)] for c in configurations}
with (
patch(f"{_MODULE}.fetch_live_logs_checkpoint", return_value=None),
patch(f"{_MODULE}.BatchedAlertCheckQuery") as query,
@@ -78,6 +81,23 @@ class TestLogsAlertEvaluation(APIBaseTest):
slot = slot_of(configurations[0].next_check_at, now)
return evaluate_logs_batch(self.team.id, slot, now), query
+ def _add_incident_destination(self, configuration: PlatformConfigurationSnapshot) -> None:
+ HogFunction.objects.create(
+ team=self.team,
+ type="internal_destination",
+ name="PagerDuty",
+ template_id="template-pagerduty",
+ hog="return event",
+ enabled=True,
+ filters={
+ "source": "internal-events",
+ "events": [{"id": "$logs_alert_incident_closed", "type": "events"}],
+ "properties": [
+ {"key": "alert_id", "value": str(configuration.id), "operator": "exact", "type": "event"}
+ ],
+ },
+ )
+
def _slot(self) -> str:
return slot_of(self.cutoff - timedelta(minutes=1), self.cutoff)
@@ -89,13 +109,19 @@ class TestLogsAlertEvaluation(APIBaseTest):
"""
record_outcomes(self.team.id, evaluation.outcomes, self.cutoff)
- def test_a_breaching_configuration_fires_and_records_its_own_state(self) -> None:
+ @parameterized.expand([("without_a_paging_destination", False), ("with_a_paging_destination", True)])
+ def test_a_breaching_configuration_fires_and_records_its_own_state(self, _name: str, paged: bool) -> None:
configuration = self._configuration()
+ if paged:
+ self._add_incident_destination(configuration)
evaluation, _ = self._run(configuration)
self._record(evaluation)
assert [(o.kind, o.value) for o in evaluation.outcomes] == [(AlertEventKind.FIRING, 500.0)]
+ assert [(d.sends_messages, d.incident_actions) for d in evaluation.deliveries] == [
+ (True, {"": IncidentAction.TRIGGER} if paged else {})
+ ]
with team_scope(self.team.id):
alert = platform_testing.alert_for(configuration.id)
assert alert is not None
@@ -173,12 +199,16 @@ class TestLogsAlertEvaluation(APIBaseTest):
configuration = self._configuration(
schedule_restriction={"blocked_windows": [{"start": "09:00", "end": "12:00"}]}
)
+ self._add_incident_destination(configuration)
evaluation, query = self._run(configuration)
self._record(evaluation)
query.assert_called_once()
- assert evaluation.deliveries == ()
+ # Quiet hours hold the message, never the incident: the only delivery carries the trigger.
+ assert [(d.sends_messages, d.incident_actions) for d in evaluation.deliveries] == [
+ (False, {"": IncidentAction.TRIGGER})
+ ]
with team_scope(self.team.id):
alert = platform_testing.alert_for(configuration.id)
assert alert is not None
@@ -197,6 +227,22 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert [o.kind for o in unmuted.outcomes] == [AlertEventKind.FIRING]
+ def test_a_resolve_cooldown_holds_still_closes_the_incident(self) -> None:
+ configuration = self._configuration(cooldown_minutes=60)
+ self._add_incident_destination(configuration)
+ fired, _ = self._run(configuration)
+ record_outcomes(self.team.id, fired.outcomes, self.cutoff)
+ with team_scope(self.team.id):
+ configuration = platform_testing.configuration(configuration.id)
+
+ later = datetime(2026, 9, 16, 10, 10, tzinfo=UTC)
+ cleared, _ = self._run(configuration, now=later, count=0)
+
+ assert [o.kind for o in cleared.outcomes] == [AlertEventKind.CHECK]
+ assert [(d.sends_messages, d.incident_actions) for d in cleared.deliveries] == [
+ (False, {"": IncidentAction.RESOLVE})
+ ]
+
def test_a_broken_filter_config_stops_being_discovered(self) -> None:
configuration = self._configuration(source_config={"filterGroup": {"type": "nonsense"}})
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index dc0730a9d2ca..d7d5e835165b 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -299,8 +299,10 @@ class TestSaveCohortOutcomesFallback(APIBaseTest):
class TestResolveNotificationDeliveries(unittest.TestCase):
def _dispatched(self, produce_result, notification_failed=False):
+ evaluation = MagicMock(state_before=LogsAlertConfiguration.State.NOT_FIRING)
+ evaluation.outcome.new_state = AlertState.FIRING
return _DispatchedAlert(
- evaluation=MagicMock(),
+ evaluation=evaluation,
notification_failed=notification_failed,
produce_result=produce_result,
)