: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): recover mangled investigation reports instead of dropping them (#74110)
Andrew Maguirebb5c99ac3363
diff --git a/posthog/tasks/alerts/investigation_notifications.py b/posthog/tasks/alerts/investigation_notifications.pyindex f0ebc2bfdaf1..da19d1b6ddd5 100644--- a/posthog/tasks/alerts/investigation_notifications.py+++ b/posthog/tasks/alerts/investigation_notifications.py@@ -40,10 +40,10 @@ 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`-# (30 min) × `ANOMALY_INVESTIGATION_ACTIVITY_MAX_ATTEMPTS` (2) = 60 min — plus slack, so a+# (40 min) × `ANOMALY_INVESTIGATION_ACTIVITY_MAX_ATTEMPTS` (2) = 80 min — plus slack, so a# healthy long investigation on its second attempt isn't preempted by a duplicate# force-dispatch that would fire a notification the verdict gate was meant to hold.-INVESTIGATION_RUNNING_GRACE_MINUTES = 70+INVESTIGATION_RUNNING_GRACE_MINUTES = 90def run_investigation_notification_safety_net() -> int:diff --git a/posthog/temporal/ai/anomaly_investigation/report.py b/posthog/temporal/ai/anomaly_investigation/report.pyindex be1ef24b0fc1..e0abe8bb7d48 100644--- a/posthog/temporal/ai/anomaly_investigation/report.py+++ b/posthog/temporal/ai/anomaly_investigation/report.py@@ -1,30 +1,132 @@+import reimport jsonfrom typing import Any, Literal-from pydantic import BaseModel, Field, field_validator+from pydantic import BaseModel, Field, ValidationError, model_validator+_LEADING_PARAMETER_TAG_RE = re.compile(r'^\s*<parameter\s+name="([^"]*)">\s*')-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.+def _close_truncated_json(fragment: str) -> str | None:+ """Append the closing brackets a truncated JSON array/object fragment is missing.++ Sonnet 5 sometimes stops emitting a leaked-string list argument before closing the+ outer array, so `[{...}` arrives with no final `]`. Scanning bracket nesting (string+ literals excluded) tells us exactly which closers to append. Fragments cut off inside+ a string literal are not repairable this way, and balanced fragments need no repair;+ both return None so the caller falls through to its next strategy.+ """+ closers: list[str] = []+ in_string = False+ escaped = False+ for ch in fragment:+ if in_string:+ if escaped:+ escaped = False+ elif ch == "\\":+ escaped = True+ elif ch == '"':+ in_string = False+ elif ch == '"':+ in_string = True+ elif ch == "[":+ closers.append("]")+ elif ch == "{":+ closers.append("}")+ elif ch in "]}":+ if not closers or closers[-1] != ch:+ return None+ closers.pop()+ if in_string or not closers:+ return None+ return fragment.rstrip().rstrip(",") + "".join(reversed(closers))+++def _parse_leaked_value(field: str, value: str) -> tuple[str | None, Any]:+ """Parse a list argument the model emitted as a string.++ Returns (leaked_tag_name, parsed). Sonnet 5's text-tool-call syntax leaks in several+ shapes seen in production: a stray `<parameter name="...">` tag prefixing the JSON+ array, sibling parameters concatenated after the array into the same string value+ (`[...], "recommendations": [...]`), and arrays cut off before their closing bracket.+ The leaked tag name matters to the caller: a tag that names a different field (e.g.+ `evidence` inside `hypotheses`) means the content belongs elsewhere."""- if not isinstance(value, str):- return value- start = value.find("[")- end = value.rfind("]")- if start != -1 and end > start:+ tag: str | None = None+ body = value+ match = _LEADING_PARAMETER_TAG_RE.match(value)+ if match:+ tag = match.group(1)+ body = value[match.end() :]+ start = body.find("[")+ if start == -1:+ return tag, None+ fragment = body[start:].strip()+ # Concatenated sibling parameters become valid JSON once wrapped in an object keyed+ # by this field. A plain well-formed array also parses through this path; unwrap it+ # back to the bare list so the caller's leaked-tag handling still applies.+ try:+ wrapped = json.loads(f'{{"{field}": {fragment}}}')+ if set(wrapped) == {field}:+ return tag, wrapped[field]+ return tag, wrapped+ except ValueError:+ pass+ end = fragment.rfind("]")+ if end != -1:+ try:+ return tag, json.loads(fragment[: end + 1])+ except ValueError:+ pass+ repaired = _close_truncated_json(fragment)+ if repaired is not None:try:- return json.loads(value[start : end + 1])- except (ValueError, TypeError):+ return tag, json.loads(repaired)+ except ValueError:pass- return value+ return tag, None+++def _normalize_report_args(data: dict[str, Any]) -> dict[str, Any]:+ """Undo the argument manglings Sonnet 5 produces when submitting the report.++ Handles the shapes observed in production traces: list fields serialized as strings+ (with or without leaked `<parameter>` tags, truncation, or concatenated siblings),+ and a single hypothesis flattened into top-level `title`/`rationale`/`evidence` keys.+ Unrecoverable values pass through unchanged so pydantic raises its normal validation+ error instead of this masking the problem.+ """+ data = dict(data)+ stray_evidence: list[Any] | None = None+ for field in ("hypotheses", "recommendations"):+ value = data.get(field)+ if not isinstance(value, str):+ continue+ tag, parsed = _parse_leaked_value(field, value)+ if isinstance(parsed, dict):+ for key, item in parsed.items():+ if key == field or key not in data:+ data[key] = item+ elif isinstance(parsed, list):+ if field == "hypotheses" and tag == "evidence":+ # The string was one hypothesis's evidence array; its title/rationale sit+ # flattened at the top level and are re-attached below.+ stray_evidence = parsed+ del data[field]+ else:+ data[field] = parsed+ hypotheses = data.get("hypotheses")+ hypotheses_usable = isinstance(hypotheses, list) and any(isinstance(item, dict) for item in hypotheses)+ if not hypotheses_usable and ("title" in data or "rationale" in data):+ hypothesis: dict[str, Any] = {+ "title": str(data.get("title") or "Hypothesis"),+ "rationale": str(data.get("rationale") or ""),+ }+ evidence = stray_evidence if stray_evidence is not None else data.get("evidence")+ if isinstance(evidence, list):+ hypothesis["evidence"] = [str(item) for item in evidence]+ data["hypotheses"] = [hypothesis]+ return dataclass InvestigationHypothesis(BaseModel):@@ -60,7 +162,42 @@ class InvestigationReport(BaseModel):)tool_calls_used: int = Field(default=0, description="Number of tool calls the agent made, for audit.")- @field_validator("hypotheses", "recommendations", mode="before")+ @model_validator(mode="before")@classmethod- def _recover_leaked_list(cls, value: Any) -> Any:- return _recover_stringified_list(value)+ def _recover_mangled_args(cls, data: Any) -> Any:+ if not isinstance(data, dict):+ return data+ return _normalize_report_args(data)+++def salvage_report(args: Any) -> InvestigationReport | None:+ """Build a report from whichever fields survive validation.++ Last resort when the model's final report call fails full validation even after+ recovery. Verdict and summary are the load-bearing fields (the verdict gates+ notification dispatch and the summary is what users read in the alert), so keeping+ them with degraded hypotheses beats collapsing the whole run to a generic+ inconclusive fallback. Returns None when verdict or summary themselves are invalid.+ """+ if not isinstance(args, dict):+ return None+ data = _normalize_report_args(args)+ try:+ report = InvestigationReport.model_validate({"verdict": data.get("verdict"), "summary": data.get("summary")})+ except ValidationError:+ return None+ if not report.summary.strip():+ # A verdict with no explanation must not gate notification dispatch; the+ # inconclusive fallback is safer than an unexplained suppression.+ return None+ hypotheses = data.get("hypotheses")+ if isinstance(hypotheses, list):+ for item in hypotheses:+ try:+ report.hypotheses.append(InvestigationHypothesis.model_validate(item))+ except ValidationError:+ continue+ recommendations = data.get("recommendations")+ if isinstance(recommendations, list):+ report.recommendations = [item for item in recommendations if isinstance(item, str)]+ return reportdiff --git a/posthog/temporal/ai/anomaly_investigation/runner.py b/posthog/temporal/ai/anomaly_investigation/runner.pyindex dfe28b38d398..a20c56e7da01 100644--- a/posthog/temporal/ai/anomaly_investigation/runner.py+++ b/posthog/temporal/ai/anomaly_investigation/runner.py@@ -27,7 +27,7 @@ from pydantic import BaseModel, ValidationErrorfrom posthog.models import Team, Userfrom posthog.temporal.ai.anomaly_investigation.prompts import SYSTEM_PROMPT-from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport+from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport, salvage_reportfrom posthog.temporal.ai.anomaly_investigation.tools import (FetchMetricSeriesArgs,InvestigationToolkit,@@ -186,6 +186,10 @@ async def run_investigation(]tool_calls_used = 0+ # Every set of submit_investigation_report args seen, valid or not, oldest first.+ # When every parse path fails, salvage tries these newest-to-oldest so a corrective+ # retry that came back worse cannot clobber an earlier salvageable attempt.+ report_args_history: list[dict[str, Any]] = []for _ in range(MAX_TOOL_CALLS + 1):if heartbeat is not None:@@ -198,27 +202,64 @@ async def run_investigation(HumanMessage(content=("Tool call budget exhausted. Submit the final InvestigationReport "- "now using whatever evidence you have."+ "now using whatever evidence you have. Pass hypotheses as a JSON "+ "array of objects (title, rationale, evidence) and recommendations "+ "as a JSON array of strings, never as serialized strings.")))- if heartbeat is not None:- heartbeat()- try:- final = await llm_with_final_report.ainvoke(messages, config=config)- except Exception as err:- # Swallow final-turn failures and return an inconclusive report rather than- # bouncing off Temporal retries — MaxChatAnthropic already exhausted its- # built-in retry budget, so another activity attempt is unlikely to help.- logger.warning("anomaly_investigation.llm_finalize_error", extra={"error": str(err)})- return InvestigationRunResult(- report=_fallback_report(f"LLM finalize call failed: {err}"),- tool_calls_used=tool_calls_used,- model=AGENT_MODEL,- )- messages.append(final)- forced_report = _parse_report_message(final)- if forced_report is not None:+ # Production traces show this finalize turn is where Sonnet 5 mangles the+ # report args (leaked text-tool-call syntax, flattened hypothesis fields), so+ # give the model one corrective retry with the validation error before+ # falling back to salvage.+ for finalize_attempt in range(2):+ if heartbeat is not None:+ heartbeat()+ try:+ final = await llm_with_final_report.ainvoke(messages, config=config)+ except Exception as err:+ # Swallow final-turn failures and return the best report we can rather+ # than bouncing off Temporal retries — MaxChatAnthropic already exhausted+ # its built-in retry budget, so another activity attempt is unlikely to help.+ logger.warning("anomaly_investigation.llm_finalize_error", extra={"error": str(err)})+ salvaged = _salvage_from_history(report_args_history) or _fallback_report(+ f"LLM finalize call failed: {err}"+ )+ salvaged.tool_calls_used = tool_calls_used+ return InvestigationRunResult(report=salvaged, tool_calls_used=tool_calls_used, model=AGENT_MODEL)+ messages.append(final)+ final_tool_calls = getattr(final, "tool_calls", None) or []+ report_args = _final_report_args(final_tool_calls)+ if report_args is None:+ # Plain-text final answer; the text-JSON fallback below handles it.+ break+ report_args_history.append(report_args)+ try:+ forced_report = InvestigationReport.model_validate(report_args)+ except ValidationError as err:+ error_summary = _validation_error_summary(err)+ logger.warning(+ "anomaly_investigation.report_validation_error",+ extra={"error": error_summary, "finalize_attempt": finalize_attempt},+ )+ if finalize_attempt == 0:+ # Answer every pending tool_use block or the retry request is+ # rejected by the API for dangling tool calls.+ for call in final_tool_calls:+ messages.append(+ ToolMessage(+ content=(+ f"Report rejected: {error_summary}. Call "+ f"{FINAL_REPORT_TOOL_NAME} again with corrected "+ "arguments: hypotheses must be a JSON array of "+ "objects with title, rationale and evidence keys; "+ "recommendations must be a JSON array of strings."+ ),+ tool_call_id=call.get("id") or call.get("tool_call_id") or "",+ )+ )+ continue+ breakforced_report.tool_calls_used = tool_calls_usedreturn InvestigationRunResult(report=forced_report, tool_calls_used=tool_calls_used, model=AGENT_MODEL)break@@ -235,10 +276,19 @@ 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)+ report_error: str | None = None+ report_args = _final_report_args(tool_calls)+ if report_args is not None:+ report_args_history.append(report_args)+ try:+ structured_report = InvestigationReport.model_validate(report_args)+ structured_report.tool_calls_used = tool_calls_used+ return InvestigationRunResult(+ report=structured_report, tool_calls_used=tool_calls_used, model=AGENT_MODEL+ )+ except ValidationError as err:+ report_error = _validation_error_summary(err)+ logger.warning("anomaly_investigation.report_validation_error", extra={"error": report_error})if not tool_calls:break@@ -249,7 +299,11 @@ async def run_investigation(# Enforce the cap per-call, not just per-turn — a single assistant# response can emit several parallel tool_use blocks.if name == FINAL_REPORT_TOOL_NAME:- content = "Final report tool call was invalid. Submit it again with all required fields."+ content = (+ f"Final report tool call was invalid ({report_error or 'missing required fields'}). "+ "Submit it again: hypotheses must be a JSON array of objects with title, "+ "rationale and evidence keys; recommendations must be a JSON array of strings."+ )elif tool_calls_used >= MAX_TOOL_CALLS:content = "[skipped — tool call budget exhausted]"else:@@ -271,7 +325,26 @@ async def run_investigation(messages.append(ToolMessage(content=content, tool_call_id=tool_call_id))final_message = messages[-1]- report = _parse_report(getattr(final_message, "content", ""))+ content = getattr(final_message, "content", "")+ report: InvestigationReport | None = _parse_report_text(content)+ if report is None:+ report = _salvage_from_history(report_args_history)+ if report is not None:+ logger.warning(+ "anomaly_investigation.report_salvaged",+ extra={"hypotheses_kept": len(report.hypotheses), "recommendations_kept": len(report.recommendations)},+ )+ if report is None:+ text = _stringify(content).strip()+ # Log only length, not content: the agent's final message can echo customer event+ # data, which must not land in centralized worker logs. The full output stays+ # available in the run's LLM analytics trace.+ logger.warning("anomaly_investigation.no_parsable_report", extra={"content_length": len(text)})+ report = _fallback_report(+ "Agent returned no final message."+ if not text+ else "Agent final message was not valid InvestigationReport JSON."+ )report.tool_calls_used = tool_calls_usedreturn InvestigationRunResult(report=report, tool_calls_used=tool_calls_used, model=AGENT_MODEL)@@ -298,25 +371,37 @@ def _build_callbacks(*, team: Team, alert: AlertConfiguration | None) -> list[Bareturn callbacks-def _parse_report_message(message: Any) -> InvestigationReport | None:- return _report_from_tool_calls(getattr(message, "tool_calls", None) or [])+def _final_report_args(tool_calls: list[dict[str, Any]]) -> dict[str, Any] | None:+ for call in tool_calls:+ if call.get("name") == FINAL_REPORT_TOOL_NAME:+ return call.get("args") or {}+ return None-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+def _salvage_from_history(report_args_history: list[dict[str, Any]]) -> InvestigationReport | None:+ for args in reversed(report_args_history):+ report = salvage_report(args)+ if report is not None:+ return reportreturn None-def _parse_report(content: Any) -> InvestigationReport:+def _report_from_tool_calls(tool_calls: list[dict[str, Any]]) -> InvestigationReport | None:+ args = _final_report_args(tool_calls)+ if args is None:+ return None+ try:+ return InvestigationReport.model_validate(args)+ except ValidationError:+ return None+++def _validation_error_summary(err: ValidationError) -> str:+ return "; ".join(f"{'.'.join(str(loc) for loc in detail['loc'])}: {detail['msg']}" for detail in err.errors()[:5])+++def _parse_report_text(content: Any) -> InvestigationReport | None:text = _stringify(content).strip()- if not text:- return _fallback_report("Agent returned no final message.")# Try direct JSON; else find first/last brace.for candidate in _json_candidates(text):try:@@ -324,6 +409,16 @@ def _parse_report(content: Any) -> InvestigationReport:return InvestigationReport.model_validate(parsed)except (ValueError, TypeError, ValidationError):continue+ return None+++def _parse_report(content: Any) -> InvestigationReport:+ report = _parse_report_text(content)+ if report is not None:+ return report+ text = _stringify(content).strip()+ if not text:+ return _fallback_report("Agent returned no final message.")return _fallback_report("Agent final message was not valid InvestigationReport JSON.")diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.pyindex a6315dff93d9..c764a0efc52a 100644--- a/posthog/temporal/ai/anomaly_investigation/workflow.py+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py@@ -49,12 +49,14 @@ SIGNAL_SOURCE_PRODUCT = "analytics"SIGNAL_SOURCE_TYPE = "anomaly_investigation"-# Sized to cover a realistic worst-case sequential agent run: up to MAX_TOOL_CALLS + 1 LLM turns,-# each capped at the runner's per-request timeout (thinking turns run long). 20 min got tight once-# that per-request timeout rose to 180s, so a slow thinking-heavy run could blow the deadline and be-# killed mid-flight — skipping the runner's fallback path and re-running the whole agent. 30 min-# keeps a realistic run inside a single activity attempt; the pathological tail falls to the retry.-ANOMALY_INVESTIGATION_ACTIVITY_START_TO_CLOSE = 30 * 60 # 30 minutes+# Sized to cover a realistic worst-case sequential agent run: up to MAX_TOOL_CALLS + 2 LLM turns+# (tool loop, finalize, and one corrective finalize retry), each capped at the runner's per-request+# timeout (thinking turns run long). 20 min got tight once that per-request timeout rose to 180s,+# so a slow thinking-heavy run could blow the deadline and be killed mid-flight — skipping the+# runner's fallback path and re-running the whole agent; the finalize retry pushed the 12-request+# worst case to 36 min, past the previous 30. 40 min keeps a realistic run inside a single activity+# attempt; the pathological tail falls to the retry.+ANOMALY_INVESTIGATION_ACTIVITY_START_TO_CLOSE = 40 * 60 # 40 minutesANOMALY_INVESTIGATION_ACTIVITY_HEARTBEAT_TIMEOUT = 5 * 60 # 5 minutesANOMALY_INVESTIGATION_ACTIVITY_MAX_ATTEMPTS = 2diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py b/posthog/temporal/tests/ai/test_anomaly_investigation_runner.pyindex 8bc8db2a0448..1feb576cf5ba 100644--- a/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py@@ -1,13 +1,17 @@import pytestfrom unittest.mock import MagicMock, patch+from langchain_core.messages import AIMessagefrom parameterized import parameterized+from posthog.temporal.ai.anomaly_investigation.report import salvage_reportfrom posthog.temporal.ai.anomaly_investigation.runner import (FINAL_REPORT_TOOL_NAME,+ MAX_TOOL_CALLS,_build_callbacks,_parse_report,_report_from_tool_calls,+ run_investigation,)@@ -142,6 +146,90 @@ def test_report_from_tool_calls_rejects_unrecoverable_stringified_hypotheses(_naassert report is None+ [+ # Hypothesis fields flattened to the top level, with the evidence array leaked as+ # a tagged string under `hypotheses` (trace shape from 2026-07-27).+ (+ "flattened_hypothesis_with_leaked_evidence_tag",+ {+ "verdict": "true_positive",+ "summary": "s",+ "title": "Single account driving skips",+ "rationale": "One tenant loops on the cap check.",+ "hypotheses": '\n<parameter name="evidence">["88% of events from one distinct_id."]',+ },+ [("Single account driving skips", ["88% of events from one distinct_id."])],+ [],+ ),+ # The recommendations parameter concatenated into the hypotheses string value.+ (+ "sibling_recommendations_concatenated_into_hypotheses_string",+ {+ "verdict": "true_positive",+ "summary": "s",+ "hypotheses": '[{"title": "Bulk sync", "rationale": "Batch job.", "evidence": ["0 -> 54 in one bucket."]}], "recommendations": ["Check the connector."]',+ },+ [("Bulk sync", ["0 -> 54 in one bucket."])],+ ["Check the connector."],+ ),+ # Leaked tag plus an array cut off before its closing bracket.+ (+ "truncated_hypotheses_array_missing_closing_bracket",+ {+ "verdict": "true_positive",+ "summary": "s",+ "hypotheses": '\n<parameter name="hypotheses">[{"title": "Batch eval run", "rationale": "Tight burst.", "evidence": ["7x hourly baseline."]}',+ "recommendations": ["Confirm the eval job."],+ },+ [("Batch eval run", ["7x hourly baseline."])],+ ["Confirm the eval job."],+ ),+ ]+)+def test_report_from_tool_calls_recovers_production_manglings(+ _name: str,+ args: dict,+ expected_hypotheses: list[tuple[str, list[str]]],+ expected_recommendations: list[str],+) -> None:+ report = _report_from_tool_calls([{"name": FINAL_REPORT_TOOL_NAME, "args": args}])++ assert report is not None+ assert report.verdict == "true_positive"+ assert [(hypothesis.title, hypothesis.evidence) for hypothesis in report.hypotheses] == expected_hypotheses+ assert report.recommendations == expected_recommendations+++def test_salvage_report_keeps_verdict_and_summary_when_hypotheses_unrecoverable() -> None:+ report = salvage_report(+ {+ "verdict": "true_positive",+ "summary": "One tenant drove the spike.",+ "hypotheses": "prose with no recoverable array",+ "recommendations": ["Check the tenant."],+ }+ )++ assert report is not None+ assert report.verdict == "true_positive"+ assert report.summary == "One tenant drove the spike."+ assert report.hypotheses == []+ assert report.recommendations == ["Check the tenant."]+++ [+ ("invalid_verdict", {"verdict": "maybe", "summary": "x"}),+ # A blank summary must not gate notifications: a salvaged false_positive with no+ # explanation would silently suppress the alert.+ ("blank_summary", {"verdict": "false_positive", "summary": " ", "hypotheses": "prose"}),+ ]+)+def test_salvage_report_rejects_untrustworthy_args(_name: str, args: dict) -> None:+ assert salvage_report(args) is None++def test_report_from_tool_calls_ignores_invalid_structured_final_report() -> None:report = _report_from_tool_calls([@@ -212,3 +300,83 @@ def test_build_callbacks_skips_when_default_client_missing() -> None:callbacks = _build_callbacks(team=team, alert=None)assert callbacks == []+++class _ScriptedRunnable:+ def __init__(self, responses: list) -> None:+ self._responses = list(responses)++ async def ainvoke(self, messages, config=None):+ return self._responses.pop(0)+++def _budget_burning_turn() -> AIMessage:+ return AIMessage(+ content="",+ tool_calls=[{"name": "noop_tool", "args": {}, "id": f"call-{i}"} for i in range(MAX_TOOL_CALLS)],+ )+++def _report_turn(args: dict) -> AIMessage:+ return AIMessage(content="", tool_calls=[{"name": FINAL_REPORT_TOOL_NAME, "args": args, "id": "report-1"}])+++_UNRECOVERABLE_REPORT_ARGS = {+ "verdict": "true_positive",+ "summary": "One tenant drove the spike.",+ "hypotheses": "prose with no recoverable array",+ "recommendations": ["Check the tenant."],+}+_VALID_REPORT_ARGS = {+ "verdict": "true_positive",+ "summary": "One tenant drove the spike.",+ "hypotheses": [{"title": "Runaway tenant", "rationale": "Loops on the cap check.", "evidence": []}],+ "recommendations": ["Check the tenant."],+}+++ "finalize_responses,expected_hypothesis_count",+ [+ pytest.param(+ [_report_turn(_UNRECOVERABLE_REPORT_ARGS), _report_turn(_VALID_REPORT_ARGS)],+ 1,+ id="retry_recovers_full_report",+ ),+ pytest.param(+ [_report_turn(_UNRECOVERABLE_REPORT_ARGS), _report_turn(_UNRECOVERABLE_REPORT_ARGS)],+ 0,+ id="salvage_after_failed_retry",+ ),+ pytest.param(+ [_report_turn(_UNRECOVERABLE_REPORT_ARGS), _report_turn({"verdict": "maybe", "summary": "x"})],+ 0,+ id="salvage_first_attempt_when_retry_comes_back_worse",+ ),+ ],+)+async def test_finalize_turn_retries_then_salvages_invalid_report(+ finalize_responses: list, expected_hypothesis_count: int+) -> None:+ llm = MagicMock()+ llm.bind_tools.side_effect = lambda tools: (+ _ScriptedRunnable([_budget_burning_turn()]) if len(tools) > 1 else _ScriptedRunnable(finalize_responses)+ )++ with (+ patch("ee.hogai.llm.MaxChatAnthropic", return_value=llm),+ patch("posthog.temporal.ai.anomaly_investigation.runner.posthoganalytics") as mock_module,+ ):+ mock_module.default_client = None+ result = await run_investigation(+ team=MagicMock(id=1),+ user=MagicMock(id=2),+ anomaly_context="anomaly context",+ alert=None,+ )++ assert result.tool_calls_used == MAX_TOOL_CALLS+ assert result.report.verdict == "true_positive"+ assert result.report.summary == "One tenant drove the spike."+ assert len(result.report.hypotheses) == expected_hypothesis_count+ assert result.report.recommendations == ["Check the tenant."]