: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): cut over insight alerts that use the investigation agent (#127926)
Jimmy Zhu02a98aa8be79
diff --git a/products/alerts/backend/platform_cutover.py b/products/alerts/backend/platform_cutover.pyindex f9ce15be191c..4179b18ea981 100644--- a/products/alerts/backend/platform_cutover.py+++ b/products/alerts/backend/platform_cutover.py@@ -12,15 +12,17 @@ from typing import Finalfrom uuid import UUIDfrom django.db import transaction+from django.db.models import Qfrom django.utils import timezonefrom posthog.dataclasses import frozenfrom posthog.schema_enums import AlertStatefrom posthog.tasks.alerts.utils import due_insight_alerts_q+from posthog.temporal.alerts.investigation import IN_FLIGHT_INVESTIGATION_HORIZONfrom products.alerts.backend.facade.destinations import choose_delivery_pathfrom products.alerts.backend.insight_alert_state_machine import apply_invalid_configuration, apply_platform_state-from products.alerts.backend.models.alert import AlertConfiguration+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatusfrom products.alerts.backend.platform_source_cycle import DELIVERY_EVENT_IDS, platform_upsert_offrom products.alerts_platform.backend.facade.api import give_back_ownership, take_ownership, upsert_configurationfrom products.alerts_platform.backend.facade.contracts import (@@ -71,8 +73,6 @@ class CutoverSkip(StrEnum):ENVIRONMENT = "environment"# The platform cannot copy it, such as an alert with no cadence.NOT_ON_PLATFORM = "not_on_platform"- # The investigation agent reads and writes the insight stack's checks, which the platform does not keep.- INVESTIGATION = "investigation"# The two stacks key a firing differently, so a firing moves only after it resolves.FIRING = "firing"# The insight scheduler owes this alert a check, which may already be running and could notify@@ -83,6 +83,9 @@ class CutoverSkip(StrEnum):# Its destinations need the HogFunction path, and nothing emits the insight events that path# sends, so the platform would deliver it natively and lose what its destinations add.NO_HOG_FUNCTION_PATH = "no_hog_function_path"+ # The insight stack's agent still runs for a recent firing, or its held notification is unsent.+ # Moved now, that notification could not go out, and the platform would start a second agent.+ INVESTIGATION_UNSETTLED = "investigation_unsettled"@frozen@@ -103,6 +106,24 @@ def _insight_check_owed(team_id: int, alert_id: UUID, at: datetime) -> bool:return AlertConfiguration.objects.filter(team_id=team_id, id=alert_id).filter(due_insight_alerts_q(at)).exists()+def _investigation_unsettled(alert: AlertConfiguration, at: datetime) -> bool:+ """Whether a recent check of the alert has an investigation in flight, or a finished one whose+ held notification neither went out nor was suppressed. Past the in-flight horizon the insight+ stack's safety net has sent it."""+ in_flight = Q(investigation_status__in=[InvestigationStatus.PENDING, InvestigationStatus.RUNNING])+ held = Q(+ investigation_status__in=[InvestigationStatus.DONE, InvestigationStatus.FAILED],+ state=AlertState.FIRING,+ notification_sent_at__isnull=True,+ notification_suppressed_by_agent=False,+ )+ return (+ AlertCheck.objects.filter(alert_configuration=alert, created_at__gte=at - IN_FLIGHT_INVESTIGATION_HORIZON)+ .filter(in_flight | held)+ .exists()+ )++def cut_over_team(team_id: int, *, now: datetime | None = None) -> tuple[AlertCutover, ...]:"""Hands every insight alert of one team to the platform, or says why one stays.@@ -144,13 +165,15 @@ def _cut_over_alert(team_id: int, alert_id: UUID, now: datetime | None) -> Cutovif in_an_environment(alert):return CutoverSkip.ENVIRONMENTif not can_move(alert):- return CutoverSkip.INVESTIGATION if alert.investigation_agent_enabled else CutoverSkip.NOT_ON_PLATFORM+ return CutoverSkip.NOT_ON_PLATFORMif not delivers_as_it_does_today(alert):return CutoverSkip.NO_HOG_FUNCTION_PATHif alert.state == AlertState.FIRING:return CutoverSkip.FIRINGif _insight_check_owed(team_id, alert.id, at):return CutoverSkip.CHECK_DUE+ if _investigation_unsettled(alert, at):+ return CutoverSkip.INVESTIGATION_UNSETTLEDif not hand_over(alert, at):return CutoverSkip.PLATFORM_FIRINGreturn None@@ -162,9 +185,9 @@ def in_an_environment(alert: AlertConfiguration) -> bool:def can_move(alert: AlertConfiguration) -> bool:- """Whether the platform can own the alert: one it evaluates, with a threshold or a detector, which- no investigation agent reads."""- return platform_upsert_of(alert) is not None and not alert.investigation_agent_enabled+ """Whether the platform can own the alert: one it evaluates, with a threshold or a detector, and+ with or without the investigation agent."""+ return platform_upsert_of(alert) is not Nonedef has_begun_cutover(team_id: int) -> bool:diff --git a/products/alerts/backend/platform_ownership.py b/products/alerts/backend/platform_ownership.pyindex 45970c2751f3..0c6a9067909e 100644--- a/products/alerts/backend/platform_ownership.py+++ b/products/alerts/backend/platform_ownership.py@@ -55,11 +55,11 @@ def on_updated(alert: AlertConfiguration, *, snooze_changed: bool, rescheduled:"""Writes an edit the insight API saved onto the platform's copy. `rescheduled` says the editmoved the alert's own due time, which the copy then follows.- Raises `PlatformCannotOwn` for an edit the platform cannot evaluate, such as one the investigation agent reads, and+ Raises `PlatformCannotOwn` for an edit the platform cannot evaluate, such as a frequency it does not run, and`InvalidPlatformAlertEdit` for one the platform's schema rejects."""if not can_move(alert):- raise PlatformCannotOwn("The alerts platform runs this alert, and it cannot run the investigation agent yet.")+ raise PlatformCannotOwn("The alerts platform runs this alert, and it can't run checks at this frequency.")upsert = platform_upsert_of(alert)assert upsert is not Noneupdate_owned_copy(diff --git a/products/alerts/backend/test/test_platform_cutover.py b/products/alerts/backend/test/test_platform_cutover.pyindex 6d52199e6496..2aea7c2ddf6c 100644--- a/products/alerts/backend/test/test_platform_cutover.py+++ b/products/alerts/backend/test/test_platform_cutover.py@@ -10,7 +10,7 @@ from posthog.models import Teamfrom posthog.models.scoping import team_scopefrom posthog.schema_enums import AlertCalculationInterval, AlertState-from products.alerts.backend.models.alert import AlertConfiguration+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatusfrom products.alerts.backend.platform_cutover import CutoverSkip, RollbackSkip, cut_over_team, roll_back_teamfrom products.alerts.backend.test.insight_alerts import create_insight_alertfrom products.alerts_platform.backend.facade import testing as platform_testing@@ -40,6 +40,11 @@ class TestInsightPlatformCutover(APIBaseTest):("statistical_detector", {"detector_config": {"type": "zscore"}}, "not_firing"),("ai_detector", {"detector_config": {"type": "llm"}}, "not_firing"),("real_time", {"calculation_interval": AlertCalculationInterval.REAL_TIME.value}, "not_firing"),+ (+ "investigated",+ {"detector_config": {"type": "zscore"}, "investigation_agent_enabled": True},+ "not_firing",+ ),])def test_an_alert_moves_with_its_state_and_schedule(@@ -67,7 +72,6 @@ class TestInsightPlatformCutover(APIBaseTest):("firing", {"state": AlertState.FIRING}, CutoverSkip.FIRING),("check_due", {"next_check_at": NOW}, CutoverSkip.CHECK_DUE),("never_scheduled", {"next_check_at": None}, CutoverSkip.CHECK_DUE),- ("investigated", {"investigation_agent_enabled": True}, CutoverSkip.INVESTIGATION),])def test_an_alert_that_cannot_move_now_stays_with_insight(@@ -81,6 +85,42 @@ class TestInsightPlatformCutover(APIBaseTest):alert.refresh_from_db()assert alert.owner == "source"+ @parameterized.expand(+ [+ (+ "agent_running",+ InvestigationStatus.RUNNING,+ None,+ timedelta(minutes=10),+ CutoverSkip.INVESTIGATION_UNSETTLED,+ ),+ (+ "held_notification",+ InvestigationStatus.DONE,+ None,+ timedelta(minutes=10),+ CutoverSkip.INVESTIGATION_UNSETTLED,+ ),+ ("notification_sent", InvestigationStatus.DONE, NOW, timedelta(minutes=10), None),+ ("past_the_horizon", InvestigationStatus.RUNNING, None, timedelta(hours=2), None),+ ]+ )+ def test_an_alert_moves_only_once_its_investigation_settles(+ self, _name: str, status: str, sent_at: datetime | None, age: timedelta, reason: CutoverSkip | None+ ) -> None:+ alert = self._alert(investigation_agent_enabled=True, detector_config={"type": "zscore"})+ check = AlertCheck.objects.create(+ alert_configuration=alert,+ state=AlertState.FIRING,+ investigation_status=status,+ notification_sent_at=sent_at,+ )+ AlertCheck.objects.filter(id=check.id).update(created_at=NOW - age)++ (result,) = cut_over_team(self.team.id, now=NOW)++ assert result.skipped == reason+def test_an_alert_in_a_child_environment_stays_with_insight(self) -> None:environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")alert = create_insight_alert(environment, next_check_at=NOW + timedelta(minutes=3))