: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): wire investigation agent — workflow, trigger, gating (#55185)
Andrew Maguireb7fa471d690e
diff --git a/posthog/tasks/alerts/investigation_notifications.py b/posthog/tasks/alerts/investigation_notifications.pynew file mode 100644index 000000000000..f902f78fe455--- /dev/null+++ b/posthog/tasks/alerts/investigation_notifications.py@@ -0,0 +1,137 @@+"""Safety-net dispatcher for investigation-gated alert notifications.++When an alert has `investigation_gates_notifications=True`, the synchronous+notification in `notify_alert` is skipped and the investigation workflow+becomes responsible for firing it. That's great when the workflow completes —+but if Temporal has a hiccup, the workflow times out, or any other path leaves+an AlertCheck with no `notification_sent_at` and no `notification_suppressed_by_agent`,+the user could silently miss a real fire.++`run_investigation_notification_safety_net` is invoked on a Temporal schedule+(see `posthog/temporal/alerts/schedule.py`), looks for gated checks past a grace+period, and force-dispatches the notification with whatever context we have on+hand. Terminal investigation statuses (DONE/FAILED) get picked up after+`INVESTIGATION_NOTIFY_GRACE_MINUTES`; non-terminal statuses wait the longer+`INVESTIGATION_RUNNING_GRACE_MINUTES` so we never preempt a healthy long run.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++from django.db import transaction+from django.db.models import Q+from django.utils import timezone++import structlog++from posthog.schema import AlertState++from posthog.models.alert import AlertCheck, InvestigationStatus+from posthog.tasks.alerts.utils import dispatch_alert_notification, record_alert_delivery++logger = structlog.get_logger(__name__)+++# Fast pickup for investigations that already reached a terminal state — the workflow+# is no longer going to dispatch, so we shouldn't make the user wait.+INVESTIGATION_NOTIFY_GRACE_MINUTES = 5++# Fallback for non-terminal investigations (RUNNING / PENDING / SKIPPED / null). Must+# exceed the activity's worst case — `ANOMALY_INVESTIGATION_ACTIVITY_START_TO_CLOSE`+# (20 min) × `ANOMALY_INVESTIGATION_ACTIVITY_MAX_ATTEMPTS` (2) — so a healthy long+# investigation isn't preempted by a duplicate force-dispatch.+INVESTIGATION_RUNNING_GRACE_MINUTES = 45+++def run_investigation_notification_safety_net() -> int:+ """Dispatch notifications for gated AlertChecks whose investigation stalled.++ Returns the number of checks that were force-notified (for metrics / tests).+ """+ now = datetime.now(UTC)+ terminal_cutoff = now - timedelta(minutes=INVESTIGATION_NOTIFY_GRACE_MINUTES)+ running_cutoff = now - timedelta(minutes=INVESTIGATION_RUNNING_GRACE_MINUTES)+ # Scope the sweep to alerts that opted into the investigation agent rather+ # than the narrower `investigation_gates_notifications` flag. The latter is+ # a sub-toggle a user might flip off mid-investigation, which would hide a+ # legitimately-held check from this safety net; `investigation_agent_enabled`+ # is a stickier configuration knob and picks up exactly the checks whose+ # dispatch could have been the workflow's responsibility.+ candidates = (+ AlertCheck.objects.select_related("alert_configuration")+ .filter(+ state=AlertState.FIRING,+ notification_sent_at__isnull=True,+ notification_suppressed_by_agent=False,+ # Pre-PR-3 `notify_alert` populated `targets_notified` without setting+ # `notification_sent_at`. New code writes both atomically, so the combination+ # (targets_notified populated, notification_sent_at NULL) only occurs in+ # legacy data delivered before this safety net existed; skip it.+ targets_notified={},+ alert_configuration__investigation_agent_enabled=True,+ )+ .filter(+ # Terminal investigation states (DONE / FAILED): the workflow is not coming+ # back, so a 5-min grace gets stuck dispatches through quickly. Non-terminal+ # states (RUNNING / PENDING / SKIPPED / null): wait past the activity's+ # full retry budget so we don't race a healthy long-running investigation.+ Q(+ investigation_status__in=[InvestigationStatus.DONE, InvestigationStatus.FAILED],+ created_at__lte=terminal_cutoff,+ )+ | Q(created_at__lte=running_cutoff)+ )+ )++ notified = 0+ for check in candidates.iterator():+ alert = check.alert_configuration+ if alert is None or not alert.enabled:+ continue++ try:+ with transaction.atomic():+ locked = AlertCheck.objects.select_for_update().get(id=check.id)+ if locked.notification_sent_at is not None or locked.notification_suppressed_by_agent:+ continue+ breaches = _fallback_breach_descriptions(locked)+ targets = dispatch_alert_notification(alert, locked, breaches)+ if targets is not None:+ record_alert_delivery(alert, locked, targets)+ # Set notification_sent_at in lock-step with record_alert_delivery so+ # gating/idempotency reads that still use this marker stay consistent.+ locked.notification_sent_at = timezone.now()+ locked.save(update_fields=["notification_sent_at"])+ except Exception:+ logger.exception(+ "alert.investigation_safety_net_failed",+ alert_id=str(alert.id),+ alert_check_id=str(check.id),+ )+ continue++ logger.warning(+ "alert.investigation_safety_net_dispatched",+ alert_id=str(alert.id),+ alert_check_id=str(check.id),+ investigation_status=check.investigation_status,+ )+ notified += 1++ return notified+++def _fallback_breach_descriptions(alert_check: AlertCheck) -> list[str]:+ """Minimal breach description for a safety-net dispatch (no verdict yet)."""+ triggered_dates = alert_check.triggered_dates or []+ if triggered_dates:+ if len(triggered_dates) == 1:+ head = f"Anomaly detected on {triggered_dates[0]}."+ else:+ head = f"Anomaly detected from {triggered_dates[0]} to {triggered_dates[-1]}."+ elif alert_check.calculated_value is not None:+ head = f"Calculated value at fire: {alert_check.calculated_value}."+ else:+ head = "Anomaly detected."+ return [head, "(Investigation agent did not complete before the notification grace period expired.)"]diff --git a/posthog/tasks/alerts/test/test_investigation_notifications.py b/posthog/tasks/alerts/test/test_investigation_notifications.pynew file mode 100644index 000000000000..25255c575998--- /dev/null+++ b/posthog/tasks/alerts/test/test_investigation_notifications.py@@ -0,0 +1,206 @@+from datetime import UTC, datetime, timedelta++from freezegun import freeze_time+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.schema import AlertState++from posthog.models import AlertConfiguration, Insight+from posthog.models.alert import AlertCheck, InvestigationStatus+from posthog.tasks.alerts.investigation_notifications import (+ INVESTIGATION_NOTIFY_GRACE_MINUTES,+ INVESTIGATION_RUNNING_GRACE_MINUTES,+ run_investigation_notification_safety_net,+)++NOW = datetime(2026, 5, 4, 12, 0, 0, tzinfo=UTC)+++@freeze_time(NOW)+class TestInvestigationNotificationSafetyNet(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.insight = Insight.objects.create(team=self.team, name="test insight")+ self.alert = AlertConfiguration.objects.create(+ team=self.team,+ insight=self.insight,+ name="anomaly alert",+ detector_config={"type": "zscore", "threshold": 0.95, "window": 30},+ investigation_agent_enabled=True,+ investigation_gates_notifications=True,+ state=AlertState.FIRING,+ enabled=True,+ created_by=self.user,+ )++ def _make_check(+ self,+ *,+ age_minutes: int,+ investigation_status: str | None = None,+ notification_sent_at: datetime | None = None,+ notification_suppressed_by_agent: bool = False,+ targets_notified: dict | None = None,+ state: str = AlertState.FIRING,+ ) -> AlertCheck:+ check = AlertCheck.objects.create(+ alert_configuration=self.alert,+ state=state,+ calculated_value=42.0,+ investigation_status=investigation_status,+ notification_sent_at=notification_sent_at,+ notification_suppressed_by_agent=notification_suppressed_by_agent,+ targets_notified=targets_notified or {},+ )+ # `created_at` is auto_now_add — bypass with an UPDATE so the parametrized+ # ages drive the safety-net's cutoff predicate.+ AlertCheck.objects.filter(id=check.id).update(created_at=NOW - timedelta(minutes=age_minutes))+ check.refresh_from_db()+ return check++ @parameterized.expand(+ [+ # name, age_minutes, investigation_status, expected_dispatched+ # Terminal states (DONE/FAILED) — picked up after 5 min.+ (+ "done_within_terminal_grace_skipped",+ INVESTIGATION_NOTIFY_GRACE_MINUTES - 1,+ InvestigationStatus.DONE,+ False,+ ),+ (+ "done_past_terminal_grace_dispatched",+ INVESTIGATION_NOTIFY_GRACE_MINUTES + 1,+ InvestigationStatus.DONE,+ True,+ ),+ (+ "failed_past_terminal_grace_dispatched",+ INVESTIGATION_NOTIFY_GRACE_MINUTES + 1,+ InvestigationStatus.FAILED,+ True,+ ),+ # Non-terminal states — must wait the longer running grace so we don't+ # race a healthy long-running investigation.+ (+ "running_within_running_grace_skipped",+ INVESTIGATION_RUNNING_GRACE_MINUTES - 1,+ InvestigationStatus.RUNNING,+ False,+ ),+ (+ "running_past_running_grace_dispatched",+ INVESTIGATION_RUNNING_GRACE_MINUTES + 1,+ InvestigationStatus.RUNNING,+ True,+ ),+ (+ "pending_within_running_grace_skipped",+ INVESTIGATION_RUNNING_GRACE_MINUTES - 1,+ InvestigationStatus.PENDING,+ False,+ ),+ (+ "pending_past_running_grace_dispatched",+ INVESTIGATION_RUNNING_GRACE_MINUTES + 1,+ InvestigationStatus.PENDING,+ True,+ ),+ (+ "skipped_status_past_running_grace_dispatched",+ INVESTIGATION_RUNNING_GRACE_MINUTES + 1,+ InvestigationStatus.SKIPPED,+ True,+ ),+ # Investigation never started (status null) — treated as non-terminal.+ ("null_status_within_running_grace_skipped", INVESTIGATION_RUNNING_GRACE_MINUTES - 1, None, False),+ ("null_status_past_running_grace_dispatched", INVESTIGATION_RUNNING_GRACE_MINUTES + 1, None, True),+ ]+ )+ @patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")+ @patch("posthog.tasks.alerts.investigation_notifications.record_alert_delivery")+ def test_grace_period_predicate(+ self,+ _name: str,+ age_minutes: int,+ investigation_status: str | None,+ expected_dispatched: bool,+ mock_record: object,+ mock_dispatch: object,+ ) -> None:+ mock_dispatch.return_value = ["[email protected]"] # type: ignore[attr-defined]++ check = self._make_check(age_minutes=age_minutes, investigation_status=investigation_status)+ notified = run_investigation_notification_safety_net()++ check.refresh_from_db()+ if expected_dispatched:+ assert notified == 1+ assert check.notification_sent_at is not None+ mock_dispatch.assert_called_once() # type: ignore[attr-defined]+ else:+ assert notified == 0+ assert check.notification_sent_at is None+ mock_dispatch.assert_not_called() # type: ignore[attr-defined]++ @patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")+ def test_skips_legacy_delivered_check(self, mock_dispatch: object) -> None:+ # Pre-PR-3 `notify_alert` populated targets_notified without setting+ # notification_sent_at. The safety net must not double-dispatch these.+ self._make_check(+ age_minutes=INVESTIGATION_RUNNING_GRACE_MINUTES + 60,+ investigation_status=None,+ targets_notified={"users": ["[email protected]"]},+ )+ notified = run_investigation_notification_safety_net()+ assert notified == 0+ mock_dispatch.assert_not_called() # type: ignore[attr-defined]++ @patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")+ def test_skips_already_suppressed_check(self, mock_dispatch: object) -> None:+ self._make_check(+ age_minutes=INVESTIGATION_NOTIFY_GRACE_MINUTES + 60,+ investigation_status=InvestigationStatus.DONE,+ notification_suppressed_by_agent=True,+ )+ notified = run_investigation_notification_safety_net()+ assert notified == 0+ mock_dispatch.assert_not_called() # type: ignore[attr-defined]++ @patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")+ def test_skips_already_notified_check(self, mock_dispatch: object) -> None:+ self._make_check(+ age_minutes=INVESTIGATION_NOTIFY_GRACE_MINUTES + 60,+ investigation_status=InvestigationStatus.DONE,+ notification_sent_at=NOW - timedelta(minutes=10),+ )+ notified = run_investigation_notification_safety_net()+ assert notified == 0+ mock_dispatch.assert_not_called() # type: ignore[attr-defined]++ @patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")+ def test_skips_disabled_alert(self, mock_dispatch: object) -> None:+ self.alert.enabled = False+ self.alert.save(update_fields=["enabled"])+ self._make_check(+ age_minutes=INVESTIGATION_NOTIFY_GRACE_MINUTES + 60,+ investigation_status=InvestigationStatus.DONE,+ )+ notified = run_investigation_notification_safety_net()+ assert notified == 0+ mock_dispatch.assert_not_called() # type: ignore[attr-defined]++ @patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")+ def test_skips_non_agent_alert(self, mock_dispatch: object) -> None:+ self.alert.investigation_agent_enabled = False+ self.alert.save(update_fields=["investigation_agent_enabled"])+ self._make_check(+ age_minutes=INVESTIGATION_NOTIFY_GRACE_MINUTES + 60,+ investigation_status=InvestigationStatus.DONE,+ )+ notified = run_investigation_notification_safety_net()+ assert notified == 0+ mock_dispatch.assert_not_called() # type: ignore[attr-defined]diff --git a/posthog/temporal/ai/__init__.py b/posthog/temporal/ai/__init__.pyindex 2592e73bd607..916bccd3fc64 100644--- a/posthog/temporal/ai/__init__.py+++ b/posthog/temporal/ai/__init__.py@@ -1,3 +1,4 @@+from posthog.temporal.ai.anomaly_investigation import AnomalyInvestigationWorkflow, investigate_anomaly_activityfrom posthog.temporal.ai.chat_agent import (AssistantConversationRunnerWorkflow,ChatAgentWorkflow,@@ -52,6 +53,7 @@ AI_WORKFLOWS = [SlackConversationRunnerWorkflow,PostHogCodeSlackMentionWorkflow,PostHogCodeSlackTerminateTaskWorkflow,+ AnomalyInvestigationWorkflow,]AI_ACTIVITIES = [@@ -76,6 +78,7 @@ AI_ACTIVITIES = [post_posthog_code_picker_timeout_activity,post_posthog_code_internal_error_activity,process_posthog_code_terminate_task_activity,+ investigate_anomaly_activity,]__all__ = [diff --git a/posthog/temporal/ai/anomaly_investigation/__init__.py b/posthog/temporal/ai/anomaly_investigation/__init__.pyindex 2c8a9f3cf36b..e5a48eca33c3 100644--- a/posthog/temporal/ai/anomaly_investigation/__init__.py+++ b/posthog/temporal/ai/anomaly_investigation/__init__.py@@ -1,7 +1,11 @@-"""Anomaly investigation agent package.+from posthog.temporal.ai.anomaly_investigation.workflow import (+ AnomalyInvestigationWorkflow,+ AnomalyInvestigationWorkflowInputs,+ investigate_anomaly_activity,+)-Pure-python modules: tool toolkit, prompt builder, pydantic report schema,-chart renderer, notebook builder, and agent runner. Wiring into the Temporal-workflow lands in a follow-up PR — this package is importable and unit-tested-in isolation here so the review can focus on the agent logic itself.-"""+__all__ = [+ "AnomalyInvestigationWorkflow",+ "AnomalyInvestigationWorkflowInputs",+ "investigate_anomaly_activity",+]diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.pynew file mode 100644index 000000000000..3290e903cced--- /dev/null+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py@@ -0,0 +1,359 @@+"""Temporal workflow that kicks off the anomaly investigation agent and persists+its findings as a Notebook linked to the AlertCheck.++Triggered from posthog/tasks/alerts/checks.py when an alert transitions to FIRING.+"""++from __future__ import annotations++import json+import asyncio+from dataclasses import dataclass+from datetime import timedelta+from typing import Optional+from uuid import UUID++from django.db import transaction+from django.utils import timezone++import structlog+from asgiref.sync import sync_to_async+from temporalio import activity, workflow+from temporalio.common import RetryPolicy++from posthog.models import Team, User+from posthog.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus+from posthog.tasks.alerts.utils import dispatch_alert_notification, record_alert_delivery+from posthog.temporal.ai.anomaly_investigation.charts import png_to_b64, render_series_chart+from posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebook+from posthog.temporal.ai.anomaly_investigation.prompts import build_anomaly_context+from posthog.temporal.ai.anomaly_investigation.runner import run_investigation+from posthog.temporal.ai.anomaly_investigation.tools import _run_detector_simulation+from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.heartbeat import Heartbeater++from products.notebooks.backend.models import Notebook++logger = structlog.get_logger(__name__)+++ANOMALY_INVESTIGATION_ACTIVITY_START_TO_CLOSE = 20 * 60 # 20 minutes+ANOMALY_INVESTIGATION_ACTIVITY_HEARTBEAT_TIMEOUT = 5 * 60 # 5 minutes+ANOMALY_INVESTIGATION_ACTIVITY_MAX_ATTEMPTS = 2++MAX_SUMMARY_CHARS = 500+++@dataclass+class AnomalyInvestigationWorkflowInputs:+ team_id: int+ alert_id: UUID+ alert_check_id: UUID+ user_id: Optional[int] = None+ trace_id: Optional[str] = None++[email protected](name="anomaly-investigation")+class AnomalyInvestigationWorkflow(PostHogWorkflow):+ """Single-activity workflow — the heavy lifting happens inside the activity."""++ @staticmethod+ def parse_inputs(inputs: list[str]) -> AnomalyInvestigationWorkflowInputs:+ loaded = json.loads(inputs[0])+ return AnomalyInvestigationWorkflowInputs(**loaded)++ @workflow.run+ async def run(self, inputs: AnomalyInvestigationWorkflowInputs) -> None:+ await workflow.execute_activity(+ investigate_anomaly_activity,+ inputs,+ start_to_close_timeout=timedelta(seconds=ANOMALY_INVESTIGATION_ACTIVITY_START_TO_CLOSE),+ heartbeat_timeout=timedelta(seconds=ANOMALY_INVESTIGATION_ACTIVITY_HEARTBEAT_TIMEOUT),+ retry_policy=RetryPolicy(+ initial_interval=timedelta(seconds=2),+ maximum_interval=timedelta(minutes=1),+ maximum_attempts=ANOMALY_INVESTIGATION_ACTIVITY_MAX_ATTEMPTS,+ ),+ )+++async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInputs) -> None:+ team, alert, alert_check = await asyncio.gather(+ Team.objects.aget(id=inputs.team_id),+ AlertConfiguration.objects.select_related("insight").aget(id=inputs.alert_id),+ AlertCheck.objects.aget(id=inputs.alert_check_id),+ )++ user: User | None = None+ if inputs.user_id is not None:+ try:+ user = await User.objects.aget(id=inputs.user_id)+ except User.DoesNotExist:+ user = None+ if user is None:+ user = await _pick_investigation_user(alert)++ if user is None:+ await _mark_failed(alert_check, "No user available to run the investigation agent.")+ return++ await _update_status(alert_check, InvestigationStatus.RUNNING)++ insight = alert.insight+ metric_description = insight.name or f"Insight {insight.short_id}"+ detector_type = (alert.detector_config or {}).get("type") or "threshold"++ anomaly_context_text = build_anomaly_context(+ alert_name=alert.name or "Unnamed alert",+ metric_description=metric_description,+ detector_type=detector_type,+ triggered_dates=list(alert_check.triggered_dates or []),+ triggered_metadata=alert_check.triggered_metadata,+ calculated_value=alert_check.calculated_value,+ interval=alert_check.interval,+ )++ # Render a chart of the metric with the detector's anomaly points marked and+ # attach it to the HumanMessage so the multimodal model can reason visually+ # before spending any tool-call budget.+ anomaly_context = await sync_to_async(_build_multimodal_context, thread_sensitive=False)(+ alert=alert,+ context_text=anomaly_context_text,+ )++ try:+ async with Heartbeater():+ result = await run_investigation(+ team=team,+ user=user,+ anomaly_context=anomaly_context,+ alert=alert,+ heartbeat=activity.heartbeat,+ )+ except Exception as err:+ logger.exception("anomaly_investigation.agent_failed", alert_id=str(alert.id))+ await _mark_failed(alert_check, f"Agent run failed: {err}")+ raise++ notebook_content = build_investigation_notebook(+ NotebookRenderContext(+ alert=alert,+ alert_check=alert_check,+ insight=insight,+ report=result.report,+ )+ )++ notebook = await sync_to_async(Notebook.objects.create, thread_sensitive=False)(+ team=team,+ title=f"Investigation — {alert.name or 'anomaly alert'}",+ content=notebook_content,+ text_content=result.report.summary,+ created_by=user,+ last_modified_by=user,+ visibility=Notebook.Visibility.DEFAULT,+ )++ summary_for_list = _truncate_summary(result.report.summary)+ await sync_to_async(AlertCheck.objects.filter(id=alert_check.id).update, thread_sensitive=False)(+ investigation_notebook_id=notebook.id,+ investigation_status=InvestigationStatus.DONE,+ investigation_verdict=result.report.verdict,+ investigation_summary=summary_for_list,+ investigation_error=None,+ )++ # Always invoke the dispatcher — it reads the check's own delivery state+ # (`notification_sent_at` / `notification_suppressed_by_agent`) as its+ # idempotency guard, so non-gated checks (already dispatched by the main+ # task) short-circuit safely. Calling unconditionally closes the race where+ # a user toggles `investigation_gates_notifications` from True → False+ # after the check was held back but before the workflow completes — in+ # that case the current flag would say "don't dispatch" even though the+ # notification was never sent.+ await sync_to_async(_dispatch_gated_notification, thread_sensitive=False)(+ alert=alert,+ alert_check=alert_check,+ verdict=result.report.verdict,+ summary=summary_for_list or "",+ notebook_short_id=notebook.short_id,+ )+++def _dispatch_gated_notification(+ *,+ alert,+ alert_check,+ verdict: str | None,+ summary: str,+ notebook_short_id: str | None,+) -> None:+ """Decide whether to fire the notification now that we have the verdict.++ - 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)++ Idempotent: if another codepath (retry, safety-net task) already dispatched,+ this is a no-op.+ """+ inconclusive_action = alert.investigation_inconclusive_action or "notify"+ suppress = verdict == "false_positive" or (verdict == "inconclusive" and inconclusive_action == "suppress")++ with transaction.atomic():+ # Re-fetch under a row lock so concurrent dispatchers can't double-notify.+ check = AlertCheck.objects.select_for_update().get(id=alert_check.id)+ if check.notification_sent_at is not None or check.notification_suppressed_by_agent:+ return++ if suppress:+ check.notification_suppressed_by_agent = True+ check.save(update_fields=["notification_suppressed_by_agent"])+ logger.info(+ "anomaly_investigation.notification_suppressed",+ alert_id=str(alert.id),+ alert_check_id=str(alert_check.id),+ verdict=verdict,+ )+ return++ breaches = _build_breach_descriptions(+ alert_check=check, verdict=verdict, summary=summary, notebook_short_id=notebook_short_id+ )+ try:+ targets = dispatch_alert_notification(alert, check, breaches)+ if targets is not None:+ record_alert_delivery(alert, check, targets)+ except Exception:+ logger.exception(+ "anomaly_investigation.gated_notification_failed",+ alert_id=str(alert.id),+ alert_check_id=str(alert_check.id),+ )+ # Don't swallow — let the safety-net task retry on the next tick.+ raise++ # Keep notification_sent_at updated in lock-step with the delivery so the+ # safety-net's idempotency check still trips on a successful workflow dispatch.+ check.notification_sent_at = timezone.now()+ check.save(update_fields=["notification_sent_at"])+++def _build_breach_descriptions(+ *,+ alert_check,+ verdict: str | None,+ summary: str,+ notebook_short_id: str | None,+) -> list[str]:+ """Compose the strings that populate the `match_descriptions` list in the+ existing alert email template. Keeps the current template working while+ giving gated notifications richer body content.+ """+ lines: list[str] = []+ triggered_dates = alert_check.triggered_dates or []+ if triggered_dates:+ if len(triggered_dates) == 1:+ lines.append(f"Anomaly detected on {triggered_dates[0]}.")+ else:+ lines.append(f"Anomaly detected from {triggered_dates[0]} to {triggered_dates[-1]}.")+ elif alert_check.calculated_value is not None:+ lines.append(f"Calculated value at fire: {alert_check.calculated_value}.")+ else:+ lines.append("Anomaly detected.")++ verdict_label = {"true_positive": "True positive", "inconclusive": "Inconclusive"}.get(verdict or "", "")+ if verdict_label:+ lines.append(f"Investigation verdict: {verdict_label}.")+ if summary:+ lines.append(summary)+ if notebook_short_id:+ lines.append(f"See /notebooks/{notebook_short_id} for the full investigation.")+ return lines+++def _truncate_summary(summary: str | None) -> str | None:+ """Clamp the agent's summary for list rendering and email/Slack follow-ups.++ The full write-up already lives in the notebook — this field is just a teaser.+ """+ if not summary:+ return None+ trimmed = summary.strip()+ if not trimmed:+ return None+ if len(trimmed) <= MAX_SUMMARY_CHARS:+ return trimmed+ return trimmed[: MAX_SUMMARY_CHARS - 1].rstrip() + "…"+++async def _update_status(alert_check, status: str) -> None:+ await sync_to_async(AlertCheck.objects.filter(id=alert_check.id).update, thread_sensitive=False)(+ investigation_status=status,+ )+++async def _mark_failed(alert_check, reason: str) -> None:+ await sync_to_async(AlertCheck.objects.filter(id=alert_check.id).update, thread_sensitive=False)(+ investigation_status=InvestigationStatus.FAILED,+ investigation_error={"message": reason},+ )+++def _build_multimodal_context(*, alert, context_text: str):+ """Return a LangChain HumanMessage content value — either a plain string or a+ list of content blocks with the text and a rendered chart PNG.++ Best-effort: if the detector can't simulate or the chart fails to render, we+ fall back to text-only so the investigation still runs.+ """+ if alert.detector_config is None or alert.insight is None:+ return context_text++ sim = _run_detector_simulation(alert=alert, team=alert.team, date_from=None)+ if isinstance(sim, str) or not sim:+ logger.info("anomaly_investigation.chart_skipped", alert_id=str(alert.id), reason=str(sim)[:120])+ return context_text++ dates = sim.get("dates") or []+ values = sim.get("data") or []+ if not dates or not values:+ return context_text++ png = render_series_chart(+ dates=dates,+ values=values,+ triggered_indices=sim.get("triggered_indices") or [],+ scores=sim.get("scores") or None,+ title=(alert.insight.name or alert.name or "Metric")[:80],+ )+ if not png:+ return context_text++ return [+ {"type": "text", "text": context_text},+ {+ "type": "image",+ "source": {+ "type": "base64",+ "media_type": "image/png",+ "data": png_to_b64(png),+ },+ },+ ]+++async def _pick_investigation_user(alert) -> User | None:+ """Fall back to the alert creator, then any subscribed user, then None."""++ def _resolve() -> User | None:+ if alert.created_by_id:+ try:+ return User.objects.get(id=alert.created_by_id)+ except User.DoesNotExist:+ pass+ return alert.subscribed_users.first()++ return await sync_to_async(_resolve, thread_sensitive=False)()diff --git a/posthog/temporal/alerts/__init__.py b/posthog/temporal/alerts/__init__.pyindex 20c3edbb0e1b..7e8b919aac2a 100644--- a/posthog/temporal/alerts/__init__.py+++ b/posthog/temporal/alerts/__init__.py@@ -1,11 +1,26 @@-from posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert, retrieve_due_alerts-from posthog.temporal.alerts.workflows import CheckAlertWorkflow, ScheduleDueAlertChecksWorkflow+from posthog.temporal.alerts.activities import (+ evaluate_alert,+ notify_alert,+ prepare_alert,+ retrieve_due_alerts,+ run_investigation_safety_net,+)+from posthog.temporal.alerts.workflows import (+ CheckAlertWorkflow,+ RunInvestigationSafetyNetWorkflow,+ ScheduleDueAlertChecksWorkflow,+)-WORKFLOWS = [ScheduleDueAlertChecksWorkflow, CheckAlertWorkflow]+WORKFLOWS = [+ ScheduleDueAlertChecksWorkflow,+ CheckAlertWorkflow,+ RunInvestigationSafetyNetWorkflow,+]ACTIVITIES = [retrieve_due_alerts,prepare_alert,evaluate_alert,notify_alert,+ run_investigation_safety_net,]diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex 7d51d389f3ee..10d1549c89a2 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -18,6 +18,7 @@ from posthog.models.alert import AlertCheckfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.sync import database_sync_to_asyncfrom posthog.tasks.alerts.checks import AlertCheckException, add_alert_check, check_alert_for_insight+from posthog.tasks.alerts.investigation_notifications import run_investigation_notification_safety_netfrom posthog.tasks.alerts.schedule_restriction import is_utc_datetime_blocked, next_unblocked_utcfrom posthog.tasks.alerts.utils import (disable_invalid_alert,@@ -27,6 +28,7 @@ from posthog.tasks.alerts.utils import (skip_because_of_weekend,validate_alert_config,)+from posthog.temporal.alerts.investigation import claim_investigation_slot, should_trigger_investigationfrom posthog.temporal.alerts.types import (AlertInfo,EvaluateAlertActivityInputs,@@ -190,6 +192,10 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe# CH workload management keys off this tag to isolate alert queries from other tenants.tag_queries(alert_config_id=str(alert.id))+ # Snapshot before add_alert_check mutates alert.state — needed to detect the+ # NOT_FIRING/ERRORED -> FIRING transition that triggers an investigation.+ previous_state = alert.state+value: float | None = Nonebreaches: list[str] | None = Noneerror: dict | None = None@@ -219,6 +225,8 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertReinterval = alert_evaluation_result.interval if alert_evaluation_result else Nonetriggered_metadata = alert_evaluation_result.triggered_metadata if alert_evaluation_result else None+ should_start_investigation = False+ should_gate_notification = Falsewith transaction.atomic():alert_check, should_notify = add_alert_check(alert,@@ -232,11 +240,23 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRetriggered_metadata,)+ if should_trigger_investigation(+ alert,+ previous_state=previous_state,+ new_state=alert_check.state,+ ):+ if claim_investigation_slot(alert, alert_check):+ should_start_investigation = True+ should_gate_notification = bool(alert.investigation_gates_notifications)+return EvaluateAlertResult(alert_check_id=str(alert_check.id),should_notify=should_notify,new_state=AlertState(alert_check.state),breaches=breaches,+ should_start_investigation=should_start_investigation,+ should_gate_notification=should_gate_notification,+ investigation_user_id=alert.created_by_id if should_start_investigation else None,)async with Heartbeater():@@ -274,6 +294,25 @@ async def notify_alert(inputs: NotifyAlertActivityInputs) -> None:with transaction.atomic():record_alert_delivery(alert, alert_check, targets)+ # Stamp notification_sent_at in lock-step with delivery — the investigation+ # workflow and safety-net both read this column to decide whether they still+ # need to dispatch, and the gating path relies on it for idempotency.+ AlertCheck.objects.filter(id=alert_check.id).update(notification_sent_at=datetime.now(UTC))async with Heartbeater():await _notify()+++async def run_investigation_safety_net() -> int:+ """Force-dispatch notifications for gated AlertChecks whose investigation stalled.++ Returns the number of checks that were force-notified (for metrics / tests).+ """++ @database_sync_to_async(thread_sensitive=False)+ def _sweep() -> int:+ return run_investigation_notification_safety_net()++ async with Heartbeater():+ return await _sweep()diff --git a/posthog/temporal/alerts/investigation.py b/posthog/temporal/alerts/investigation.pynew file mode 100644index 000000000000..1217e6ddb743--- /dev/null+++ b/posthog/temporal/alerts/investigation.py@@ -0,0 +1,66 @@+"""Investigation-agent trigger helpers used by the Temporal evaluate_alert activity.++The trigger and notification-gating decisions both run inside `evaluate_alert`+in the same DB transaction as the AlertCheck insert, so the read-then-write that+claims the cooldown lease stays consistent. This module exposes the primitives+as pure functions so they can be unit-tested independently of Temporal.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++from posthog.schema import AlertState++from posthog.models import AlertConfiguration+from posthog.models.alert import AlertCheck, InvestigationStatus++INVESTIGATION_COOLDOWN = timedelta(hours=1)+++def should_trigger_investigation(+ alert: AlertConfiguration,+ *,+ previous_state: str | None,+ new_state: str,+) -> bool:+ """True when this fire is eligible for an investigation, ignoring cooldown.++ Cooldown is enforced by `claim_investigation_slot`, which does the read-then-write+ inside the caller's transaction.+ """+ if not alert.investigation_agent_enabled:+ return False+ if not alert.detector_config:+ return False+ if previous_state == AlertState.FIRING:+ return False+ if new_state != AlertState.FIRING:+ return False+ return True+++def claim_investigation_slot(alert: AlertConfiguration, alert_check: AlertCheck) -> bool:+ """Try to claim the cooldown slot for `alert` and return True on success.++ On success, marks `alert_check.investigation_status = PENDING`. On failure+ (a recent investigation is RUNNING/DONE/PENDING within the cooldown window),+ marks it SKIPPED and returns False so flappy alerts don't pile up.++ Caller must run this inside a transaction so the read-then-write is atomic.+ """+ cooldown_since = datetime.now(UTC) - INVESTIGATION_COOLDOWN+ recent = AlertCheck.objects.filter(+ alert_configuration=alert,+ created_at__gte=cooldown_since,+ investigation_status__in=[+ InvestigationStatus.RUNNING,+ InvestigationStatus.DONE,+ InvestigationStatus.PENDING,+ ],+ ).exclude(id=alert_check.id)+ if recent.exists():+ AlertCheck.objects.filter(id=alert_check.id).update(investigation_status=InvestigationStatus.SKIPPED)+ return False+ AlertCheck.objects.filter(id=alert_check.id).update(investigation_status=InvestigationStatus.PENDING)+ return Truediff --git a/posthog/temporal/alerts/schedule.py b/posthog/temporal/alerts/schedule.pyindex c7a8636ccc0c..e910648ff014 100644--- a/posthog/temporal/alerts/schedule.py+++ b/posthog/temporal/alerts/schedule.py@@ -14,6 +14,7 @@ from temporalio.client import (from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_scheduleSCHEDULE_ID = "schedule-due-alert-checks-schedule"+INVESTIGATION_SAFETY_NET_SCHEDULE_ID = "run-investigation-safety-net-schedule"async def create_schedule_due_alert_checks_schedule(client: Client) -> None:@@ -32,3 +33,27 @@ async def create_schedule_due_alert_checks_schedule(client: Client) -> None:await a_update_schedule(client, SCHEDULE_ID, schedule)else:await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=False)+++async def create_run_investigation_safety_net_schedule(client: Client) -> None:+ """Investigation-gated alerts that stall past the grace period get force-notified by this sweep.++ Skip the run if the previous one is still in flight (SKIP overlap policy) — the+ sweep is idempotent and missing one tick is harmless because the next will pick+ up the same checks.+ """+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ "run-investigation-safety-net",+ id=INVESTIGATION_SAFETY_NET_SCHEDULE_ID,+ task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,+ execution_timeout=dt.timedelta(minutes=5),+ ),+ spec=ScheduleSpec(cron_expressions=["*/2 * * * *"]),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )++ if await a_schedule_exists(client, INVESTIGATION_SAFETY_NET_SCHEDULE_ID):+ await a_update_schedule(client, INVESTIGATION_SAFETY_NET_SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, INVESTIGATION_SAFETY_NET_SCHEDULE_ID, schedule, trigger_immediately=False)diff --git a/posthog/temporal/alerts/types.py b/posthog/temporal/alerts/types.pyindex 4bcedc0d90d1..8dc6be90c7bc 100644--- a/posthog/temporal/alerts/types.py+++ b/posthog/temporal/alerts/types.py@@ -66,6 +66,15 @@ class EvaluateAlertResult:# Human-readable breach descriptions the FIRING email uses as match_descriptions.# Not persisted on AlertCheck, so the workflow must pipe them from evaluate to notify.breaches: list[str] | None = None+ # Investigation agent is opted in and this fire claimed the cooldown slot. Workflow+ # should start the AnomalyInvestigationWorkflow as a child.+ should_start_investigation: bool = False+ # Hold the synchronous notification — the investigation workflow will dispatch it+ # itself after the verdict, or the safety-net schedule will force-fire on stall.+ should_gate_notification: bool = False+ # Persisted alert.created_by — the investigation workflow uses this to attribute+ # the resulting Notebook. Optional because legacy alerts may not have it.+ investigation_user_id: int | None = None@dataclasses.dataclass(frozen=True)diff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.pyindex 1f1108f1864c..9403a23a4e77 100644--- a/posthog/temporal/alerts/workflows.py+++ b/posthog/temporal/alerts/workflows.py@@ -1,6 +1,7 @@import jsonimport asyncioimport datetime as dt+from uuid import UUIDimport temporalio.commonimport temporalio.workflow@@ -9,7 +10,13 @@ from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedErrorfrom posthog.schema import AlertStatefrom posthog.slo.types import SloArea, SloConfig, SloOperation-from posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert, retrieve_due_alerts+from posthog.temporal.alerts.activities import (+ evaluate_alert,+ notify_alert,+ prepare_alert,+ retrieve_due_alerts,+ run_investigation_safety_net,+)from posthog.temporal.alerts.retry_policy import (ALERT_EVALUATE_RETRY_POLICY,ALERT_NOTIFY_RETRY_POLICY,@@ -24,6 +31,11 @@ from posthog.temporal.alerts.types import ()from posthog.temporal.common.base import PostHogWorkflow+with temporalio.workflow.unsafe.imports_passed_through():+ from django.conf import settings++ from posthog.temporal.ai.anomaly_investigation import AnomalyInvestigationWorkflowInputs+@temporalio.workflow.defn(name="schedule-due-alert-checks")class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):@@ -142,7 +154,10 @@ class CheckAlertWorkflow(PostHogWorkflow):new_state = evaluation.new_state# Phase 3 — notify (optional)- if evaluation.should_notify:+ # Skip the synchronous notify when the investigation agent is gating —+ # the AnomalyInvestigationWorkflow will dispatch (or suppress) after the+ # verdict, and the safety-net schedule force-fires if the workflow stalls.+ if evaluation.should_notify and not evaluation.should_gate_notification:await temporalio.workflow.execute_activity(notify_alert,NotifyAlertActivityInputs(@@ -154,6 +169,24 @@ class CheckAlertWorkflow(PostHogWorkflow):retry_policy=ALERT_NOTIFY_RETRY_POLICY,)+ # Phase 4 — kick off the anomaly investigation as an abandoned child+ # so it lives independently of this workflow's lifetime. Runs on the+ # AI task queue and uses a deterministic ID per AlertCheck so retries+ # of CheckAlertWorkflow don't double-start the investigation.+ if evaluation.should_start_investigation:+ await temporalio.workflow.start_child_workflow(+ "anomaly-investigation",+ AnomalyInvestigationWorkflowInputs(+ team_id=inputs.team_id,+ alert_id=UUID(inputs.alert_id),+ alert_check_id=UUID(evaluation.alert_check_id),+ user_id=evaluation.investigation_user_id,+ ),+ id=f"anomaly-investigation-{evaluation.alert_check_id}",+ task_queue=settings.MAX_AI_TASK_QUEUE,+ parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,+ )+except Exception as e:caught_error = e@@ -171,3 +204,29 @@ class CheckAlertWorkflow(PostHogWorkflow):# Re-raise after cleanup completes. Same Temporal SDK quirk as ProcessSubscriptionWorkflowif caught_error:raise caught_error++[email protected](name="run-investigation-safety-net")+class RunInvestigationSafetyNetWorkflow(PostHogWorkflow):+ """Periodic sweep that force-dispatches notifications for stalled investigation checks.++ Runs as a Temporal schedule (see posthog/temporal/alerts/schedule.py). The actual+ DB scan + dispatch lives in `run_investigation_safety_net` so the workflow stays+ a thin shell.+ """++ @staticmethod+ def parse_inputs(inputs: list[str]) -> None:+ return None++ @temporalio.workflow.run+ async def run(self) -> None:+ await temporalio.workflow.execute_activity(+ run_investigation_safety_net,+ start_to_close_timeout=dt.timedelta(minutes=2),+ retry_policy=temporalio.common.RetryPolicy(+ initial_interval=dt.timedelta(seconds=5),+ maximum_interval=dt.timedelta(seconds=30),+ maximum_attempts=2,+ ),+ )diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex e8794be70a51..e7b4e3c865c8 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -23,7 +23,10 @@ from temporalio.client import (from posthog.hogql_queries.ai.vector_search_query_runner import LATEST_ACTIONS_EMBEDDING_VERSIONfrom posthog.temporal.ai import SyncVectorsInputsfrom posthog.temporal.ai.sync_vectors import EmbeddingVersion-from posthog.temporal.alerts.schedule import create_schedule_due_alert_checks_schedule+from posthog.temporal.alerts.schedule import (+ create_run_investigation_safety_net_schedule,+ create_schedule_due_alert_checks_schedule,+)from posthog.temporal.common.client import async_connectfrom posthog.temporal.common.schedule import a_create_schedule, a_delete_schedule, a_schedule_exists, a_update_schedulefrom posthog.temporal.data_imports.signals.conversations_schedule import (@@ -555,6 +558,7 @@ schedules = [create_wa_weekly_digest_schedule,create_logs_alert_check_schedule,create_schedule_due_alert_checks_schedule,+ create_run_investigation_safety_net_schedule,]if settings.CLOUD_DEPLOYMENT:diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_summary.py b/posthog/temporal/tests/ai/test_anomaly_investigation_summary.pynew file mode 100644index 000000000000..4ddbbdae4a08--- /dev/null+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_summary.py@@ -0,0 +1,25 @@+import pytest++from posthog.temporal.ai.anomaly_investigation.workflow import MAX_SUMMARY_CHARS, _truncate_summary+++ "input,expected",+ [+ (None, None),+ ("", None),+ (" ", None),+ ("Traffic doubled after a marketing campaign launch.", "Traffic doubled after a marketing campaign launch."),+ (" hello ", "hello"),+ ],+)+def test_truncate_summary_basic(input, expected) -> None:+ assert _truncate_summary(input) == expected+++def test_truncate_summary_clips_long_text_with_ellipsis() -> None:+ text = "x" * (MAX_SUMMARY_CHARS + 50)+ clipped = _truncate_summary(text)+ assert clipped is not None+ assert len(clipped) == MAX_SUMMARY_CHARS+ assert clipped.endswith("…")diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.pynew file mode 100644index 000000000000..7257f33bf11a--- /dev/null+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py@@ -0,0 +1,103 @@+"""Verifies that the workflow activity persists the agent's verdict onto the AlertCheck."""++import pytest+from posthog.test.base import NonAtomicBaseTest+from unittest.mock import patch++from asgiref.sync import sync_to_async++from posthog.schema import AlertState++from posthog.models import Insight+from posthog.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus, InvestigationVerdict+from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport+from posthog.temporal.ai.anomaly_investigation.runner import InvestigationRunResult+from posthog.temporal.ai.anomaly_investigation.workflow import (+ AnomalyInvestigationWorkflowInputs,+ investigate_anomaly_activity,+)+++class TestInvestigationVerdictPersistence(NonAtomicBaseTest):+ # NonAtomicBaseTest TRUNCATEs after each test so class-level fixtures stale out;+ # force per-test setup so self.team is freshly inserted each time.+ CLASS_DATA_LEVEL_SETUP = False++ def setUp(self) -> None:+ super().setUp()+ self.insight = Insight.objects.create(team=self.team, name="test insight")+ self.alert = AlertConfiguration.objects.create(+ team=self.team,+ insight=self.insight,+ name="anomaly alert",+ detector_config={"type": "zscore", "threshold": 0.95, "window": 30},+ investigation_agent_enabled=True,+ state=AlertState.FIRING,+ created_by=self.user,+ )+ self.alert_check = AlertCheck.objects.create(+ alert_configuration=self.alert,+ state=AlertState.FIRING,+ calculated_value=42.0,+ )++ @pytest.mark.asyncio+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")+ @patch("temporalio.activity.heartbeat")+ @patch("temporalio.activity.info")+ async def test_true_positive_verdict_is_persisted(self, mock_info, _heartbeat, mock_run) -> None:+ mock_info.return_value.heartbeat_timeout = None+ mock_run.return_value = InvestigationRunResult(+ report=InvestigationReport(+ verdict="true_positive",+ summary="Confirmed spike caused by campaign launch.",+ hypotheses=[],+ recommendations=[],+ ),+ tool_calls_used=0,+ model="test-model",+ )++ await investigate_anomaly_activity(+ AnomalyInvestigationWorkflowInputs(+ team_id=self.team.id,+ alert_id=self.alert.id,+ alert_check_id=self.alert_check.id,+ user_id=self.user.id,+ )+ )++ await sync_to_async(self.alert_check.refresh_from_db)()+ assert self.alert_check.investigation_status == InvestigationStatus.DONE+ assert self.alert_check.investigation_verdict == InvestigationVerdict.TRUE_POSITIVE+ assert self.alert_check.investigation_summary == "Confirmed spike caused by campaign launch."+ assert self.alert_check.investigation_notebook_id is not None++ @pytest.mark.asyncio+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")+ @patch("temporalio.activity.heartbeat")+ @patch("temporalio.activity.info")+ async def test_false_positive_verdict_is_persisted(self, mock_info, _heartbeat, mock_run) -> None:+ mock_info.return_value.heartbeat_timeout = None+ mock_run.return_value = InvestigationRunResult(+ report=InvestigationReport(+ verdict="false_positive",+ summary="Spike was a replay of duplicated events from a broken SDK release.",+ hypotheses=[],+ recommendations=[],+ ),+ tool_calls_used=0,+ model="test-model",+ )++ await investigate_anomaly_activity(+ AnomalyInvestigationWorkflowInputs(+ team_id=self.team.id,+ alert_id=self.alert.id,+ alert_check_id=self.alert_check.id,+ user_id=self.user.id,+ )+ )++ await sync_to_async(self.alert_check.refresh_from_db)()+ assert self.alert_check.investigation_verdict == InvestigationVerdict.FALSE_POSITIVEdiff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex 0d293cf67c5a..c6ed44018857 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -27,6 +27,7 @@ class TestAITemporalModuleIntegrity:"SlackConversationRunnerWorkflow","PostHogCodeSlackMentionWorkflow","PostHogCodeSlackTerminateTaskWorkflow",+ "AnomalyInvestigationWorkflow",]actual_workflow_names = [workflow.__name__ for workflow in ai.AI_WORKFLOWS]assert len(actual_workflow_names) == len(expected_workflows), (@@ -66,6 +67,7 @@ class TestAITemporalModuleIntegrity:"post_posthog_code_picker_timeout_activity","post_posthog_code_internal_error_activity","process_posthog_code_terminate_task_activity",+ "investigate_anomaly_activity",]actual_activity_names = [activity.__name__ for activity in ai.AI_ACTIVITIES]assert len(actual_activity_names) == len(expected_activities), (diff --git a/posthog/temporal/tests/test_alerts_investigation.py b/posthog/temporal/tests/test_alerts_investigation.pynew file mode 100644index 000000000000..9896c62863f8--- /dev/null+++ b/posthog/temporal/tests/test_alerts_investigation.py@@ -0,0 +1,149 @@+"""Tests for the investigation-agent trigger helpers in posthog/temporal/alerts/investigation.py.++The decision logic — should we kick off an investigation, can we claim the cooldown+slot — runs synchronously inside the `evaluate_alert` activity. These tests exercise+the helpers directly so they're independent of Temporal harnessing.+"""++from datetime import UTC, datetime, timedelta++from freezegun import freeze_time+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.schema import AlertState++from posthog.models import Insight+from posthog.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus+from posthog.temporal.alerts.investigation import claim_investigation_slot, should_trigger_investigation+++class TestShouldTriggerInvestigation(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.insight = Insight.objects.create(team=self.team, name="test insight")+ self.alert = AlertConfiguration.objects.create(+ team=self.team,+ insight=self.insight,+ name="anomaly alert",+ detector_config={"type": "zscore", "threshold": 0.95, "window": 30},+ investigation_agent_enabled=True,+ )++ def test_triggers_on_transition_to_firing(self) -> None:+ assert should_trigger_investigation(+ self.alert,+ previous_state=AlertState.NOT_FIRING,+ new_state=AlertState.FIRING,+ )++ @parameterized.expand(+ [+ ("already_firing", AlertState.FIRING, AlertState.FIRING),+ ("still_not_firing", AlertState.NOT_FIRING, AlertState.NOT_FIRING),+ ("transition_to_errored", AlertState.NOT_FIRING, AlertState.ERRORED),+ ]+ )+ def test_does_not_trigger_on_other_transitions(self, _name: str, previous: str, new: str) -> None:+ assert not should_trigger_investigation(self.alert, previous_state=previous, new_state=new)++ def test_does_not_trigger_when_not_opted_in(self) -> None:+ self.alert.investigation_agent_enabled = False+ self.alert.save()+ assert not should_trigger_investigation(+ self.alert,+ previous_state=AlertState.NOT_FIRING,+ new_state=AlertState.FIRING,+ )++ def test_does_not_trigger_for_threshold_only_alerts(self) -> None:+ self.alert.detector_config = None+ self.alert.save()+ assert not should_trigger_investigation(+ self.alert,+ previous_state=AlertState.NOT_FIRING,+ new_state=AlertState.FIRING,+ )+++class TestClaimInvestigationSlot(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.insight = Insight.objects.create(team=self.team, name="test insight")+ self.alert = AlertConfiguration.objects.create(+ team=self.team,+ insight=self.insight,+ name="anomaly alert",+ detector_config={"type": "zscore", "threshold": 0.95, "window": 30},+ investigation_agent_enabled=True,+ )++ def _make_check(self, *, investigation_status: str | None = None) -> AlertCheck:+ return AlertCheck.objects.create(+ alert_configuration=self.alert,+ state=AlertState.FIRING,+ calculated_value=42.0,+ investigation_status=investigation_status,+ )++ def test_claims_when_no_recent_investigation(self) -> None:+ check = self._make_check()+ assert claim_investigation_slot(self.alert, check)+ check.refresh_from_db()+ assert check.investigation_status == InvestigationStatus.PENDING++ def test_skips_when_recent_investigation_exists(self) -> None:+ now = datetime(2026, 4, 30, 10, 0, tzinfo=UTC)+ with freeze_time(now - timedelta(minutes=10)):+ self._make_check(investigation_status=InvestigationStatus.DONE)++ with freeze_time(now):+ new_check = self._make_check()+ assert not claim_investigation_slot(self.alert, new_check)++ new_check.refresh_from_db()+ assert new_check.investigation_status == InvestigationStatus.SKIPPED++ def test_claims_after_cooldown_expires(self) -> None:+ now = datetime(2026, 4, 30, 10, 0, tzinfo=UTC)+ with freeze_time(now - timedelta(hours=2)):+ self._make_check(investigation_status=InvestigationStatus.DONE)++ with freeze_time(now):+ new_check = self._make_check()+ assert claim_investigation_slot(self.alert, new_check)++ new_check.refresh_from_db()+ assert new_check.investigation_status == InvestigationStatus.PENDING++ @parameterized.expand(+ [+ ("running", InvestigationStatus.RUNNING),+ ("done", InvestigationStatus.DONE),+ ("pending", InvestigationStatus.PENDING),+ ]+ )+ def test_cooldown_blocks_for_active_statuses(self, _name: str, blocking_status: str) -> None:+ now = datetime(2026, 4, 30, 10, 0, tzinfo=UTC)+ with freeze_time(now - timedelta(minutes=10)):+ self._make_check(investigation_status=blocking_status)++ with freeze_time(now):+ new_check = self._make_check()+ assert not claim_investigation_slot(self.alert, new_check)++ @parameterized.expand(+ [+ ("skipped", InvestigationStatus.SKIPPED),+ ("failed", InvestigationStatus.FAILED),+ ]+ )+ def test_cooldown_ignores_terminal_failure_statuses(self, _name: str, terminal_status: str) -> None:+ now = datetime(2026, 4, 30, 10, 0, tzinfo=UTC)+ with freeze_time(now - timedelta(minutes=10)):+ self._make_check(investigation_status=terminal_status)++ with freeze_time(now):+ new_check = self._make_check()+ assert claim_investigation_slot(self.alert, new_check)