: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): announce a held fire when a mute ends (#104862)
Jimmy Zhu1c0b588a7ad5
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.mdindex edf109826573..734421fec33a 100644--- a/docs/internal/alerts-platform-temporal.md+++ b/docs/internal/alerts-platform-temporal.md@@ -343,6 +343,16 @@ 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`.+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`+is false, so nobody is ever told.+A recovery that happened entirely inside a mute is not announced when the mute lifts, which is what+Datadog does and what a person muting an alert expects.+Production logs gets the same reset on snooze expiry, by way of the SNOOZED branch in+`evaluate_alert_check`; under mute semantics the state is never SNOOZED, so the reset needs its own+signal.+### Evaluating and writing are separate activities`evaluate_logs_alerts_activity` reads and decides; it writes nothing.diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.pyindex 33c95c2aff8f..8c339fe443fc 100644--- a/products/alerts/backend/facade/contracts.py+++ b/products/alerts/backend/facade/contracts.py@@ -163,8 +163,9 @@ class AlertEventKind(StrEnum):"""What one evaluation announced about an alert.`CHECK` is an evaluation that announced nothing, which includes one that moved the alert while- a cooldown or a mute held the notification back. Read `previous_state` and `state` to find the- moves, because counting `RESOLVED` rows misses every recovery that was suppressed.+ a cooldown or a mute held the notification back. Read the history row's `previous_state` and+ `state` to find the moves, because counting `RESOLVED` rows misses every recovery that was+ suppressed.A source reports the kind rather than the platform deriving it: the machine already decidedwhat to announce, and deriving it again from the states would be a second implementation of@@ -222,16 +223,30 @@ class PlatformAlertOutcome:@frozenclass GroupTransition:- """One transition a delivery would carry. `grouping_key` is empty until a source groups,- so delivery reads a list of one today and a list of N when fan-out ships."""+ """One transition a delivery carries: `kind` picks the headline, `value` is the number it+ quotes.++ `grouping_key` is empty until a source groups, so delivery reads a list of one today and a+ list of N when fan-out ships.++ The condition and the source config a message also needs stay on the history row the+ delivery addresses, because `source_config` is an unbounded filter tree and one per+ transition would blow the payload bound `MAX_PREVIEWS_PER_CYCLE` was sized against.+ """grouping_key: str- notification: str+ kind: AlertEventKind+ value: float | None = None@frozenclass AlertDeliveryPreview:- """What delivery would send. The PoC records it instead of contacting a destination."""+ """What delivery would send. The PoC records it instead of contacting a destination.++ `alert_id` is the configuration's id, which a history row carries as `configuration_id`, not+ as its own `alert_id` column. A delivery addresses its rows by that column, the transition's+ `grouping_key` and `evaluation_key` together; joining on the row's `alert_id` finds nothing.+ """source: SourceKindalert_id: strdiff --git a/products/alerts/backend/facade/lifecycle.py b/products/alerts/backend/facade/lifecycle.pyindex 1df3e31b84f7..fb54212416de 100644--- a/products/alerts/backend/facade/lifecycle.py+++ b/products/alerts/backend/facade/lifecycle.py@@ -214,6 +214,21 @@ def _muted(outcome: AlertCheckOutcome) -> AlertCheckOutcome:)+def _firing_is_unannounced(snapshot: AlertSnapshot) -> bool:+ """Whether the firing the alert is in was never announced, so one is still owed.++ Derived rather than stored, because the two timestamps already say it: a firing that was+ announced has a notification at or after its start. A mute, a cooldown or any other gate+ leaves `last_notified_at` behind the start, which is exactly the set of fires still owed.++ A firing that began before the platform recorded starts has no start to compare, and reads as+ announced. Reading it the other way re-fires it on every later check, forever.+ """+ if snapshot.firing_started_at is None:+ return False+ return snapshot.last_notified_at is None or snapshot.last_notified_at < snapshot.firing_started_at++def decide_firing_episode(snapshot: AlertSnapshot, outcome: Outcome, now: datetime, *, policy: AlertPolicy) -> FiringEpisode | None:@@ -318,6 +333,12 @@ def evaluate_alert_check(elif snapshot.state in (AlertState.ERRORED, AlertState.BROKEN):# BROKEN is only reachable here when the policy allows checks to un-break.effective_state = AlertState.NOT_FIRING+ elif policy.mute_gates_notification_only and not muted and _firing_is_unannounced(snapshot):+ # Re-evaluating from scratch is what makes a condition that survived the mute announce+ # itself, and is what the SNOOZED arm does for an expired snooze. Last in the chain, so a+ # state that names its own re-entry keeps it: under `clear_check_ends_snooze` a parked+ # breach reads as unannounced and still has to re-enter as FIRING to resolve.+ effective_state = AlertState.NOT_FIRINGelse:effective_state = snapshot.statediff --git a/products/alerts/backend/temporal/workflows.py b/products/alerts/backend/temporal/workflows.pyindex 309726a7c6d9..d66806d36d41 100644--- a/products/alerts/backend/temporal/workflows.py+++ b/products/alerts/backend/temporal/workflows.py@@ -103,7 +103,7 @@ async def alerts_platform_deliver_preview_activity(preview: AlertDeliveryPreviewevaluation_key=preview.evaluation_key,destinations=list(preview.destination_names),transitions=[- {"grouping_key": transition.grouping_key, "notification": transition.notification}+ {"grouping_key": transition.grouping_key, "kind": transition.kind.value, "value": transition.value}for transition in preview.transitions],)diff --git a/products/alerts/backend/test/test_platform_lifecycle.py b/products/alerts/backend/test/test_platform_lifecycle.pyindex 76c0b826f2d0..dd2595b7fe5e 100644--- a/products/alerts/backend/test/test_platform_lifecycle.py+++ b/products/alerts/backend/test/test_platform_lifecycle.py@@ -36,10 +36,11 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):)self.slot = (self.cutoff - timedelta(minutes=1)).isoformat()- def _record(self, now: datetime | None = None, **overrides) -> None:+ def _record(self, *, at: datetime | None = None, **overrides) -> None:+ at = at or self.cutofffields = {"configuration_id": self.configuration.id,- "evaluation_key": f"window:{self.cutoff.isoformat()}",+ "evaluation_key": f"window:{at.isoformat()}","kind": AlertEventKind.FIRING,"new_state": "firing","notified": True,@@ -48,7 +49,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):fields.update(overrides)# History rides `transaction.on_commit`, which a `TestCase` transaction never reaches.with self.captureOnCommitCallbacks(execute=True):- record_outcomes(self.team.id, [PlatformAlertOutcome(**fields)], now or self.cutoff)+ record_outcomes(self.team.id, [PlatformAlertOutcome(**fields)], at)def _alert(self) -> PlatformAlert:with team_scope(self.team.id):@@ -62,7 +63,7 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):self._record(new_state="not_firing",firing_episode=FiringEpisode(started_at=self.cutoff, ended=True),- now=self.cutoff + timedelta(hours=1),+ at=self.cutoff + timedelta(hours=1),)assert self._alert().firing_started_at is Nonediff --git a/products/alerts/backend/test/test_state_machine.py b/products/alerts/backend/test/test_state_machine.pyindex fd7978a0ab44..01539bd2a789 100644--- a/products/alerts/backend/test/test_state_machine.py+++ b/products/alerts/backend/test/test_state_machine.py@@ -285,6 +285,70 @@ class TestPolicyDecisionTable:NotificationAction.ERROR,NotificationAction.NONE,),+ (+ "unmute_announces_a_held_fire",+ snapshot(state=AlertState.FIRING, firing_started_at=NOW, last_notified_at=None),+ BREACH,+ AlertState.FIRING,+ NotificationAction.FIRE,+ NotificationAction.NONE,+ ),+ (+ "unmute_stays_quiet_when_the_condition_cleared",+ snapshot(state=AlertState.FIRING, firing_started_at=NOW, last_notified_at=None),+ CLEAR,+ AlertState.NOT_FIRING,+ NotificationAction.NONE,+ NotificationAction.NONE,+ ),+ (+ # Without the mute guard, this re-enters NOT_FIRING and reports a held FIRE on+ # every check for the length of the mute.+ "a_steady_muted_fire_is_not_held_again",+ snapshot(+ state=AlertState.FIRING,+ firing_started_at=NOW,+ last_notified_at=None,+ snooze_until=SNOOZING,+ ),+ BREACH,+ AlertState.FIRING,+ NotificationAction.NONE,+ NotificationAction.NONE,+ ),+ (+ "a_firing_announced_at_its_start_does_not_refire",+ snapshot(state=AlertState.FIRING, firing_started_at=NOW, last_notified_at=NOW),+ BREACH,+ AlertState.FIRING,+ NotificationAction.NONE,+ NotificationAction.NONE,+ ),+ (+ # No start to compare, so the firing reads as announced. The other reading re-fires+ # it on every later check.+ "a_firing_with_no_recorded_start_does_not_refire",+ snapshot(state=AlertState.FIRING, firing_started_at=None, last_notified_at=NOW - timedelta(hours=1)),+ BREACH,+ AlertState.FIRING,+ NotificationAction.NONE,+ NotificationAction.NONE,+ ),+ (+ # A cooldown leaves the same pair of timestamps a mute does, so the fire it+ # suppressed is owed an announcement once the cooldown is over.+ "a_cooldown_suppressed_fire_is_still_owed",+ snapshot(+ state=AlertState.FIRING,+ firing_started_at=NOW,+ last_notified_at=NOW - timedelta(minutes=20),+ cooldown=timedelta(0),+ ),+ BREACH,+ AlertState.FIRING,+ NotificationAction.FIRE,+ NotificationAction.NONE,+ ),("an_unmuted_check_still_announces",snapshot(),diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex 654948a78e50..f55d34552e72 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -298,8 +298,7 @@ def _delivery(if outcome.notification == NotificationAction.NONE:return recorded, None- kind = _NOTIFICATION_OUTCOME_KINDS[outcome.notification]- spec = EVENT_KIND_CONFIG[cast(EventKind, kind.value)]+ spec = EVENT_KIND_CONFIG[cast(EventKind, recorded.kind.value)]destinations = list_active_alert_destinations(team_id=check.team_id,alert_id=str(check.legacy_configuration_id or check.id),@@ -309,14 +308,13 @@ def _delivery(source=SourceKind.LOGS,alert_id=str(check.id),alert_name=check.name,- # The recorded key, not a second construction of one. This becomes the delivery child- # workflow id, so a key without the slot lets two scheduled checks that clamped to the- # same window end collide and drops the later announcement.- evaluation_key=f"{check.id}:{recorded.evaluation_key}",+ # 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 `alert_id` itself.+ evaluation_key=recorded.evaluation_key,destination_names=tuple(destination.name for destination in destinations),# One transition with an empty grouping key. Logs does not group yet, and delivery# reads a list either way, so fan-out changes this call and nothing downstream.- transitions=(GroupTransition(grouping_key="", notification=outcome.notification.value),),+ transitions=(GroupTransition(grouping_key="", kind=recorded.kind, value=recorded.value),),)diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.pyindex 1a2a9dabb8f6..ff4983aa4e71 100644--- a/products/logs/backend/temporal/alert_evaluate.py+++ b/products/logs/backend/temporal/alert_evaluate.py@@ -95,15 +95,16 @@ class LogsAlertEvaluateWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=3),)- # The evaluation key names the alert and its window, so a re-run of the same occasion- # reuses these ids. A reused id raises, so one already-started preview must not stop- # the rest.+ # The evaluation key names the window and the slot but not the alert, because a delivery+ # addresses the history row with it. The id joins the two, so two alerts in one slot do+ # not collide. A re-run of the same occasion reuses these ids, and a reused id raises, so+ # one already-started preview must not stop the rest.results = await asyncio.gather(*(workflow.start_child_workflow("alerts-platform-deliver-preview",preview,- id=f"alerts-deliver-preview-{preview.evaluation_key}",+ id=f"alerts-deliver-preview-{preview.alert_id}:{preview.evaluation_key}",task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,parent_close_policy=workflow.ParentClosePolicy.ABANDON,execution_timeout=dt.timedelta(minutes=1),diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.pyindex 4dc6a5de8f69..37bf1caa511b 100644--- a/products/logs/backend/test/test_alert_evaluate.py+++ b/products/logs/backend/test/test_alert_evaluate.py@@ -12,8 +12,8 @@ from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.models.scoping import team_scope-from products.alerts.backend.facade.contracts import SourceBatchEvaluation, SourceKind-from products.alerts.backend.facade.platform_alerts import due_checks, record_outcomes+from products.alerts.backend.facade.contracts import AlertEventKind, GroupTransition, SourceBatchEvaluation, SourceKind+from products.alerts.backend.facade.platform_alerts import due_checks, record_outcomes, slot_offrom products.alerts.backend.facade.temporal import SOURCE_EVALUATION_TIMEOUTfrom products.alerts.backend.models import PlatformAlert, PlatformAlertConfigurationfrom products.logs.backend.alert_check_query import BatchedBucketedResult, BucketedCount@@ -50,8 +50,14 @@ class TestLogsAlertEvaluation(APIBaseTest):with team_scope(self.team.id):return PlatformAlertConfiguration.objects.create(**defaults)- def _run(self, *configurations: PlatformAlertConfiguration, query_error: Exception | None = None):- breaching = {str(c.id): [BucketedCount(timestamp=self.cutoff, count=500)] for c in configurations}+ def _run(+ self,+ *configurations: PlatformAlertConfiguration,+ query_error: Exception | None = None,+ now: datetime | None = None,+ ):+ now = now or self.cutoff+ breaching = {str(c.id): [BucketedCount(timestamp=now, count=500)] for c in configurations}with (patch(f"{_MODULE}.fetch_live_logs_checkpoint", return_value=None),patch(f"{_MODULE}.BatchedAlertCheckQuery") as query,@@ -62,11 +68,11 @@ class TestLogsAlertEvaluation(APIBaseTest):query.return_value.execute_rolling_checks.return_value = BatchedBucketedResult(per_alert=breaching, query_duration_ms=1)- slot = (configurations[0].next_check_at or self.cutoff).replace(second=0, microsecond=0).isoformat()- return evaluate_logs_batch(self.team.id, slot, self.cutoff), query+ slot = slot_of(configurations[0].next_check_at, now)+ return evaluate_logs_batch(self.team.id, slot, now), querydef _slot(self) -> str:- return (self.cutoff - timedelta(minutes=1)).isoformat()+ return slot_of(self.cutoff - timedelta(minutes=1), self.cutoff)def _record(self, evaluation: SourceBatchEvaluation) -> None:"""The write the platform's own activity runs after the evaluation returns.@@ -82,7 +88,9 @@ class TestLogsAlertEvaluation(APIBaseTest):evaluation, _ = self._run(configuration)self._record(evaluation)- assert [t.notification for preview in evaluation.previews for t in preview.transitions] == ["fire"]+ assert [t for preview in evaluation.previews for t in preview.transitions] == [+ GroupTransition(grouping_key="", kind=AlertEventKind.FIRING, value=500.0)+ ]with team_scope(self.team.id):alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")configuration.refresh_from_db()@@ -148,7 +156,7 @@ class TestLogsAlertEvaluation(APIBaseTest):per_alert={str(configuration.id): [BucketedCount(timestamp=self.cutoff, count=500)]},query_duration_ms=1,)- slot = next_check_at.replace(second=0, microsecond=0).isoformat()+ slot = slot_of(next_check_at, self.cutoff)evaluation = evaluate_logs_batch(self.team.id, slot, self.cutoff)return evaluation.outcomes[0].evaluation_key@@ -173,10 +181,17 @@ class TestLogsAlertEvaluation(APIBaseTest):# An incident wholly inside the window must still leave a trace, and must not move the cooldown.assert alert.state == PlatformAlert.State.FIRINGassert alert.last_notified_at is None+ assert alert.firing_started_at == self.cutoff# Parked at the end of the window would leave the alert unevaluated until noon.assert configuration.next_check_at is not Noneassert self.cutoff < configuration.next_check_at < datetime(2026, 9, 16, 11, tzinfo=UTC)+ # The first check after the window announces the fire the mute held. Without the held+ # firing reaching it, a FIRING alert does not fire again on its own and stays silent.+ unmuted, _ = self._run(configuration, now=datetime(2026, 9, 16, 12, 30, tzinfo=UTC))++ assert [t.kind for preview in unmuted.previews for t in preview.transitions] == [AlertEventKind.FIRING]+def test_a_broken_filter_config_stops_being_discovered(self) -> None:configuration = self._configuration(source_config={"filterGroup": {"type": "nonsense"}})@@ -269,17 +284,17 @@ class TestLogsAlertEvaluation(APIBaseTest):kwargs = query.call_args.kwargsassert kwargs["date_to"] - kwargs["date_from"] == timedelta(minutes=expected_lookback_minutes)- def test_the_evaluation_key_comes_from_the_tick_occasion_not_the_clock(self) -> None:+ def test_a_preview_and_its_recorded_outcome_name_the_same_evaluation(self) -> None:configuration = self._configuration(next_check_at=None)evaluation, _ = self._run(configuration)- # The preview key is the recorded key, so the slot travels with it. It becomes the- # delivery workflow id, and a window-only id lets two checks that clamped to the same- # window end collide and drops the later announcement.- assert [p.evaluation_key for p in evaluation.previews] == [- f"{configuration.id}:slot:{self.cutoff.isoformat()}|window:{self.cutoff.isoformat()}"- ]+ # A preview carries the recorded key unchanged, so a delivery can address the row the+ # check wrote. The slot is in the key because two checks of one alert can clamp to the+ # same window end, and a key without it makes them one evaluation to any reader.+ expected = f"slot:{self.cutoff.isoformat()}|window:{self.cutoff.isoformat()}"+ assert evaluation.outcomes[0].evaluation_key == expected+ assert [p.evaluation_key for p in evaluation.previews] == [expected]class TestEvaluationTimeoutLadder(SimpleTestCase):