: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): use structured anomaly investigation reports (#58919)
Andrew Maguiree0f3fb9ca672
diff --git a/posthog/temporal/ai/anomaly_investigation/prompts.py b/posthog/temporal/ai/anomaly_investigation/prompts.pyindex 4a7dc5ca1157..48a4db1a3de2 100644--- a/posthog/temporal/ai/anomaly_investigation/prompts.py+++ b/posthog/temporal/ai/anomaly_investigation/prompts.py@@ -25,8 +25,9 @@ Workflow:lean toward `false_positive` or `inconclusive` and use any remaining budgetto confirm rather than to keep hunting for a story.3. Decide which tool, if any, confirms or refutes your leading hypothesis.-4. Emit a final JSON report matching the schema below. Do not emit any free-form- text around it — output the raw JSON object only.+4. Submit the final report with the `submit_investigation_report` tool. If the+ tool is unavailable, emit a final JSON report matching the schema below with no+ free-form text around it.Final JSON schema (emit exactly these keys):{@@ -113,5 +114,5 @@ def build_anomaly_context(f"Triggered dates: {', '.join(triggered_dates) if triggered_dates else 'n/a'}\n"f"{metadata_line}\n\n""Use your tools to validate the anomaly and investigate the likely cause. "- "Return the final InvestigationReport JSON."+ "Submit the final InvestigationReport using the submit_investigation_report tool.")diff --git a/posthog/temporal/ai/anomaly_investigation/runner.py b/posthog/temporal/ai/anomaly_investigation/runner.pyindex 76dd20a4cd26..6b5ae1eb57b8 100644--- a/posthog/temporal/ai/anomaly_investigation/runner.py+++ b/posthog/temporal/ai/anomaly_investigation/runner.py@@ -37,6 +37,7 @@ logger = logging.getLogger(__name__)MAX_TOOL_CALLS = 10AGENT_MODEL = "claude-sonnet-4-6"+FINAL_REPORT_TOOL_NAME = "submit_investigation_report"MAX_TOOL_RESULT_CHARS = 12_000 # ~3K tokens per call — keeps 10 calls well under the context limit.# Per-request cap. The surrounding Temporal activity has its own (longer) deadline;# this guards against a single stuck HTTP call hanging for the whole activity budget.@@ -117,6 +118,15 @@ async def run_investigation(),]+ final_report_tool = {+ "name": FINAL_REPORT_TOOL_NAME,+ "description": (+ "Submit the final anomaly investigation report. Use this instead of writing "+ "JSON as plain text when you have finished investigating."+ ),+ "input_schema": InvestigationReport.model_json_schema(),+ }+llm = MaxChatAnthropic(model=AGENT_MODEL,team=team,@@ -129,14 +139,18 @@ async def run_investigation()llm_with_tools = llm.bind_tools([- {- "name": name,- "description": description,- "input_schema": schema.model_json_schema(),- }- for name, description, schema in tools_spec+ *(+ {+ "name": name,+ "description": description,+ "input_schema": schema.model_json_schema(),+ }+ for name, description, schema in tools_spec+ ),+ final_report_tool,])+ llm_with_final_report = llm.bind_tools([final_report_tool], tool_choice=FINAL_REPORT_TOOL_NAME)messages: list[Any] = [SystemMessage(content=SYSTEM_PROMPT),@@ -155,7 +169,7 @@ async def run_investigation(messages.append(HumanMessage(content=(- "Tool call budget exhausted. Emit the final InvestigationReport JSON "+ "Tool call budget exhausted. Submit the final InvestigationReport ""now using whatever evidence you have."))@@ -163,7 +177,7 @@ async def run_investigation(if heartbeat is not None:heartbeat()try:- final = await llm.ainvoke(messages)+ final = await llm_with_final_report.ainvoke(messages)except Exception as err:# Swallow final-turn failures and return an inconclusive report rather than# bouncing off Temporal retries — MaxChatAnthropic already exhausted its@@ -175,6 +189,10 @@ async def run_investigation(model=AGENT_MODEL,)messages.append(final)+ forced_report = _parse_report_message(final)+ if forced_report is not None:+ forced_report.tool_calls_used = tool_calls_used+ return InvestigationRunResult(report=forced_report, tool_calls_used=tool_calls_used, model=AGENT_MODEL)breaktry:@@ -189,6 +207,10 @@ async def run_investigation(messages.append(response)tool_calls = getattr(response, "tool_calls", None) or []+ structured_report = _report_from_tool_calls(tool_calls)+ if structured_report is not None:+ structured_report.tool_calls_used = tool_calls_used+ return InvestigationRunResult(report=structured_report, tool_calls_used=tool_calls_used, model=AGENT_MODEL)if not tool_calls:break@@ -198,7 +220,9 @@ async def run_investigation(tool_call_id = call.get("id") or call.get("tool_call_id") or ""# Enforce the cap per-call, not just per-turn — a single assistant# response can emit several parallel tool_use blocks.- if tool_calls_used >= MAX_TOOL_CALLS:+ if name == FINAL_REPORT_TOOL_NAME:+ content = "Final report tool call was invalid. Submit it again with all required fields."+ elif tool_calls_used >= MAX_TOOL_CALLS:content = "[skipped — tool call budget exhausted]"else:tool_calls_used += 1@@ -224,6 +248,21 @@ async def run_investigation(return InvestigationRunResult(report=report, tool_calls_used=tool_calls_used, model=AGENT_MODEL)+def _parse_report_message(message: Any) -> InvestigationReport | None:+ return _report_from_tool_calls(getattr(message, "tool_calls", None) or [])+++def _report_from_tool_calls(tool_calls: list[dict[str, Any]]) -> InvestigationReport | None:+ for call in tool_calls:+ if call.get("name") != FINAL_REPORT_TOOL_NAME:+ continue+ try:+ return InvestigationReport.model_validate(call.get("args") or {})+ except ValidationError:+ return None+ return None++def _parse_report(content: Any) -> InvestigationReport:text = _stringify(content).strip()if not text:diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py b/posthog/temporal/tests/ai/test_anomaly_investigation_runner.pynew file mode 100644index 000000000000..ac84e140fcfc--- /dev/null+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py@@ -0,0 +1,58 @@+from posthog.temporal.ai.anomaly_investigation.runner import (+ FINAL_REPORT_TOOL_NAME,+ _parse_report,+ _report_from_tool_calls,+)+++def test_report_from_tool_calls_accepts_structured_final_report() -> None:+ report = _report_from_tool_calls(+ [+ {+ "name": FINAL_REPORT_TOOL_NAME,+ "args": {+ "verdict": "false_positive",+ "summary": "The spike is within normal low-volume variance.",+ "hypotheses": [+ {+ "title": "Low-volume noise",+ "rationale": "The metric has sparse hourly counts.",+ "evidence": ["The triggered bucket was close to recent peaks."],+ }+ ],+ "recommendations": ["Aggregate to daily buckets."],+ },+ }+ ]+ )++ assert report is not None+ assert report.verdict == "false_positive"+ assert report.summary == "The spike is within normal low-volume variance."+ assert report.hypotheses[0].title == "Low-volume noise"+ assert report.recommendations == ["Aggregate to daily buckets."]+++def test_report_from_tool_calls_ignores_invalid_structured_final_report() -> None:+ report = _report_from_tool_calls(+ [+ {+ "name": FINAL_REPORT_TOOL_NAME,+ "args": {+ "verdict": "maybe",+ "summary": "Invalid verdict.",+ },+ }+ ]+ )++ assert report is None+++def test_parse_report_keeps_plain_json_fallback() -> None:+ report = _parse_report(+ '{"verdict":"inconclusive","summary":"Need manual review.","hypotheses":[],"recommendations":[]}'+ )++ assert report.verdict == "inconclusive"+ assert report.summary == "Need manual review."