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.

refactor(alerts): reduce investigation loop complexity (#100093)

Paul D'Ambraa9b914797f90
diff --git a/posthog/temporal/ai/anomaly_investigation/runner.py b/posthog/temporal/ai/anomaly_investigation/runner.py
index ce906c5cf47c..f958b1b35d3a 100644
--- a/posthog/temporal/ai/anomaly_investigation/runner.py
+++ b/posthog/temporal/ai/anomaly_investigation/runner.py
@@ -64,6 +64,247 @@ class InvestigationRunResult:
model: str
+def _result(report: InvestigationReport, tool_calls_used: int) -> InvestigationRunResult:
+ report.tool_calls_used = tool_calls_used
+ return InvestigationRunResult(report=report, tool_calls_used=tool_calls_used, model=AGENT_MODEL)
+
+
+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 _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 _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 report
+ return None
+
+
+def _add_report_correction_messages(messages: list[Any], tool_calls: list[dict[str, Any]], error_summary: str) -> None:
+ for call in tool_calls:
+ messages.append(
+ ToolMessage(
+ content=(
+ f"Report rejected: {error_summary}. Call {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 "",
+ )
+ )
+
+
+def _fallback_report(reason: str) -> InvestigationReport:
+ return InvestigationReport(
+ verdict="inconclusive",
+ summary=reason,
+ hypotheses=[],
+ recommendations=["Review the insight manually — the agent could not produce a structured report."],
+ )
+
+
+class _InvestigationRunner:
+ """Owns the mutable state for one investigation loop: messages, tool budget, and report history."""
+
+ def __init__(
+ self,
+ *,
+ llm_with_tools: Any,
+ llm_with_final_report: Any,
+ handlers: dict[str, ToolHandler],
+ config: RunnableConfig,
+ heartbeat: Callable[[], None] | None,
+ ) -> None:
+ self._llm_with_tools = llm_with_tools
+ self._llm_with_final_report = llm_with_final_report
+ self._handlers = handlers
+ self._config = config
+ self._heartbeat = heartbeat
+ # Per-run state lives on run(), the only place this class is driven from, so there is
+ # one place to reset it rather than two copies that can drift out of sync.
+ self.messages: list[Any]
+ self.tool_calls_used: int
+ # 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.
+ self.report_args_history: list[dict[str, Any]]
+
+ def _tick_heartbeat(self) -> None:
+ if self._heartbeat is not None:
+ self._heartbeat()
+
+ async def run(self, *, anomaly_context: Any) -> InvestigationRunResult:
+ self.messages = [
+ SystemMessage(content=SYSTEM_PROMPT),
+ HumanMessage(content=anomaly_context),
+ ]
+ self.tool_calls_used = 0
+ self.report_args_history = []
+ for _ in range(MAX_TOOL_CALLS + 1):
+ self._tick_heartbeat()
+
+ if self.tool_calls_used >= MAX_TOOL_CALLS:
+ result = await self._finalize_after_tool_budget()
+ if result is not None:
+ return result
+ break
+
+ try:
+ response = await self._llm_with_tools.ainvoke(self.messages, config=self._config)
+ except Exception as err:
+ logger.warning("anomaly_investigation.llm_invoke_error", extra={"error": str(err)})
+ report = _salvage_from_history(self.report_args_history) or _fallback_report(
+ f"LLM tool-calling loop failed: {err}"
+ )
+ return _result(report, self.tool_calls_used)
+ self.messages.append(response)
+
+ tool_calls = getattr(response, "tool_calls", None) or []
+ if not tool_calls:
+ break
+ result = await self._handle_tool_calls(tool_calls)
+ if result is not None:
+ return result
+
+ return self._finish_investigation()
+
+ async def _finalize_after_tool_budget(self) -> InvestigationRunResult | None:
+ # Budget exhausted — no tool_use block in flight so we can send a plain
+ # HumanMessage rather than stubbing pending tool_result pairs.
+ self.messages.append(
+ HumanMessage(
+ content=(
+ "Tool call budget exhausted. Submit the final InvestigationReport "
+ "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."
+ )
+ )
+ )
+ # 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):
+ self._tick_heartbeat()
+ try:
+ final = await self._llm_with_final_report.ainvoke(self.messages, config=self._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)})
+ report = _salvage_from_history(self.report_args_history) or _fallback_report(
+ f"LLM finalize call failed: {err}"
+ )
+ return _result(report, self.tool_calls_used)
+ self.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.
+ return None
+ self.report_args_history.append(report_args)
+ try:
+ return _result(InvestigationReport.model_validate(report_args), self.tool_calls_used)
+ 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.
+ _add_report_correction_messages(self.messages, final_tool_calls, error_summary)
+ continue
+ return None
+
+ async def _handle_tool_calls(self, tool_calls: list[dict[str, Any]]) -> InvestigationRunResult | None:
+ report_error: str | None = None
+ report_args = _final_report_args(tool_calls)
+ if report_args is not None:
+ self.report_args_history.append(report_args)
+ try:
+ return _result(InvestigationReport.model_validate(report_args), self.tool_calls_used)
+ except ValidationError as err:
+ report_error = _validation_error_summary(err)
+ logger.warning("anomaly_investigation.report_validation_error", extra={"error": report_error})
+ await self._run_tool_calls(tool_calls=tool_calls, report_error=report_error)
+ return None
+
+ async def _run_tool_calls(self, *, tool_calls: list[dict[str, Any]], report_error: str | None) -> None:
+ for call in tool_calls:
+ content = await self._run_tool_call(call=call, report_error=report_error)
+ # Guard against runaway tool responses pushing the conversation past
+ # the model's context window. Keep the first slice; if the
+ # agent needs more it can issue a narrower query.
+ if isinstance(content, str) and len(content) > MAX_TOOL_RESULT_CHARS:
+ content = content[:MAX_TOOL_RESULT_CHARS] + "\n[truncated — narrow the query for more]"
+ self.messages.append(
+ ToolMessage(content=content, tool_call_id=call.get("id") or call.get("tool_call_id") or "")
+ )
+
+ async def _run_tool_call(self, *, call: dict[str, Any], report_error: str | None) -> str:
+ name = call.get("name")
+ if name == FINAL_REPORT_TOOL_NAME:
+ return (
+ 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."
+ )
+ # Enforce the cap per-call, not just per-turn — a single assistant
+ # response can emit several parallel tool_use blocks.
+ if self.tool_calls_used >= MAX_TOOL_CALLS:
+ return "[skipped — tool call budget exhausted]"
+ self.tool_calls_used += 1
+ handler = self._handlers.get(name) if isinstance(name, str) else None
+ if handler is None:
+ return f"Unknown tool: {name}"
+ try:
+ result = await handler(call.get("args") or {})
+ if not isinstance(result, str) or not result.startswith("Error"):
+ self.report_args_history.clear()
+ return result
+ except Exception as err:
+ logger.warning("anomaly_investigation.tool_error", extra={"tool": name, "error": str(err)})
+ return f"Tool {name} failed: {err}"
+
+ def _finish_investigation(self) -> InvestigationRunResult:
+ content = getattr(self.messages[-1], "content", "")
+ report = _parse_report_text(content)
+ if report is None:
+ report = _salvage_from_history(self.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."
+ )
+ return _result(report, self.tool_calls_used)
+
+
async def run_investigation(
*,
team: Team,
@@ -170,7 +411,7 @@ async def run_investigation(
# choice, so forcing a specific tool returns a 400 and this finalize turn would fall through to
# the generic fallback report. Binding *only* the final-report tool, plus the explicit "submit
# now" nudge on the budget-exhausted turn, reliably elicits the call without forcing it; if the
- # model returns plain text instead, the text-JSON fallback in _parse_report still recovers it.
+ # model returns plain text instead, the text-JSON fallback in _parse_report_text still recovers it.
llm_with_final_report = llm.bind_tools([final_report_tool])
# Without a langchain CallbackHandler attached, MaxChatAnthropic's posthog_properties
@@ -180,179 +421,14 @@ async def run_investigation(
# Temporal-driven agents (see llma_eval_reports/report_agent/graph.py).
config: RunnableConfig = {"callbacks": _build_callbacks(team=team, alert=alert)}
- messages: list[Any] = [
- SystemMessage(content=SYSTEM_PROMPT),
- HumanMessage(content=anomaly_context),
- ]
-
- 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:
- heartbeat()
-
- if tool_calls_used >= MAX_TOOL_CALLS:
- # Budget exhausted — no tool_use block in flight so we can send a plain
- # HumanMessage rather than stubbing pending tool_result pairs.
- messages.append(
- HumanMessage(
- content=(
- "Tool call budget exhausted. Submit the final InvestigationReport "
- "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."
- )
- )
- )
- # 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
- break
- forced_report.tool_calls_used = tool_calls_used
- return InvestigationRunResult(report=forced_report, tool_calls_used=tool_calls_used, model=AGENT_MODEL)
- break
-
- try:
- response = await llm_with_tools.ainvoke(messages, config=config)
- except Exception as err:
- logger.warning("anomaly_investigation.llm_invoke_error", extra={"error": str(err)})
- recovered_report = _salvage_from_history(report_args_history) or _fallback_report(
- f"LLM tool-calling loop failed: {err}"
- )
- recovered_report.tool_calls_used = tool_calls_used
- return InvestigationRunResult(
- report=recovered_report,
- tool_calls_used=tool_calls_used,
- model=AGENT_MODEL,
- )
- messages.append(response)
-
- tool_calls = getattr(response, "tool_calls", None) or []
- 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
-
- for call in tool_calls:
- name = call.get("name")
- args = call.get("args") or {}
- 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 name == FINAL_REPORT_TOOL_NAME:
- 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:
- tool_calls_used += 1
- handler = handlers.get(name)
- if handler is None:
- content = f"Unknown tool: {name}"
- else:
- try:
- content = await handler(args)
- if not isinstance(content, str) or not content.startswith("Error"):
- report_args_history.clear()
- except Exception as err:
- logger.warning("anomaly_investigation.tool_error", extra={"tool": name, "error": str(err)})
- content = f"Tool {name} failed: {err}"
- # Guard against runaway tool responses pushing the conversation past
- # the model's context window. Keep the first slice; if the
- # agent needs more it can issue a narrower query.
- if isinstance(content, str) and len(content) > MAX_TOOL_RESULT_CHARS:
- content = content[:MAX_TOOL_RESULT_CHARS] + "\n[truncated — narrow the query for more]"
- messages.append(ToolMessage(content=content, tool_call_id=tool_call_id))
-
- final_message = messages[-1]
- 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_used
- return InvestigationRunResult(report=report, tool_calls_used=tool_calls_used, model=AGENT_MODEL)
+ runner = _InvestigationRunner(
+ llm_with_tools=llm_with_tools,
+ llm_with_final_report=llm_with_final_report,
+ handlers=handlers,
+ config=config,
+ heartbeat=heartbeat,
+ )
+ return await runner.run(anomaly_context=anomaly_context)
def _build_callbacks(*, team: Team, alert: AlertConfiguration | None) -> list[BaseCallbackHandler]:
@@ -377,21 +453,6 @@ def _build_callbacks(*, team: Team, alert: AlertConfiguration | None) -> list[Ba
return callbacks
-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 _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 report
- return None
-
-
def _report_from_tool_calls(tool_calls: list[dict[str, Any]]) -> InvestigationReport | None:
args = _final_report_args(tool_calls)
if args is None:
@@ -402,10 +463,6 @@ def _report_from_tool_calls(tool_calls: list[dict[str, Any]]) -> InvestigationRe
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()
# Try direct JSON; else find first/last brace.
@@ -449,12 +506,3 @@ def _stringify(content: Any) -> str:
chunks.append(item)
return "".join(chunks)
return str(content)
-
-
-def _fallback_report(reason: str) -> InvestigationReport:
- return InvestigationReport(
- verdict="inconclusive",
- summary=reason,
- hypotheses=[],
- recommendations=["Review the insight manually — the agent could not produce a structured report."],
- )