Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): emit anomaly_investigation signal from alert agent (#70136)

Radu Raiceaae4b1e9ac8a8
diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.py
index cb988be04386..3b3c15462c98 100644
--- a/posthog/temporal/ai/anomaly_investigation/workflow.py
+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py
@@ -11,7 +11,7 @@ import json
import asyncio
from dataclasses import dataclass
from datetime import timedelta
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
from uuid import UUID
from django.db import transaction
@@ -27,6 +27,7 @@ from posthog.tasks.alerts.utils import dispatch_alert_notification, record_alert
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.report import InvestigationReport
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
@@ -35,9 +36,18 @@ from posthog.utils import absolute_uri
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
from products.notebooks.backend.facade import api as notebooks
+from products.signals.backend.facade import api as signals
+
+if TYPE_CHECKING:
+ from products.product_analytics.backend.models.insight import Insight
logger = structlog.get_logger(__name__)
+# (source_product, source_type) identifiers for the emitted signal. The signals taxonomy, payload
+# contract, and inbox support for this pair are added in a separate PR; this module only emits.
+SIGNAL_SOURCE_PRODUCT = "analytics"
+SIGNAL_SOURCE_TYPE = "anomaly_investigation"
+
ANOMALY_INVESTIGATION_ACTIVITY_START_TO_CLOSE = 20 * 60 # 20 minutes
ANOMALY_INVESTIGATION_ACTIVITY_HEARTBEAT_TIMEOUT = 5 * 60 # 5 minutes
@@ -45,6 +55,11 @@ ANOMALY_INVESTIGATION_ACTIVITY_MAX_ATTEMPTS = 2
MAX_SUMMARY_CHARS = 500
+# Cap for the embedded signal description. Kept well under the signals facade's ~8000-token limit
+# (a conservative margin even for token-dense text) so a long agent report can't get the signal
+# rejected and silently dropped.
+_MAX_DESCRIPTION_CHARS = 3000
+
# Matches a sentence-ending punctuation mark followed by whitespace or end-of-string,
# used to clip the summary teaser on a sentence boundary instead of mid-word.
_SENTENCE_END_RE = re.compile(r"[.!?](?=\s|$)")
@@ -186,6 +201,128 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput
notebook_short_id=notebook.short_id,
)
+ # Surface the completed investigation to the Signals inbox. Best-effort: the investigation
+ # itself has already succeeded and been persisted, so a failure to emit must not fail the
+ # activity (and trigger a re-run of the whole agent).
+ try:
+ await _emit_investigation_signal(
+ team=team,
+ alert=alert,
+ alert_check=alert_check,
+ insight=insight,
+ detector_type=detector_type,
+ report=result.report,
+ notebook_short_id=notebook.short_id,
+ )
+ except Exception:
+ logger.exception(
+ "anomaly_investigation.signal_emission_failed",
+ alert_id=str(alert.id),
+ alert_check_id=str(alert_check.id),
+ )
+
+
+def _build_investigation_signal_extra(
+ *,
+ alert: AlertConfiguration,
+ alert_check: AlertCheck,
+ insight: Insight,
+ detector_type: str,
+ report: InvestigationReport,
+ notebook_short_id: str | None,
+) -> dict:
+ """The `extra` payload for an anomaly-investigation signal — a plain dict validated against
+ `AnomalyInvestigationSignalExtra` inside `emit_signal`."""
+ notebook_url = absolute_uri(f"/notebooks/{notebook_short_id}") if notebook_short_id else absolute_uri("/alerts")
+ extra: dict = {
+ "alert_id": str(alert.id),
+ "alert_name": alert.name or "Unnamed alert",
+ "alert_check_id": str(alert_check.id),
+ "insight_id": str(insight.id),
+ "detector_type": detector_type,
+ "verdict": report.verdict,
+ "url": notebook_url,
+ }
+ # Optional fields — omit when absent so the schema's None defaults apply.
+ if insight.name:
+ extra["insight_name"] = insight.name
+ insight_short_id = getattr(insight, "short_id", None)
+ if insight_short_id:
+ extra["insight_short_id"] = insight_short_id
+ if alert_check.triggered_dates:
+ extra["triggered_dates"] = list(alert_check.triggered_dates)
+ if notebook_short_id:
+ extra["notebook_short_id"] = notebook_short_id
+ return extra
+
+
+async def _emit_investigation_signal(
+ *,
+ team: Team,
+ alert: AlertConfiguration,
+ alert_check: AlertCheck,
+ insight: Insight,
+ detector_type: str,
+ report: InvestigationReport,
+ notebook_short_id: str | None,
+) -> None:
+ """Emit an `alerts/anomaly_investigation` signal carrying the agent's verdict and findings."""
+ await signals.emit_signal(
+ team=team,
+ source_product=SIGNAL_SOURCE_PRODUCT,
+ source_type=SIGNAL_SOURCE_TYPE,
+ source_id=str(alert_check.id),
+ description=_build_signal_description(
+ alert_name=alert.name or "Unnamed alert",
+ insight_name=insight.name or None,
+ insight_id=str(insight.id),
+ insight_short_id=getattr(insight, "short_id", None),
+ report=report,
+ ),
+ weight=1,
+ extra=_build_investigation_signal_extra(
+ alert=alert,
+ alert_check=alert_check,
+ insight=insight,
+ detector_type=detector_type,
+ report=report,
+ notebook_short_id=notebook_short_id,
+ ),
+ )
+
+
+def _build_signal_description(
+ *,
+ alert_name: str,
+ insight_name: str | None,
+ insight_id: str,
+ insight_short_id: str | None,
+ report: InvestigationReport,
+) -> str:
+ """Human-readable description embedded for grouping. Leads with the verdict, names the insight
+ (with its id, handy for lookups), then the agent's summary, hypotheses, and recommendations."""
+ verdict_label = report.verdict.replace("_", " ")
+ metric = f" on {insight_name}" if insight_name else ""
+ insight_ref = f"{insight_short_id} / id {insight_id}" if insight_short_id else f"id {insight_id}"
+ lines: list[str] = [
+ f"Anomaly investigation for alert '{alert_name}'{metric} (verdict: {verdict_label}).",
+ f"Insight: {insight_ref}.",
+ report.summary,
+ ]
+ if report.hypotheses:
+ lines.append("Hypotheses:")
+ lines.extend(f"- {h.title}: {h.rationale}" for h in report.hypotheses)
+ if report.recommendations:
+ lines.append("Recommendations:")
+ lines.extend(f"- {rec}" for rec in report.recommendations)
+ description = "\n".join(line for line in lines if line)
+ # Bound the agent-generated text so it can't blow the facade's description token limit — past it
+ # emit_signal raises and the best-effort caller would silently drop the signal. The full write-up
+ # lives in the linked notebook, so truncating the embedded description is safe.
+ if len(description) > _MAX_DESCRIPTION_CHARS:
+ description = description[: _MAX_DESCRIPTION_CHARS - 1].rstrip() + "…"
+ return description
+
def _dispatch_gated_notification(
*,
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_signal.py b/posthog/temporal/tests/ai/test_anomaly_investigation_signal.py
new file mode 100644
index 000000000000..7a00b91f54d5
--- /dev/null
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_signal.py
@@ -0,0 +1,44 @@
+from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
+from posthog.temporal.ai.anomaly_investigation.workflow import _MAX_DESCRIPTION_CHARS, _build_signal_description
+
+
+class TestBuildSignalDescription:
+ def test_long_report_is_truncated_under_cap(self) -> None:
+ # A runaway agent summary must not push the description past emit_signal's token limit,
+ # which would raise and let the best-effort caller silently drop the signal.
+ report = InvestigationReport(
+ verdict="true_positive",
+ summary="x" * 10000,
+ hypotheses=[],
+ recommendations=[],
+ )
+
+ description = _build_signal_description(
+ alert_name="Signups dropped",
+ insight_name="Daily signups",
+ insight_id="42",
+ insight_short_id="abc123",
+ report=report,
+ )
+
+ assert len(description) <= _MAX_DESCRIPTION_CHARS
+ assert description.endswith("…")
+
+ def test_short_report_includes_verdict_and_insight_id(self) -> None:
+ report = InvestigationReport(
+ verdict="true_positive",
+ summary="Signups fell after the deploy.",
+ hypotheses=[],
+ recommendations=[],
+ )
+
+ description = _build_signal_description(
+ alert_name="Signups dropped",
+ insight_name="Daily signups",
+ insight_id="42",
+ insight_short_id="abc123",
+ report=report,
+ )
+
+ assert "verdict: true positive" in description
+ assert "id 42" in description
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
index 284d7fc0b1b7..ed1297b39ca4 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_verdict.py
@@ -107,3 +107,40 @@ class TestInvestigationVerdictPersistence(NonAtomicBaseTest):
await sync_to_async(self.alert_check.refresh_from_db)()
assert self.alert_check.investigation_verdict == InvestigationVerdict.FALSE_POSITIVE
+
+ @pytest.mark.asyncio
+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.signals.emit_signal")
+ @patch("posthog.temporal.ai.anomaly_investigation.workflow.run_investigation")
+ @patch("temporalio.activity.heartbeat")
+ @patch("temporalio.activity.info")
+ async def test_completed_investigation_emits_signal(self, mock_info, _heartbeat, mock_run, mock_emit) -> 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,
+ )
+ )
+
+ mock_emit.assert_awaited_once()
+ kwargs = mock_emit.await_args.kwargs
+ assert kwargs["source_product"] == "analytics"
+ assert kwargs["source_type"] == "anomaly_investigation"
+ assert kwargs["source_id"] == str(self.alert_check.id)
+ assert kwargs["weight"] == 1
+ assert kwargs["extra"]["verdict"] == "true_positive"
+ assert kwargs["extra"]["insight_id"] == str(self.insight.id)
+ assert not {"summary", "hypotheses", "recommendations", "tool_calls_used"} & kwargs["extra"].keys()