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.

fix(alerts): recover leaked-string hypotheses from investigation report (#73499)

Andrew Maguire17d170b7e3f9
diff --git a/posthog/temporal/ai/anomaly_investigation/report.py b/posthog/temporal/ai/anomaly_investigation/report.py
index 65770afd9ace..be1ef24b0fc1 100644
--- a/posthog/temporal/ai/anomaly_investigation/report.py
+++ b/posthog/temporal/ai/anomaly_investigation/report.py
@@ -1,6 +1,30 @@
-from typing import Literal
+import json
+from typing import Any, Literal
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, field_validator
+
+
+def _recover_stringified_list(value: Any) -> Any:
+ """Coerce a list field the model emitted as a string back into a list.
+
+ Sonnet 5 (adaptive thinking) sometimes serializes a nested list argument as a single
+ string with its text-tool-call syntax leaking in, e.g. a stray
+ `<parameter name="hypothesis">` prefixing a JSON array. The leaked wrapper always sits
+ outside the array, so slice from the first `[` to the last `]` and parse only that —
+ this never mutates content inside the JSON. Non-string and unrecoverable values pass
+ through unchanged so pydantic raises its normal validation error instead of this
+ masking the problem; an empty or tag-only string has no array, so it stays invalid.
+ """
+ if not isinstance(value, str):
+ return value
+ start = value.find("[")
+ end = value.rfind("]")
+ if start != -1 and end > start:
+ try:
+ return json.loads(value[start : end + 1])
+ except (ValueError, TypeError):
+ pass
+ return value
class InvestigationHypothesis(BaseModel):
@@ -35,3 +59,8 @@ class InvestigationReport(BaseModel):
description="Suggested next actions for the on-call engineer or product owner.",
)
tool_calls_used: int = Field(default=0, description="Number of tool calls the agent made, for audit.")
+
+ @field_validator("hypotheses", "recommendations", mode="before")
+ @classmethod
+ def _recover_leaked_list(cls, value: Any) -> Any:
+ return _recover_stringified_list(value)
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py b/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py
index 7917e31ecfe0..8bc8db2a0448 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py
@@ -1,6 +1,8 @@
import pytest
from unittest.mock import MagicMock, patch
+from parameterized import parameterized
+
from posthog.temporal.ai.anomaly_investigation.runner import (
FINAL_REPORT_TOOL_NAME,
_build_callbacks,
@@ -37,6 +39,109 @@ def test_report_from_tool_calls_accepts_structured_final_report() -> None:
assert report.recommendations == ["Aggregate to daily buckets."]
+ [
+ # Sonnet 5 leaks its text-tool-call syntax and stringifies the whole list — the exact
+ # shape seen in production traces that collapsed to "Agent returned no final message".
+ (
+ "hypotheses_leaked_tag_string",
+ '\n<parameter name="hypothesis">[{"title": "Real step-change", "rationale": "Sustained climb.", "evidence": ["Rose 10 -> 60/hr"]}]',
+ ["Aggregate to daily buckets."],
+ ),
+ # Plain JSON array in a string, no leaked tag.
+ (
+ "hypotheses_plain_json_string",
+ '[{"title": "Bot spike", "rationale": "Traffic surge.", "evidence": []}]',
+ ["Filter bots."],
+ ),
+ ]
+)
+def test_report_from_tool_calls_recovers_stringified_hypotheses(
+ _name: str, hypotheses: str, recommendations: list[str]
+) -> None:
+ report = _report_from_tool_calls(
+ [
+ {
+ "name": FINAL_REPORT_TOOL_NAME,
+ "args": {
+ "verdict": "true_positive",
+ "summary": "A genuine sustained shift.",
+ "hypotheses": hypotheses,
+ "recommendations": recommendations,
+ },
+ }
+ ]
+ )
+
+ assert report is not None
+ assert report.hypotheses[0].title in ("Real step-change", "Bot spike")
+ assert report.recommendations == recommendations
+
+
+def test_report_from_tool_calls_recovers_stringified_recommendations() -> None:
+ report = _report_from_tool_calls(
+ [
+ {
+ "name": FINAL_REPORT_TOOL_NAME,
+ "args": {
+ "verdict": "inconclusive",
+ "summary": "Unclear.",
+ "hypotheses": [],
+ "recommendations": '<parameter name="recommendation">["Check the dashboard.", "Ask the owning team."]',
+ },
+ }
+ ]
+ )
+
+ assert report is not None
+ assert report.recommendations == ["Check the dashboard.", "Ask the owning team."]
+
+
+def test_report_from_tool_calls_preserves_markup_inside_recovered_content() -> None:
+ report = _report_from_tool_calls(
+ [
+ {
+ "name": FINAL_REPORT_TOOL_NAME,
+ "args": {
+ "verdict": "inconclusive",
+ "summary": "x",
+ "hypotheses": [],
+ "recommendations": '<parameter name="recommendation">["Audit the <parameter name=foo> leak in the logs."]',
+ },
+ }
+ ]
+ )
+
+ assert report is not None
+ assert report.recommendations == ["Audit the <parameter name=foo> leak in the logs."]
+
+
+ [
+ ("empty", ""),
+ ("whitespace", " "),
+ ("tag_only", '<parameter name="hypothesis">'),
+ ("prose_no_array", "the metric doubled overnight"),
+ ]
+)
+def test_report_from_tool_calls_rejects_unrecoverable_stringified_hypotheses(_name: str, hypotheses: str) -> None:
+ report = _report_from_tool_calls(
+ [
+ {
+ "name": FINAL_REPORT_TOOL_NAME,
+ "args": {
+ "verdict": "true_positive",
+ "summary": "x",
+ "hypotheses": hypotheses,
+ "recommendations": [],
+ },
+ }
+ ]
+ )
+
+ assert report is None
+
+
def test_report_from_tool_calls_ignores_invalid_structured_final_report() -> None:
report = _report_from_tool_calls(
[