: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
fix(alerts): hold every investigated fire until its verdict (#107529)
Carlos Marchal13dd4edf82e5
diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.pyindex 770b7d954b84..7f33f208f7aa 100644--- a/posthog/temporal/ai/anomaly_investigation/workflow.py+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py@@ -461,18 +461,18 @@ def _deliver_investigation_outcome() -> None:"""Decide what the user gets now that we have the verdict.- For a check whose notification was held back (the episode's first fire):+ For a check whose notification was held back (every investigated check of a gated alert):- true_positive → notify (enriched body with verdict + summary + notebook link)- false_positive → suppress, mark the check so the UI can surface why- inconclusive → fall back to the alert's configured policy- unknown / null verdict → notify (safest default)- A later investigation of the same episode is not gated, so its notification already- went out. It gets a follow-up only when the verdict changed, because the change is- the news; an unchanged verdict would repeat what the user already read. A change to- a false positive is a correction of a message the user already has, so it is sent- rather than suppressed.+ A check that was not held back (the alert did not gate when the check fired) already+ notified. It gets a follow-up only when the verdict changed,+ because the change is the news; an unchanged verdict would repeat what the user already+ read. A change to a false positive is a correction of a message the user already has,+ so it is sent rather than suppressed.Idempotent: if another codepath (retry, safety-net task) already dispatched,the first delivery is a no-op, and the follow-up is written once per check.diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex fd2ec5ddc074..e9bdf094cf6b 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -61,7 +61,11 @@ from posthog.temporal.alerts.admission import (release_evaluation_slot,release_evaluation_slots,)-from posthog.temporal.alerts.investigation import claim_investigation_slot, decide_investigation+from posthog.temporal.alerts.investigation import (+ carried_verdict_suppresses,+ claim_investigation_slot,+ decide_investigation,+)from posthog.temporal.alerts.metrics import record_ai_detector_check_outcome, record_due_insight_alert_metricsfrom posthog.temporal.alerts.retry_policy import ALERT_PREPARE_RETRY_POLICY, SlotLease, alert_timeoutsfrom posthog.temporal.alerts.types import (@@ -768,9 +772,11 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertReinvestigation = decide_investigation(alert, alert_check)if investigation.should_investigate and claim_investigation_slot(alert, alert_check):should_start_investigation = True- should_gate_notification = investigation.is_first_of_episode and bool(- alert.investigation_gates_notifications- )+ should_gate_notification = should_notify and bool(alert.investigation_gates_notifications)+ elif should_notify and carried_verdict_suppresses(alert, investigation):+ # Marked so the safety net does not force-send it and the UI shows why it was held.+ AlertCheck.objects.filter(id=alert_check.id).update(notification_suppressed_by_agent=True)+ should_notify = False# Claim the cooldown slot inside the transaction so a flapping or# concurrently-retried alert can't pile up investigations.diff --git a/posthog/temporal/alerts/investigation.py b/posthog/temporal/alerts/investigation.pyindex a9a4e0cf30b6..e6831503861c 100644--- a/posthog/temporal/alerts/investigation.py+++ b/posthog/temporal/alerts/investigation.py@@ -16,6 +16,7 @@ from posthog.schema import AlertCalculationInterval, AlertStatefrom posthog.dataclasses import frozenfrom posthog.tasks.alerts.investigation_notifications import INVESTIGATION_RUNNING_GRACE_MINUTES+from posthog.tasks.alerts.utils import _should_suppress_notificationfrom products.alerts.backend.investigation_episode import episode_investigationsfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus@@ -54,7 +55,9 @@ _CALCULATION_INTERVAL_DURATIONS: dict[str, timedelta] = {@frozenclass InvestigationDecision:should_investigate: bool = False- is_first_of_episode: bool = False+ # The last verdict an earlier check of this firing episode reached. A check that runs no+ # investigation of its own is held back by it.+ previous_verdict: str | None = Nonedef investigation_cooldown(alert: AlertConfiguration) -> timedelta:@@ -64,13 +67,12 @@ def investigation_cooldown(alert: AlertConfiguration) -> timedelta:def decide_investigation(alert: AlertConfiguration, alert_check: AlertCheck) -> InvestigationDecision:- """Whether this firing check gets an investigation, and whether it opened the episode.+ """Whether this firing check gets an investigation, and the episode's last verdict so far.- Only the episode's first fire may gate the notification, because it is the fire the- user has not heard about yet. A later check runs while its notification goes out on the- normal path, because holding a reminder of an incident the user already knows about- costs more than the verdict is worth. A skipped investigation on an earlier check does- not move the gate forward: that check notified all the same.+ Every investigated check of a gated alert holds its notification until its own verdict,+ not only the episode's first fire. Each check of a daily or hourly alert flags a new+ point, so a false positive on a later check is a new false alarm, not a reminder of an+ incident the user already knows about.Cooldown is enforced by `claim_investigation_slot`, which does the read-then-writeinside the caller's transaction.@@ -84,8 +86,19 @@ def decide_investigation(alert: AlertConfiguration, alert_check: AlertCheck) ->episode = episode_investigations(alert, alert_check)if episode.started >= MAX_INVESTIGATIONS_PER_EPISODE:- return InvestigationDecision()- return InvestigationDecision(should_investigate=True, is_first_of_episode=episode.is_first_fire)+ return InvestigationDecision(previous_verdict=episode.previous_verdict)+ return InvestigationDecision(should_investigate=True, previous_verdict=episode.previous_verdict)+++def carried_verdict_suppresses(alert: AlertConfiguration, decision: InvestigationDecision) -> bool:+ """Whether a firing check that runs no investigation is held back by the episode's last verdict.++ This covers a check past the episode budget or refused by the cooldown. Without it, the+ budget running out would turn every later false alarm of a long episode into a post.+ """+ return bool(alert.investigation_gates_notifications) and _should_suppress_notification(+ decision.previous_verdict, alert.investigation_inconclusive_action+ )def claim_investigation_slot(alert: AlertConfiguration, alert_check: AlertCheck) -> bool:diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex 4e2206f478dc..bcc62e91aca0 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -64,6 +64,7 @@ from posthog.temporal.alerts.admission import (hold_evaluation_slot,inflight_alert_ids,)+from posthog.temporal.alerts.investigation import MAX_INVESTIGATIONS_PER_EPISODEfrom posthog.temporal.alerts.retry_policy import SlotLease, alert_timeoutsfrom posthog.temporal.alerts.types import (EvaluateAlertActivityInputs,@@ -83,7 +84,7 @@ from products.alerts.backend.facade.api import (LLMDetectorUnavailableError,)from products.alerts.backend.facade.contracts import AlertDelivery-from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus, Thresholdfrom products.product_analytics.backend.facade.models import Insight@@ -1018,6 +1019,58 @@ class TestEvaluateAlert:assert check.state == AlertState.FIRINGassert check.targets_notified == {}+ @pytest.mark.parametrize(+ "investigated,previous_verdict,expect_investigation,expect_notify,expect_held",+ [+ (1, "false_positive", True, True, False),+ (MAX_INVESTIGATIONS_PER_EPISODE, "false_positive", False, False, True),+ (MAX_INVESTIGATIONS_PER_EPISODE, "true_positive", False, True, False),+ ],+ )+ async def test_gated_alert_holds_each_fire_on_a_verdict(+ self,+ ateam,+ investigated: int,+ previous_verdict: str,+ expect_investigation: bool,+ expect_notify: bool,+ expect_held: bool,+ ) -> None:+ alert = await _create_alert(ateam, state=AlertState.FIRING, detector_config={"type": "zscore"})++ @sync_to_async+ def _seed_episode() -> None:+ AlertConfiguration.objects.filter(id=alert.id).update(+ investigation_agent_enabled=True, investigation_gates_notifications=True+ )+ episode_start = datetime.now(UTC) - timedelta(days=5)+ AlertCheck.objects.create(alert_configuration=alert, state=AlertState.NOT_FIRING)+ AlertCheck.objects.filter(alert_configuration=alert).update(created_at=episode_start)+ for index in range(investigated):+ earlier = AlertCheck.objects.create(+ alert_configuration=alert,+ state=AlertState.FIRING,+ investigation_status=InvestigationStatus.DONE,+ investigation_verdict=previous_verdict,+ )+ AlertCheck.objects.filter(id=earlier.id).update(created_at=episode_start + timedelta(days=index + 1))++ await _seed_episode()++ with patch(+ "posthog.temporal.alerts.activities.check_alert_for_insight",+ return_value=AlertEvaluationResult(value=100.0, breaches=["value above threshold"]),+ ):+ result = await ActivityEnvironment().run(+ evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id))+ )++ assert result.should_start_investigation is expect_investigation+ assert result.should_gate_notification is expect_investigation+ assert result.should_notify is expect_notify+ check = await sync_to_async(AlertCheck.objects.get)(pk=result.alert_check_id)+ assert check.notification_suppressed_by_agent is expect_held+async def test_evaluate_errored_when_permanent_exception(self, alert) -> None:with patch("posthog.temporal.alerts.activities.check_alert_for_insight",diff --git a/posthog/temporal/tests/test_alerts_investigation.py b/posthog/temporal/tests/test_alerts_investigation.pyindex 1dc4a30b009e..c68c7af59658 100644--- a/posthog/temporal/tests/test_alerts_investigation.py+++ b/posthog/temporal/tests/test_alerts_investigation.py@@ -17,6 +17,8 @@ from posthog.schema import AlertCalculationInterval, AlertStatefrom posthog.temporal.alerts.investigation import (IN_FLIGHT_INVESTIGATION_HORIZON,MAX_INVESTIGATIONS_PER_EPISODE,+ InvestigationDecision,+ carried_verdict_suppresses,claim_investigation_slot,decide_investigation,investigation_cooldown,@@ -80,12 +82,16 @@ class TestDecideInvestigation(InvestigationTestCase):decision = decide_investigation(self.alert, check)assert decision.should_investigate- assert decision.is_first_of_episode is (already_investigated == 0)+ assert decision.previous_verdict == (None if already_investigated == 0 else "true_positive")def test_stops_once_the_budget_is_spent(self) -> None:check = self._firing_episode(investigated=MAX_INVESTIGATIONS_PER_EPISODE)- assert not decide_investigation(self.alert, check).should_investigate+ decision = decide_investigation(self.alert, check)++ assert not decision.should_investigate+ # The episode's last verdict still reaches the caller, so it can hold the notification.+ assert decision.previous_verdict == "true_positive"def test_investigates_a_check_whose_predecessor_was_dismissed(self) -> None:# The suppressed-false-positive case needs no rule of its own: the next check is@@ -101,7 +107,7 @@ class TestDecideInvestigation(InvestigationTestCase):decision = decide_investigation(self.alert, check)assert decision.should_investigate- assert not decision.is_first_of_episode+ assert decision.previous_verdict == "false_positive"def test_budget_resets_after_the_alert_stops_firing(self) -> None:self._firing_episode(investigated=MAX_INVESTIGATIONS_PER_EPISODE)@@ -111,7 +117,7 @@ class TestDecideInvestigation(InvestigationTestCase):decision = decide_investigation(self.alert, check)assert decision.should_investigate- assert decision.is_first_of_episode+ assert decision.previous_verdict is Nonedef test_a_skipped_check_does_not_spend_budget(self) -> None:# SKIPPED means the cooldown refused the slot, so no agent ever ran.@@ -125,21 +131,6 @@ class TestDecideInvestigation(InvestigationTestCase):assert decide_investigation(self.alert, check).should_investigate- def test_does_not_gate_a_reminder_after_a_skipped_first_fire(self) -> None:- # The cooldown refused the episode's opening fire, so its notification already went- # out. The next check must not hold a reminder of an incident the user knows about.- self._make_check(at=_EPISODE_START, state=AlertState.NOT_FIRING)- self._make_check(- at=_EPISODE_START + timedelta(hours=1),- investigation_status=InvestigationStatus.SKIPPED,- )- check = self._make_check(at=_EPISODE_START + timedelta(hours=2))-- decision = decide_investigation(self.alert, check)-- assert decision.should_investigate- assert not decision.is_first_of_episode-@parameterized.expand([("not_firing", AlertState.NOT_FIRING), ("errored", AlertState.ERRORED)])def test_does_not_trigger_on_a_check_that_is_not_firing(self, _name: str, state: str) -> None:check = self._make_check(at=_EPISODE_START + timedelta(hours=1), state=state)@@ -161,6 +152,28 @@ class TestDecideInvestigation(InvestigationTestCase):assert not decide_investigation(self.alert, check).should_investigate+class TestCarriedVerdictSuppresses(InvestigationTestCase):+ @parameterized.expand(+ [+ ("false_positive", "false_positive", True, "notify", True),+ ("true_positive", "true_positive", True, "notify", False),+ ("no_verdict_yet", None, True, "notify", False),+ ("inconclusive_notifies", "inconclusive", True, "notify", False),+ ("inconclusive_suppressed", "inconclusive", True, "suppress", True),+ ("alert_does_not_gate", "false_positive", False, "notify", False),+ ]+ )+ def test_follows_the_episode_last_verdict(+ self, _name: str, previous_verdict: str | None, gates: bool, inconclusive_action: str, expected: bool+ ) -> None:+ self.alert.investigation_gates_notifications = gates+ self.alert.investigation_inconclusive_action = inconclusive_action++ decision = InvestigationDecision(previous_verdict=previous_verdict)++ assert carried_verdict_suppresses(self.alert, decision) is expected++class TestEpisodeInvestigations(InvestigationTestCase):def test_reports_the_previous_verdict_and_the_episode_key(self) -> None:self._make_check(at=_EPISODE_START, state=AlertState.NOT_FIRING)@@ -180,7 +193,6 @@ class TestEpisodeInvestigations(InvestigationTestCase):assert episode.previous_verdict == "false_positive"# Every investigation of one incident emits under the same signal source id.assert episode.first_check_id == str(first.id)- assert episode.is_first_fire is Falsedef test_a_verdict_from_the_previous_episode_is_not_carried_over(self) -> None:self._make_check(@@ -195,7 +207,6 @@ class TestEpisodeInvestigations(InvestigationTestCase):assert episode.previous_verdict is Noneassert episode.first_check_id == str(check.id)- assert episode.is_first_fireclass TestInvestigationCooldown(InvestigationTestCase):diff --git a/products/alerts/backend/investigation_episode.py b/products/alerts/backend/investigation_episode.pyindex cf19c657d6e1..75208ef083ca 100644--- a/products/alerts/backend/investigation_episode.py+++ b/products/alerts/backend/investigation_episode.py@@ -30,10 +30,6 @@ class EpisodeInvestigations:started: intfirst_check_id: strprevious_verdict: str | None- # True when no earlier check of this episode fired, so this is the fire the user has not- # been told about yet. The count of started investigations cannot answer that: a check- # whose investigation the cooldown refused still sent its notification.- is_first_fire: booldef episode_investigations(alert: AlertConfiguration, alert_check: AlertCheck) -> EpisodeInvestigations:@@ -64,5 +60,4 @@ def episode_investigations(alert: AlertConfiguration, alert_check: AlertCheck) -started=earlier.filter(investigation_status__in=_STARTED_INVESTIGATION_STATUSES).count(),first_check_id=str(first_check_id or alert_check.id),previous_verdict=previous_verdict,- is_first_fire=first_check_id is None,)