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(aio): retry eval-report queries and flag unavailable metrics (#72126)

posthog[bot]83dd5a210058
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 7c9b36c9b017..561359e762c8 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -5,6 +5,8 @@ from collections import defaultdict
from typing import TYPE_CHECKING, NamedTuple
from zoneinfo import ZoneInfo
+from django.db.models import Q
+
import temporalio.activity
from dateutil.rrule import rrulestr
from structlog import get_logger
@@ -179,13 +181,15 @@ def _count_triggered_pg_gate(
"""
from products.ai_observability.backend.models.evaluation_reports import EvaluationReportRun
- if report.last_delivered_at:
+ cooldown_anchor = report.last_attempted_at or report.last_delivered_at
+ if cooldown_anchor:
cooldown_delta = dt.timedelta(minutes=report.cooldown_minutes)
- if (now - report.last_delivered_at) < cooldown_delta:
+ if (now - cooldown_anchor) < cooldown_delta:
return "cooldown", None
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
today_runs = EvaluationReportRun.objects.filter(
+ Q(content__generation_status__isnull=True) | ~Q(content__generation_status="metrics_unavailable"),
report=report,
created_at__gte=today_start,
).count()
@@ -609,6 +613,7 @@ async def run_eval_report_agent_activity(
content=content.to_dict(),
period_start=inputs.period_start,
period_end=inputs.period_end,
+ generation_status=content.generation_status.value,
)
@@ -633,6 +638,7 @@ async def store_report_run_activity(
from posthog.models.event.util import create_event
from posthog.models.team import Team
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import ( # noqa: PLC0415 -- keeps report agent dependencies off the activity import path
+ EvalReportGenerationStatus,
EvalReportMetrics,
normalize_report_content_payload,
)
@@ -642,13 +648,14 @@ async def store_report_run_activity(
# Mirror content.metrics into the legacy `metadata` JSONField for consumers that still read it.
content = normalize_report_content_payload(inputs.content or {})
evaluation_target = resolve_evaluation_target(content.get("evaluation_target", GENERATION_TARGET))
- metrics = content.get("metrics", {}) or {}
- parsed_metrics = EvalReportMetrics.from_dict(metrics)
+ generation_status = EvalReportGenerationStatus(content["generation_status"])
+ metrics = content.get("metrics")
+ parsed_metrics = EvalReportMetrics.from_dict(metrics) if isinstance(metrics, dict) else None
run = EvaluationReportRun.objects.create(
report_id=inputs.report_id,
content=content,
- metadata=metrics,
+ metadata=metrics or {},
period_start=inputs.period_start,
period_end=inputs.period_end,
)
@@ -668,14 +675,8 @@ async def store_report_run_activity(
"$ai_report_title": content.get("title", ""),
"$ai_report_period_start": inputs.period_start,
"$ai_report_period_end": inputs.period_end,
- "$ai_report_output_type": parsed_metrics.output_type,
"$ai_report_evaluation_target": evaluation_target,
- "$ai_report_result_counts": parsed_metrics.result_counts,
- "$ai_report_result_rates": parsed_metrics.result_rates,
- "$ai_report_previous_result_counts": parsed_metrics.previous_result_counts,
- "$ai_report_previous_result_rates": parsed_metrics.previous_result_rates,
- "$ai_report_total_runs": parsed_metrics.total_runs,
- "$ai_report_previous_total_runs": parsed_metrics.previous_total_runs,
+ "$ai_report_generation_status": generation_status.value,
# Structured content + citations for downstream consumption
"$ai_report_content": content,
"$ai_report_citations": citations,
@@ -683,7 +684,19 @@ async def store_report_run_activity(
"$ai_report_referenced_trace_ids": all_referenced_trace_ids,
"$ai_report_section_count": len(content.get("sections", [])),
}
- if parsed_metrics.output_type == "boolean":
+ if parsed_metrics is not None:
+ properties.update(
+ {
+ "$ai_report_output_type": parsed_metrics.output_type,
+ "$ai_report_result_counts": parsed_metrics.result_counts,
+ "$ai_report_result_rates": parsed_metrics.result_rates,
+ "$ai_report_previous_result_counts": parsed_metrics.previous_result_counts,
+ "$ai_report_previous_result_rates": parsed_metrics.previous_result_rates,
+ "$ai_report_total_runs": parsed_metrics.total_runs,
+ "$ai_report_previous_total_runs": parsed_metrics.previous_total_runs,
+ }
+ )
+ if parsed_metrics is not None and parsed_metrics.output_type == "boolean":
# Preserve the original flat properties for existing boolean-report consumers.
properties.update(
{
@@ -733,27 +746,42 @@ async def deliver_report_activity(
await deliver()
-async def update_next_delivery_date_activity(
- inputs: UpdateNextDeliveryDateInput,
-) -> None:
- """Update the report's next_delivery_date and last_delivered_at.
+def _update_next_delivery_date(inputs: UpdateNextDeliveryDateInput) -> None:
+ """Persist automatic-run timing without creating gaps in the report data cursor.
- last_delivered_at is set to the report's period_end (captured at the start of
- this run) rather than the current wall-clock time. This guarantees that the
- next run's period_start picks up exactly where this run's period_end left off,
- so any time spent generating/delivering does not create a coverage gap.
+ `period_end` is captured when report context is prepared. It anchors both the
+ attempt and successful cursor so time spent generating and delivering cannot
+ leave uncovered data between consecutive reports.
+
+ `advance_data_cursor=None` preserves the behavior of activity inputs recorded
+ before attempt and delivery updates were split.
"""
+ from products.ai_observability.backend.models.evaluation_reports import ( # noqa: PLC0415 -- keeps product model loading inside activity execution
+ EvaluationReport,
+ )
- @database_sync_to_async(thread_sensitive=False)
- def update():
- import datetime as dt_mod
+ report = EvaluationReport.objects.get(id=inputs.report_id)
+ period_end = dt.datetime.fromisoformat(inputs.period_end)
+ advance_data_cursor = (
+ inputs.generation_status == "completed" if inputs.advance_data_cursor is None else inputs.advance_data_cursor
+ )
+ update_fields: list[str] = []
+ if inputs.record_attempt:
+ report.last_attempted_at = period_end
+ report.set_next_delivery_date()
+ update_fields.extend(["next_delivery_date", "last_attempted_at"])
+ if advance_data_cursor:
+ report.last_delivered_at = period_end
+ update_fields.append("last_delivered_at")
+ report.save(update_fields=update_fields)
- from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
- report = EvaluationReport.objects.get(id=inputs.report_id)
- report.last_delivered_at = dt_mod.datetime.fromisoformat(inputs.period_end)
- report.set_next_delivery_date()
- report.save(update_fields=["last_delivered_at", "next_delivery_date"])
+async def update_next_delivery_date_activity(
+ inputs: UpdateNextDeliveryDateInput,
+) -> None:
+ @database_sync_to_async(thread_sensitive=False)
+ def update() -> None:
+ _update_next_delivery_date(inputs)
await update()
diff --git a/posthog/temporal/ai_observability/eval_reports/delivery.py b/posthog/temporal/ai_observability/eval_reports/delivery.py
index cdde7dfdf0c7..e5980c1ce8a5 100644
--- a/posthog/temporal/ai_observability/eval_reports/delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/delivery.py
@@ -14,6 +14,7 @@ from markdown_it import MarkdownIt
from markdown_to_mrkdwn import SlackMarkdownConverter
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
+ METRICS_UNAVAILABLE_MESSAGE,
Citation,
EvalReportContent,
EvalReportMetrics,
@@ -185,12 +186,21 @@ def _format_boolean_pass_rate_value(metrics: EvalReportMetrics) -> str:
return f"{value} ({arrow} {abs(diff):.2f}pp vs previous)"
-def _render_metrics_block_html(metrics: EvalReportMetrics) -> str:
+def _render_metrics_block_html(
+ metrics: EvalReportMetrics | None,
+ *,
+ period_start: str = "",
+ period_end: str = "",
+) -> str:
"""Render trusted outcome counts and rates as an HTML table.
Lives at the top of the email body so the reader sees the trusted numbers
before reading the agent's analysis.
"""
+ if metrics is None:
+ period = f"{_format_period_for_display(period_start)} → {_format_period_for_display(period_end)}"
+ notice = _inline_email_styles(f"<p><strong>{METRICS_UNAVAILABLE_MESSAGE}</strong></p>")
+ return f'<p class="muted"><strong>Period</strong>: {period}</p>\n{notice}\n'
period = f"{_format_period_for_display(metrics.period_start)} → {_format_period_for_display(metrics.period_end)}"
outcome_labels = _OUTCOME_LABELS[metrics.output_type]
headers = "".join(f"<th>{label}</th>" for _, label in outcome_labels)
@@ -203,8 +213,10 @@ def _render_metrics_block_html(metrics: EvalReportMetrics) -> str:
return f'<p class="muted"><strong>Period</strong>: {period}</p>\n{table}\n'
-def _render_metrics_slack_blocks(metrics: EvalReportMetrics) -> list[dict]:
+def _render_metrics_slack_blocks(metrics: EvalReportMetrics | None) -> list[dict]:
"""Render the metrics block as a compact, output-type-neutral Slack dashboard."""
+ if metrics is None:
+ return [{"type": "section", "text": {"type": "mrkdwn", "text": METRICS_UNAVAILABLE_MESSAGE}}]
outcome_lines = [
f"{label}: {_format_outcome_value(metrics, outcome)}" for outcome, label in _OUTCOME_LABELS[metrics.output_type]
]
@@ -256,7 +268,7 @@ def deliver_email_report(
errors: list[str] = []
# Metrics block first, then each section
- body_parts = [_render_metrics_block_html(content.metrics)]
+ body_parts = [_render_metrics_block_html(content.metrics, period_start=period_start, period_end=period_end)]
for section in content.sections:
body_parts.append(_render_section_html(section.title, section.content, project_id, citation_map))
body_html = "\n".join(body_parts)
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
index 87f0410e82c8..9c24c9cd094b 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -18,6 +18,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
MIN_REPORT_SECTIONS,
EvalReportContent,
+ EvalReportGenerationStatus,
EvalReportMetrics,
ReportSection,
)
@@ -25,6 +26,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.state import Ev
from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
_ch_ts,
_fetch_period_summary,
+ _is_retriable_ch_error,
get_eval_report_tools,
)
from posthog.temporal.ai_observability.eval_reports.targets import GENERATION_TARGET
@@ -41,15 +43,13 @@ def _compute_metrics(
previous_period_start: str,
output_type: str = "boolean",
evaluation_target: str = GENERATION_TARGET,
-) -> EvalReportMetrics:
+) -> EvalReportMetrics | None:
"""Compute report metrics directly via HogQL (independent of agent state).
- Always returns a valid EvalReportMetrics — on query failure, returns one
- with zero counts and logs the exception. The agent cannot fabricate numbers
- because this function is the sole source of truth for `content.metrics`.
+ Returns None when a transient ClickHouse failure exhausts the query helper's
+ retries. Other exceptions propagate so deterministic application errors do
+ not become successful fallback reports.
"""
- empty = EvalReportMetrics(output_type=output_type, period_start=period_start, period_end=period_end)
-
try:
ts_start = _ch_ts(period_start)
ts_end = _ch_ts(period_end)
@@ -72,9 +72,24 @@ def _compute_metrics(
previous_total_runs=previous_total,
previous_result_counts=previous_result_counts,
)
- except Exception:
+ except Exception as error:
+ if not _is_retriable_ch_error(error):
+ raise
logger.exception("llma_eval_reports_metrics_computation_failed")
- return empty
+ return None
+
+
+def _metrics_unavailable_content(
+ evaluation_target: str = "generation",
+) -> EvalReportContent:
+ return EvalReportContent(
+ evaluation_target=evaluation_target,
+ title="Metrics unavailable for this period",
+ sections=[],
+ citations=[],
+ metrics=None,
+ generation_status=EvalReportGenerationStatus.METRICS_UNAVAILABLE,
+ )
def _fallback_content(
@@ -224,6 +239,20 @@ def run_eval_report_agent(
evaluation_target=evaluation_target,
)
+ from posthog.temporal.ai_observability.eval_reports.metrics import increment_errors, increment_report_generated
+
+ # The agent's query tools would fail under the same sustained ClickHouse load,
+ # which could produce a narrative built on missing data.
+ if metrics is None:
+ increment_report_generated("fallback_metrics_unavailable")
+ increment_errors("metrics_unavailable")
+ logger.warning(
+ "llma_eval_reports_metrics_unavailable",
+ team_id=team_id,
+ evaluation_id=evaluation_id,
+ )
+ return _metrics_unavailable_content(evaluation_target)
+
llm = build_langchain_chat_client(EVAL_REPORT_AGENT_MODEL, EVAL_REPORT_AGENT_TIMEOUT, ai_product="aio_eval_reports")
system_prompt = build_eval_report_system_prompt(
@@ -266,8 +295,6 @@ def run_eval_report_agent(
"trace_id_allowlist": [],
}
- from posthog.temporal.ai_observability.eval_reports.metrics import increment_errors, increment_report_generated
-
# Skip in gateway mode: the Go gateway captures $ai_generation itself, so the
# SDK callback would double-count. Same gate the model routing above reads.
callbacks: list[BaseCallbackHandler] = []
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
index 6251dddd187c..34a4dfed9d57 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
@@ -14,6 +14,7 @@ analysis rather than number formatting.
"""
from dataclasses import dataclass, field
+from enum import StrEnum
from typing import Literal, overload
from posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition
@@ -26,6 +27,17 @@ MAX_REPORT_SECTIONS = 6
MIN_REPORT_SECTIONS = 1
+class EvalReportGenerationStatus(StrEnum):
+ COMPLETED = "completed"
+ METRICS_UNAVAILABLE = "metrics_unavailable"
+
+
+METRICS_UNAVAILABLE_MESSAGE = (
+ "Metrics could not be calculated for this period because evaluation data was temporarily unavailable. "
+ "This does not mean that no evaluations ran."
+)
+
+
def normalize_result_counts(output_type: str, counts: dict[str, int] | None) -> dict[str, int]:
definition = get_outcome_definition(output_type)
source = counts or {}
@@ -278,7 +290,14 @@ def normalize_report_content_payload(data: dict) -> dict:
"""Upgrade a stored report at the read/write boundary without mutating it."""
normalized = dict(data)
metrics = data.get("metrics")
- if isinstance(metrics, dict):
+ try:
+ status = EvalReportGenerationStatus(data.get("generation_status", ""))
+ except ValueError:
+ status = EvalReportGenerationStatus.COMPLETED
+ normalized["generation_status"] = status.value
+ if status == EvalReportGenerationStatus.METRICS_UNAVAILABLE:
+ normalized["metrics"] = None
+ elif isinstance(metrics, dict):
normalized["metrics"] = normalize_metrics_payload(metrics)
return normalized
@@ -291,10 +310,13 @@ class EvalReportContent:
title: str = ""
sections: list[ReportSection] = field(default_factory=list)
citations: list[Citation] = field(default_factory=list)
- metrics: EvalReportMetrics = field(default_factory=EvalReportMetrics)
+ metrics: EvalReportMetrics | None = field(default_factory=EvalReportMetrics)
+ generation_status: EvalReportGenerationStatus = EvalReportGenerationStatus.COMPLETED
def __post_init__(self) -> None:
self.evaluation_target = resolve_evaluation_target(self.evaluation_target)
+ if self.generation_status == EvalReportGenerationStatus.METRICS_UNAVAILABLE:
+ self.metrics = None
def to_dict(self) -> dict:
return {
@@ -302,15 +324,24 @@ class EvalReportContent:
"title": self.title,
"sections": [s.to_dict() for s in self.sections],
"citations": [c.to_dict() for c in self.citations],
- "metrics": self.metrics.to_dict(),
+ "metrics": self.metrics.to_dict() if self.metrics is not None else None,
+ "generation_status": self.generation_status.value,
}
@staticmethod
def from_dict(data: dict) -> "EvalReportContent":
+ normalized = normalize_report_content_payload(data)
+ generation_status = EvalReportGenerationStatus(normalized["generation_status"])
+ metrics = normalized.get("metrics")
return EvalReportContent(
- evaluation_target=data.get("evaluation_target", GENERATION_TARGET),
- title=data.get("title", ""),
- sections=[ReportSection.from_dict(s) for s in data.get("sections", [])],
- citations=[Citation.from_dict(c) for c in data.get("citations", [])],
- metrics=EvalReportMetrics.from_dict(data.get("metrics", {})),
+ evaluation_target=normalized.get("evaluation_target", GENERATION_TARGET),
+ title=normalized.get("title", ""),
+ sections=[ReportSection.from_dict(s) for s in normalized.get("sections", [])],
+ citations=[Citation.from_dict(c) for c in normalized.get("citations", [])],
+ metrics=(
+ None
+ if generation_status == EvalReportGenerationStatus.METRICS_UNAVAILABLE
+ else EvalReportMetrics.from_dict(metrics if isinstance(metrics, dict) else {})
+ ),
+ generation_status=generation_status,
)
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
index 782541b1968a..63e0f3237ca8 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
@@ -6,6 +6,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.temporal.ai_observability.eval_reports.report_agent import graph
from posthog.temporal.ai_observability.eval_reports.report_agent.graph import (
_append_references_section,
@@ -85,9 +86,38 @@ class TestComputeMetrics(SimpleTestCase):
output_type="sentiment",
)
+ self.assertIsNotNone(metrics)
+ assert metrics is not None
self.assertEqual(metrics.result_rates, {"positive": 50.0, "neutral": 25.0, "negative": 25.0})
self.assertEqual(metrics.previous_result_rates, {"positive": 50.0, "neutral": 50.0, "negative": 0.0})
+ @patch.object(graph, "_fetch_period_summary")
+ def test_transient_query_failure_returns_no_metrics(self, mock_fetch):
+ mock_fetch.side_effect = ClickHouseAtCapacity()
+
+ metrics = graph._compute_metrics(
+ team_id=1,
+ evaluation_id="eval-id",
+ period_start="2026-04-08T14:00:00+00:00",
+ period_end="2026-04-08T15:00:00+00:00",
+ previous_period_start="2026-04-08T13:00:00+00:00",
+ )
+
+ self.assertIsNone(metrics)
+
+ @patch.object(graph, "_fetch_period_summary")
+ def test_non_transient_query_failure_propagates(self, mock_fetch):
+ mock_fetch.side_effect = ValueError("invalid query result")
+
+ with self.assertRaisesRegex(ValueError, "invalid query result"):
+ graph._compute_metrics(
+ team_id=1,
+ evaluation_id="eval-id",
+ period_start="2026-04-08T14:00:00+00:00",
+ period_end="2026-04-08T15:00:00+00:00",
+ previous_period_start="2026-04-08T13:00:00+00:00",
+ )
+
class TestFallbackContent(SimpleTestCase):
def test_zero_runs_produces_no_runs_message(self):
@@ -325,6 +355,45 @@ class TestRunEvalReportAgentRouting(SimpleTestCase):
self.assertIs(mock_create_agent.call_args.kwargs["model"], mock_build_llm.return_value)
+class TestRunEvalReportAgentMetricsUnavailable(SimpleTestCase):
+ @patch.object(graph, "posthoganalytics")
+ @patch.object(graph, "build_langchain_chat_client")
+ @patch.object(graph, "create_react_agent")
+ @patch.object(graph, "_compute_metrics")
+ def test_metrics_unavailable_skips_agent_and_returns_fallback(
+ self, mock_metrics, mock_create_agent, mock_build_llm, mock_pha
+ ):
+ mock_pha.default_client = None
+ mock_metrics.return_value = None
+
+ with (
+ patch("posthog.temporal.ai_observability.eval_reports.metrics.increment_errors") as mock_increment_errors,
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.metrics.increment_report_generated"
+ ) as mock_increment_generated,
+ ):
+ content = graph.run_eval_report_agent(
+ team_id=1,
+ evaluation_id="eval-1",
+ evaluation_name="Relevance",
+ evaluation_description="",
+ evaluation_prompt="",
+ evaluation_type="llm_judge",
+ period_start="2026-04-08T14:00:00+00:00",
+ period_end="2026-04-08T15:00:00+00:00",
+ previous_period_start="2026-04-08T13:00:00+00:00",
+ )
+
+ mock_create_agent.assert_not_called()
+ mock_build_llm.assert_not_called()
+ mock_increment_generated.assert_called_once_with("fallback_metrics_unavailable")
+ mock_increment_errors.assert_called_once_with("metrics_unavailable")
+ self.assertEqual(content.generation_status, graph.EvalReportGenerationStatus.METRICS_UNAVAILABLE)
+ self.assertEqual(content.title, "Metrics unavailable for this period")
+ self.assertIsNone(content.metrics)
+ self.assertEqual(content.sections, [])
+
+
class TestRunEvalReportAgentCallbackGating(SimpleTestCase):
"""The SDK CallbackHandler fires only when NOT routing through the gateway.
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py
index c2211aa672f0..309a26bab20f 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py
@@ -8,6 +8,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MIN_REPORT_SECTIONS,
Citation,
EvalReportContent,
+ EvalReportGenerationStatus,
EvalReportMetrics,
ReportSection,
)
@@ -214,6 +215,8 @@ class TestEvalReportContent(SimpleTestCase):
self.assertEqual(len(c.sections), 2)
self.assertEqual(c.sections[1].content, "C2")
self.assertEqual(c.citations[0].reason, "r")
+ self.assertIsNotNone(c.metrics)
+ assert c.metrics is not None
self.assertEqual(c.metrics.total_runs, 10)
def test_roundtrip(self):
@@ -232,6 +235,25 @@ class TestEvalReportContent(SimpleTestCase):
self.assertEqual(roundtripped.metrics, original.metrics)
self.assertEqual(roundtripped.evaluation_target, "trace")
+ def test_metrics_unavailable_roundtrip_has_no_placeholder_metrics(self):
+ original = EvalReportContent(
+ generation_status=EvalReportGenerationStatus.METRICS_UNAVAILABLE,
+ metrics=None,
+ )
+
+ roundtripped = EvalReportContent.from_dict(original.to_dict())
+
+ self.assertEqual(roundtripped.generation_status, EvalReportGenerationStatus.METRICS_UNAVAILABLE)
+ self.assertIsNone(roundtripped.metrics)
+
+ def test_historical_content_defaults_to_completed(self):
+ content = EvalReportContent.from_dict({"metrics": {"total_runs": 5}})
+
+ self.assertEqual(content.generation_status, EvalReportGenerationStatus.COMPLETED)
+ self.assertIsNotNone(content.metrics)
+ assert content.metrics is not None
+ self.assertEqual(content.metrics.total_runs, 5)
+
class TestSectionBounds(SimpleTestCase):
def test_min_and_max_constants(self):
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
index 65dbc07098cc..451e9e899829 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
@@ -5,13 +5,19 @@ import datetime as dt
from typing import NotRequired, TypedDict
from posthog.test.base import BaseTest
-from unittest.mock import MagicMock, patch
+from unittest.mock import (
+ MagicMock,
+ call as mock_call,
+ patch,
+)
from django.test import SimpleTestCase
from django.utils import timezone
+from clickhouse_driver.errors import NetworkError, SocketTimeoutError
from parameterized import parameterized
+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
Citation,
@@ -21,6 +27,8 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
_UUID_RE,
_ch_ts,
+ _execute_ch_query_with_retry,
+ _is_retriable_ch_error,
_widened_ts_window,
add_citation,
add_section,
@@ -51,6 +59,12 @@ _sample_trace_details_fn = sample_trace_details.func # type: ignore[attr-define
_get_trace_detail_fn = get_trace_detail.func # type: ignore[attr-defined]
+def _per_query_memory_limit_error() -> ClickHouseQueryMemoryLimitExceeded:
+ error = ClickHouseQueryMemoryLimitExceeded()
+ error.is_per_query_limit = True
+ return error
+
+
class _ReportToolState(TypedDict):
report: EvalReportContent
trace_id_allowlist: list[str]
@@ -724,6 +738,27 @@ class TestListAndGetReportRun(BaseTest):
self.assertEqual(entry["result_rates"], {"pass": 75.0, "fail": 25.0, "na": 0.0})
self.assertEqual(entry["total_runs"], 8)
+ def test_metrics_unavailable_runs_are_not_agent_history(self):
+ now = timezone.now()
+ unavailable_run = self.EvaluationReportRun.objects.create(
+ report=self.report,
+ content={
+ "title": "Metrics temporarily unavailable",
+ "sections": [],
+ "generation_status": "metrics_unavailable",
+ "metrics": None,
+ },
+ metadata={},
+ period_start=now - dt.timedelta(hours=2),
+ period_end=now - dt.timedelta(hours=1),
+ )
+
+ listed_run_ids = {run["run_id"] for run in json.loads(_list_recent_report_runs_fn(state=self.state))}
+ fetched = json.loads(_get_report_run_fn(state=self.state, run_id=str(unavailable_run.id)))
+
+ self.assertNotIn(str(unavailable_run.id), listed_run_ids)
+ self.assertIn("error", fetched)
+
def test_get_rejects_non_uuid(self):
result = json.loads(_get_report_run_fn(state=self.state, run_id="not-a-uuid"))
self.assertIn("error", result)
@@ -765,6 +800,80 @@ class TestListAndGetReportRun(BaseTest):
self.assertIn("error", result)
+class TestExecuteChQueryWithRetry(SimpleTestCase):
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools.time.sleep")
+ @patch(
+ "posthog.temporal.ai_observability.eval_reports.report_agent.tools.random.uniform",
+ side_effect=lambda _minimum, maximum: maximum,
+ )
+ def test_retries_with_exponential_backoff_then_succeeds(
+ self, mock_uniform: MagicMock, mock_sleep: MagicMock
+ ) -> None:
+ attempts = {"n": 0}
+
+ def run_query() -> str:
+ attempts["n"] += 1
+ if attempts["n"] < 4:
+ raise ClickHouseAtCapacity()
+ return "ok"
+
+ result = _execute_ch_query_with_retry(run_query, query_type="Test")
+
+ self.assertEqual(result, "ok")
+ self.assertEqual(attempts["n"], 4)
+ self.assertEqual(
+ mock_uniform.call_args_list,
+ [mock_call(4.0, 8.0), mock_call(8.0, 16.0), mock_call(16.0, 32.0)],
+ )
+ self.assertEqual(mock_sleep.call_args_list, [mock_call(8.0), mock_call(16.0), mock_call(32.0)])
+
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools.time.sleep")
+ def test_reraises_after_exhausting_retries(self, mock_sleep: MagicMock) -> None:
+ attempts = {"n": 0}
+
+ def run_query() -> str:
+ attempts["n"] += 1
+ raise ClickHouseAtCapacity()
+
+ with self.assertRaises(ClickHouseAtCapacity):
+ _execute_ch_query_with_retry(run_query, query_type="Test", base_delay=0.0)
+
+ self.assertEqual(attempts["n"], 4)
+ self.assertEqual(mock_sleep.call_count, 3)
+
+ @parameterized.expand(
+ [
+ ("network", NetworkError()),
+ ("socket_timeout", SocketTimeoutError()),
+ ("cluster_memory_pressure", ClickHouseQueryMemoryLimitExceeded()),
+ ]
+ )
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools.time.sleep")
+ def test_retries_additional_transient_errors(self, _name: str, error: Exception, mock_sleep: MagicMock) -> None:
+ attempts = {"n": 0}
+
+ def run_query() -> str:
+ attempts["n"] += 1
+ if attempts["n"] == 1:
+ raise error
+ return "ok"
+
+ result = _execute_ch_query_with_retry(run_query, query_type="Test", max_retries=1, base_delay=0.0)
+
+ self.assertEqual(result, "ok")
+ mock_sleep.assert_called_once_with(0.0)
+
+ @parameterized.expand(
+ [
+ ("query_timeout", ClickHouseQueryTimeOut()),
+ ("per_query_memory_limit", _per_query_memory_limit_error()),
+ ("application_error", ValueError("bug")),
+ ]
+ )
+ def test_does_not_retry_non_transient_error(self, _name: str, error: Exception) -> None:
+ self.assertFalse(_is_retriable_ch_error(error))
+
+
class TestToolsCoordinate(SimpleTestCase):
"""Smoke: a realistic agent-like sequence of calls produces a valid report."""
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
index 49f2febf08b7..357947da2759 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -9,17 +9,23 @@ InjectedState, but whole-key replacement does not.
import re
import json
+import time
+import random
+from collections.abc import Callable
from datetime import UTC, datetime, timedelta
-from typing import TYPE_CHECKING, Annotated
+from typing import TYPE_CHECKING, Annotated, TypeVar
from django.db.models import Q
import structlog
+from clickhouse_driver.errors import NetworkError, SocketTimeoutError
from langchain_core.tools import BaseTool, tool
from langgraph.prebuilt import InjectedState
from posthog.hogql import ast
+from posthog.errors import CH_TRANSIENT_ERRORS
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
from posthog.temporal.ai_observability.eval_reports.output_types import (
EvaluationReportOutcomeDefinition,
get_outcome_definition,
@@ -27,6 +33,7 @@ from posthog.temporal.ai_observability.eval_reports.output_types import (
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
Citation,
+ EvalReportGenerationStatus,
ReportSection,
calculate_boolean_pass_rate,
calculate_result_rates,
@@ -103,6 +110,11 @@ def _report_run_target_filter(evaluation_target: str) -> Q:
return Q(content__evaluation_target=GENERATION_TARGET) | Q(content__evaluation_target__isnull=True)
+def _completed_report_run_filter() -> Q:
+ unavailable = EvalReportGenerationStatus.METRICS_UNAVAILABLE.value
+ return Q(content__generation_status__isnull=True) | ~Q(content__generation_status=unavailable)
+
+
def _ch_ts(iso_str: str) -> datetime:
"""Parse an ISO-8601 timestamp and return a UTC-aware datetime.
@@ -183,6 +195,59 @@ def _widened_ts_window(state: dict) -> tuple[datetime, datetime]:
return ts_start, ts_end
+# Query timeouts and per-query memory limits need a narrower query, so retrying
+# them without changing the query only adds load.
+RETRIABLE_CH_ERRORS = (*CH_TRANSIENT_ERRORS, NetworkError, SocketTimeoutError)
+_CH_QUERY_MAX_RETRIES = 3
+_CH_QUERY_BASE_DELAY_SECONDS = 8.0
+
+T = TypeVar("T")
+
+
+def _is_retriable_ch_error(error: Exception) -> bool:
+ return isinstance(error, RETRIABLE_CH_ERRORS) or (
+ isinstance(error, ClickHouseQueryMemoryLimitExceeded) and not error.is_per_query_limit
+ )
+
+
+def _execute_ch_query_with_retry(
+ run_query: Callable[[], T],
+ *,
+ query_type: str,
+ max_retries: int = _CH_QUERY_MAX_RETRIES,
+ base_delay: float = _CH_QUERY_BASE_DELAY_SECONDS,
+) -> T:
+ """Run a ClickHouse-backed callable, retrying transient errors with exponential backoff + jitter.
+
+ The report agent runs synchronously in a worker thread while the activity's
+ Heartbeater keeps heartbeating on the event loop, so a plain blocking sleep
+ here does not risk a heartbeat timeout. Non-transient errors propagate
+ immediately so genuine bugs still fail loudly.
+ """
+ for attempt in range(max_retries + 1):
+ try:
+ return run_query()
+ except Exception as error:
+ if not _is_retriable_ch_error(error):
+ raise
+ if attempt >= max_retries:
+ raise
+ # Jitter prevents concurrent report workers from retrying together.
+ max_delay = base_delay * (2**attempt)
+ delay = random.uniform(max_delay / 2, max_delay)
+ logger.warning(
+ "llma_eval_reports_clickhouse_retry",
+ error=str(error),
+ error_type=type(error).__name__,
+ delay=round(delay, 1),
+ attempt=attempt + 1,
+ max_retries=max_retries,
+ query_type=query_type,
+ )
+ time.sleep(delay)
+ raise AssertionError("unreachable: retry loop must return or re-raise")
+
+
def _execute_hogql(team_id: int, query_str: str, placeholders: dict | None = None) -> list[list]:
"""Execute a HogQL query against `events` and return results.
@@ -201,11 +266,14 @@ def _execute_hogql(team_id: int, query_str: str, placeholders: dict | None = Non
query = parse_select(query_str)
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team_id):
- result = execute_hogql_query(
+ result = _execute_ch_query_with_retry(
+ lambda: execute_hogql_query(
+ query_type="EvalReportAgent",
+ query=query,
+ placeholders=placeholders or {},
+ team=team,
+ ),
query_type="EvalReportAgent",
- query=query,
- placeholders=placeholders or {},
- team=team,
)
return result.results or []
@@ -230,12 +298,15 @@ def _execute_hogql_via_ai_events(team: "Team", query_str: str, placeholders: dic
# internally but not `feature`, so supply it here to keep these eval-report
# agent reads attributed to background enrichment.
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team.pk):
- result = query_ai_events(
- query=query,
- placeholders=placeholders or {},
- team=team,
+ result = _execute_ch_query_with_retry(
+ lambda: query_ai_events(
+ query=query,
+ placeholders=placeholders or {},
+ team=team,
+ query_type="EvalReportAgent",
+ fall_back_to_events=True,
+ ),
query_type="EvalReportAgent",
- fall_back_to_events=True,
)
return result.results or []
@@ -1040,6 +1111,7 @@ def list_recent_report_runs(
period_end__gte=since,
)
runs = runs.filter(_report_run_target_filter(evaluation_target))
+ runs = runs.filter(_completed_report_run_filter())
runs = runs.order_by("-period_end")[:limit]
result = []
@@ -1094,6 +1166,7 @@ def get_report_run(
evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))
runs = EvaluationReportRun.objects.filter(id=run_id, report__evaluation_id=evaluation_id)
runs = runs.filter(_report_run_target_filter(evaluation_target))
+ runs = runs.filter(_completed_report_run_filter())
try:
run = runs.get()
except EvaluationReportRun.DoesNotExist:
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
index 4fedf19e63f0..786557bc9f8f 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -5,6 +5,7 @@ import pytest
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event
from unittest.mock import MagicMock, Mock, patch
+from django.test import SimpleTestCase
from django.utils import timezone
from parameterized import parameterized
@@ -18,16 +19,86 @@ from posthog.temporal.ai_observability.eval_reports.activities import (
_find_nth_eval_timestamp,
_load_evaluation_target,
_period_for_scheduled_report,
+ _update_next_delivery_date,
run_eval_report_agent_activity,
store_report_run_activity,
)
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import EvalReportContent, EvalReportMetrics
-from posthog.temporal.ai_observability.eval_reports.types import RunEvalReportAgentInput, StoreReportRunInput
+from posthog.temporal.ai_observability.eval_reports.types import (
+ RunEvalReportAgentInput,
+ StoreReportRunInput,
+ UpdateNextDeliveryDateInput,
+)
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRun
from products.ai_observability.backend.models.evaluations import Evaluation
+class TestUpdateNextDeliveryDate(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "unavailable_legacy",
+ "metrics_unavailable",
+ True,
+ None,
+ False,
+ ["next_delivery_date", "last_attempted_at"],
+ ),
+ (
+ "completed_legacy",
+ "completed",
+ True,
+ None,
+ True,
+ ["next_delivery_date", "last_attempted_at", "last_delivered_at"],
+ ),
+ (
+ "completed_cursor_only",
+ "completed",
+ False,
+ True,
+ True,
+ ["last_delivered_at"],
+ ),
+ ]
+ )
+ @patch("products.ai_observability.backend.models.evaluation_reports.EvaluationReport.objects.get")
+ def test_updates_automatic_report_timing(
+ self,
+ _name: str,
+ generation_status: str,
+ record_attempt: bool,
+ advance_data_cursor: bool | None,
+ expects_delivered_advance: bool,
+ expected_update_fields: list[str],
+ get_report: MagicMock,
+ ) -> None:
+ last_delivered = timezone.now() - dt.timedelta(hours=2)
+ last_attempted = timezone.now() - dt.timedelta(hours=1)
+ period_end = timezone.now()
+ report = MagicMock(last_delivered_at=last_delivered, last_attempted_at=last_attempted)
+ get_report.return_value = report
+
+ _update_next_delivery_date(
+ UpdateNextDeliveryDateInput(
+ report_id="report-id",
+ period_end=period_end.isoformat(),
+ generation_status=generation_status,
+ record_attempt=record_attempt,
+ advance_data_cursor=advance_data_cursor,
+ )
+ )
+
+ self.assertEqual(report.last_attempted_at, period_end if record_attempt else last_attempted)
+ self.assertEqual(report.last_delivered_at, period_end if expects_delivered_advance else last_delivered)
+ if record_attempt:
+ report.set_next_delivery_date.assert_called_once_with()
+ else:
+ report.set_next_delivery_date.assert_not_called()
+ report.save.assert_called_once_with(update_fields=expected_update_fields)
+
+
class TestEvaluationTargetLoading(BaseTest):
def test_loads_target_without_deferred_model_fields(self) -> None:
evaluation = Evaluation.objects.create(
@@ -93,6 +164,7 @@ async def test_run_agent_activity_loads_target_and_forwards_output_type(
assert result.content["metrics"]["output_type"] == output_type
assert result.content["evaluation_target"] == evaluation_target
+ assert result.generation_status == "completed"
assert run_agent.call_args.kwargs["output_type"] == output_type
assert run_agent.call_args.kwargs["evaluation_target"] == evaluation_target
load_target.assert_called_once_with(inputs.team_id, inputs.evaluation_id)
@@ -194,6 +266,43 @@ async def test_store_legacy_boolean_report_emits_normalized_generic_metrics() ->
assert properties["$ai_report_referenced_trace_ids"] == ["customer/trace:42"]
+async def test_store_metrics_unavailable_report_omits_placeholder_metrics() -> None:
+ report_run = MagicMock(id="run-id", report_id="report-id")
+ content: dict[str, object] = {
+ "title": "Metrics temporarily unavailable",
+ "sections": [],
+ "citations": [],
+ "generation_status": "metrics_unavailable",
+ "metrics": None,
+ }
+ inputs = StoreReportRunInput(
+ report_id="report-id",
+ team_id=1,
+ evaluation_id="evaluation-id",
+ content=content,
+ period_start="2026-07-01T00:00:00+00:00",
+ period_end="2026-07-02T00:00:00+00:00",
+ )
+
+ with (
+ patch(
+ "products.ai_observability.backend.models.evaluation_reports.EvaluationReportRun.objects.create",
+ return_value=report_run,
+ ) as create_report_run,
+ patch("posthog.models.team.Team.objects.get", return_value=MagicMock()),
+ patch("posthog.models.event.util.create_event") as create_event,
+ ):
+ await store_report_run_activity(inputs)
+
+ properties = create_event.call_args.kwargs["properties"]
+ assert create_report_run.call_args.kwargs["metadata"] == {}
+ assert properties["$ai_report_generation_status"] == "metrics_unavailable"
+ assert "$ai_report_total_runs" not in properties
+ assert "$ai_report_result_counts" not in properties
+ assert "$ai_report_pass_rate" not in properties
+
+
def test_count_trigger_uses_current_output_type() -> None:
report = MagicMock(team_id=1, team=MagicMock(), evaluation_id="evaluation-id")
report.evaluation.output_type = "sentiment"
@@ -437,6 +546,21 @@ class TestCountTriggeredReportChecks(BaseTest):
self.assertEqual(result.skipped_reason, "cooldown")
execute_hogql_query.assert_not_called()
+ def test_check_report_uses_latest_attempt_for_cooldown_and_success_for_count_window(self):
+ now = timezone.now()
+ report = self._create_report(
+ last_delivered_at=now - dt.timedelta(hours=2),
+ last_attempted_at=now - dt.timedelta(minutes=5),
+ cooldown_minutes=60,
+ )
+
+ with patch("posthog.hogql.query.execute_hogql_query") as execute_hogql_query:
+ result = _check_count_triggered_eval_report_sync(str(report.id), now)
+
+ self.assertFalse(result.due)
+ self.assertEqual(result.skipped_reason, "cooldown")
+ execute_hogql_query.assert_not_called()
+
def test_check_report_skips_daily_cap_without_clickhouse_query(self):
now = timezone.now()
report = self._create_report(daily_run_cap=1)
@@ -453,6 +577,24 @@ class TestCountTriggeredReportChecks(BaseTest):
self.assertEqual(result.skipped_reason, "daily_cap")
execute_hogql_query.assert_not_called()
+ def test_check_report_does_not_count_unavailable_run_toward_daily_cap(self):
+ now = timezone.now()
+ report = self._create_report(daily_run_cap=1)
+ EvaluationReportRun.objects.create(
+ report=report,
+ content={"generation_status": "metrics_unavailable"},
+ period_start=now - dt.timedelta(hours=1),
+ period_end=now,
+ )
+
+ with patch("posthog.hogql.query.execute_hogql_query") as execute_hogql_query:
+ execute_hogql_query.return_value = Mock(results=[[100]])
+ result = _check_count_triggered_eval_report_sync(str(report.id), now)
+
+ self.assertTrue(result.due)
+ self.assertIsNone(result.skipped_reason)
+ execute_hogql_query.assert_called_once()
+
def test_batch_skips_gated_reports_without_clickhouse_and_preserves_order(self):
# Every Postgres-gated report must be resolved without touching ClickHouse — that's
# the whole point of the batched path (stop firing count queries for reports we'll skip).
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
index 27c651da3af8..fa1cd1c86176 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
@@ -338,6 +338,17 @@ class TestMetricsBlockHtml(SimpleTestCase):
self.assertNotIn("▼", html)
self.assertNotIn("pp vs previous", html)
+ def test_unavailable_metrics_render_notice_not_zero_table(self):
+ html = _render_metrics_block_html(
+ None,
+ period_start="2026-04-08T14:00:00+00:00",
+ period_end="2026-04-08T15:00:00+00:00",
+ )
+
+ self.assertIn("could not be calculated", html)
+ self.assertNotIn("Total runs", html)
+ self.assertIn("Apr 08, 2026 14:00 UTC", html) # period still shown
+
def test_renders_sentiment_distribution_without_boolean_labels(self):
metrics = EvalReportMetrics(
output_type="sentiment",
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py b/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
index 09cde955b908..20938adb9995 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
@@ -3,6 +3,10 @@ import asyncio
import pytest
from unittest.mock import patch
+from posthog.temporal.ai_observability.eval_reports.activities import (
+ deliver_report_activity,
+ update_next_delivery_date_activity,
+)
from posthog.temporal.ai_observability.eval_reports.types import (
CheckCountTriggeredEvalReportOutput,
CheckCountTriggeredEvalReportsBatchOutput,
@@ -11,6 +15,7 @@ from posthog.temporal.ai_observability.eval_reports.types import (
RunEvalReportAgentInput,
RunEvalReportAgentOutput,
StoreReportRunOutput,
+ UpdateNextDeliveryDateInput,
)
from posthog.temporal.ai_observability.eval_reports.workflow import (
GenerateAndDeliverEvalReportWorkflow,
@@ -71,6 +76,230 @@ async def test_generate_workflow_forwards_sentiment_output_type() -> None:
assert agent_input.output_type == "sentiment"
+ (
+ "agent_generation_status",
+ "generation_status_patch_enabled",
+ "attempt_patch_enabled",
+ "expected_generation_status",
+ "expected_schedule_updates",
+ ),
+ [
+ ("metrics_unavailable", True, True, "metrics_unavailable", [(True, False)]),
+ ("metrics_unavailable", False, False, "completed", [(True, True)]),
+ ("completed", True, True, "completed", [(True, False), (False, True)]),
+ ],
+)
+async def test_generate_workflow_forwards_generation_status_to_schedule(
+ agent_generation_status: str,
+ generation_status_patch_enabled: bool,
+ attempt_patch_enabled: bool,
+ expected_generation_status: str,
+ expected_schedule_updates: list[tuple[bool, bool]],
+) -> None:
+ activity_calls: list[object] = []
+ activity_inputs: list[object] = []
+ responses = iter(
+ [
+ PrepareReportContextOutput(
+ report_id="report-id",
+ team_id=1,
+ evaluation_id="evaluation-id",
+ evaluation_name="Evaluation",
+ evaluation_description="",
+ evaluation_prompt="",
+ evaluation_type="llm_judge",
+ period_start="2026-07-01T00:00:00+00:00",
+ period_end="2026-07-02T00:00:00+00:00",
+ previous_period_start="2026-06-30T00:00:00+00:00",
+ ),
+ RunEvalReportAgentOutput(
+ report_id="report-id",
+ content={
+ "generation_status": agent_generation_status,
+ "metrics": None if agent_generation_status == "metrics_unavailable" else {},
+ },
+ period_start="2026-07-01T00:00:00+00:00",
+ period_end="2026-07-02T00:00:00+00:00",
+ generation_status=agent_generation_status,
+ ),
+ StoreReportRunOutput(report_run_id="run-id"),
+ None,
+ None,
+ None,
+ ]
+ )
+
+ async def fake_execute_activity(activity, inputs, **_kwargs):
+ activity_calls.append(activity)
+ activity_inputs.append(inputs)
+ return next(responses)
+
+ def is_patch_enabled(patch_id: str) -> bool:
+ if patch_id == "eval-report-generation-status-2026-07":
+ return generation_status_patch_enabled
+ if patch_id == "eval-report-attempt-before-delivery-2026-07":
+ return attempt_patch_enabled
+ return False
+
+ with (
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.execute_activity",
+ new=fake_execute_activity,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.patched",
+ side_effect=is_patch_enabled,
+ ),
+ ):
+ await GenerateAndDeliverEvalReportWorkflow().run(
+ GenerateAndDeliverEvalReportWorkflowInput(report_id="report-id")
+ )
+
+ schedule_inputs = [inputs for inputs in activity_inputs if isinstance(inputs, UpdateNextDeliveryDateInput)]
+ assert [schedule_input.generation_status for schedule_input in schedule_inputs] == [
+ expected_generation_status
+ ] * len(expected_schedule_updates)
+ assert [
+ (schedule_input.record_attempt, schedule_input.advance_data_cursor) for schedule_input in schedule_inputs
+ ] == expected_schedule_updates
+
+ schedule_indexes = [
+ index for index, activity in enumerate(activity_calls) if activity is update_next_delivery_date_activity
+ ]
+ delivery_index = activity_calls.index(deliver_report_activity)
+ if attempt_patch_enabled:
+ assert schedule_indexes[0] < delivery_index
+ if expected_generation_status == "completed":
+ assert schedule_indexes[-1] > delivery_index
+ else:
+ assert schedule_indexes == [delivery_index + 1]
+
+
[email protected]("generation_status", ["completed", "metrics_unavailable"])
+async def test_automatic_run_records_attempt_before_delivery_failure(generation_status: str) -> None:
+ activity_calls: list[object] = []
+ activity_inputs: list[object] = []
+ responses = iter(
+ [
+ PrepareReportContextOutput(
+ report_id="report-id",
+ team_id=1,
+ evaluation_id="evaluation-id",
+ evaluation_name="Evaluation",
+ evaluation_description="",
+ evaluation_prompt="",
+ evaluation_type="llm_judge",
+ period_start="2026-07-01T00:00:00+00:00",
+ period_end="2026-07-02T00:00:00+00:00",
+ previous_period_start="2026-06-30T00:00:00+00:00",
+ ),
+ RunEvalReportAgentOutput(
+ report_id="report-id",
+ content={
+ "generation_status": generation_status,
+ "metrics": None if generation_status == "metrics_unavailable" else {},
+ },
+ period_start="2026-07-01T00:00:00+00:00",
+ period_end="2026-07-02T00:00:00+00:00",
+ generation_status=generation_status,
+ ),
+ StoreReportRunOutput(report_run_id="run-id"),
+ None,
+ ]
+ )
+
+ async def fake_execute_activity(activity, inputs, **_kwargs):
+ activity_calls.append(activity)
+ activity_inputs.append(inputs)
+ if activity is deliver_report_activity:
+ raise RuntimeError("delivery unavailable")
+ return next(responses)
+
+ with (
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.execute_activity",
+ new=fake_execute_activity,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.patched",
+ side_effect=lambda patch_id: (
+ patch_id
+ in {
+ "eval-report-generation-status-2026-07",
+ "eval-report-attempt-before-delivery-2026-07",
+ }
+ ),
+ ),
+ pytest.raises(RuntimeError, match="delivery unavailable"),
+ ):
+ await GenerateAndDeliverEvalReportWorkflow().run(
+ GenerateAndDeliverEvalReportWorkflowInput(report_id="report-id")
+ )
+
+ schedule_inputs = [inputs for inputs in activity_inputs if isinstance(inputs, UpdateNextDeliveryDateInput)]
+ assert len(schedule_inputs) == 1
+ schedule_input = schedule_inputs[0]
+ assert schedule_input.generation_status == generation_status
+ assert schedule_input.record_attempt is True
+ assert schedule_input.advance_data_cursor is False
+ assert activity_calls.count(update_next_delivery_date_activity) == 1
+ assert activity_calls.index(update_next_delivery_date_activity) < activity_calls.index(deliver_report_activity)
+
+
+async def test_generate_workflow_does_not_emit_signal_without_metrics() -> None:
+ responses = iter(
+ [
+ PrepareReportContextOutput(
+ report_id="report-id",
+ team_id=1,
+ evaluation_id="evaluation-id",
+ evaluation_name="Evaluation",
+ evaluation_description="",
+ evaluation_prompt="",
+ evaluation_type="llm_judge",
+ period_start="2026-07-01T00:00:00+00:00",
+ period_end="2026-07-02T00:00:00+00:00",
+ previous_period_start="2026-06-30T00:00:00+00:00",
+ ),
+ RunEvalReportAgentOutput(
+ report_id="report-id",
+ content={"generation_status": "metrics_unavailable", "metrics": None},
+ period_start="2026-07-01T00:00:00+00:00",
+ period_end="2026-07-02T00:00:00+00:00",
+ generation_status="metrics_unavailable",
+ ),
+ StoreReportRunOutput(report_run_id="run-id"),
+ None,
+ ]
+ )
+
+ async def fake_execute_activity(_activity, _inputs, **_kwargs):
+ return next(responses)
+
+ with (
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.execute_activity",
+ new=fake_execute_activity,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.patched",
+ return_value=True,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.start_child_workflow"
+ ) as start_child_workflow,
+ ):
+ await GenerateAndDeliverEvalReportWorkflow().run(
+ GenerateAndDeliverEvalReportWorkflowInput(report_id="report-id", manual=True)
+ )
+
+ start_child_workflow.assert_not_called()
+
+
@pytest.mark.asyncio
async def test_count_triggered_report_check_continues_after_activity_failure() -> None:
checked_report_ids: list[str] = []
diff --git a/posthog/temporal/ai_observability/eval_reports/types.py b/posthog/temporal/ai_observability/eval_reports/types.py
index 7aaffe4f19a4..f0a9a77e1bb9 100644
--- a/posthog/temporal/ai_observability/eval_reports/types.py
+++ b/posthog/temporal/ai_observability/eval_reports/types.py
@@ -95,6 +95,7 @@ class RunEvalReportAgentOutput:
content: dict[str, Any]
period_start: str
period_end: str
+ generation_status: str = "completed"
@dataclasses.dataclass
@@ -122,6 +123,9 @@ class DeliverReportInput:
class UpdateNextDeliveryDateInput:
report_id: str
period_end: str
+ generation_status: str = "completed"
+ record_attempt: bool = True
+ advance_data_cursor: bool | None = None
@dataclasses.dataclass
diff --git a/posthog/temporal/ai_observability/eval_reports/workflow.py b/posthog/temporal/ai_observability/eval_reports/workflow.py
index fe224675b9e7..804679390550 100644
--- a/posthog/temporal/ai_observability/eval_reports/workflow.py
+++ b/posthog/temporal/ai_observability/eval_reports/workflow.py
@@ -276,6 +276,28 @@ def _log_fan_out_failures(kind: str, report_ids: list[str], results: list) -> No
)
+async def _update_report_schedule(
+ report_id: str,
+ period_end: str,
+ generation_status: str,
+ *,
+ record_attempt: bool = True,
+ advance_data_cursor: bool | None = None,
+) -> None:
+ await temporalio.workflow.execute_activity(
+ update_next_delivery_date_activity,
+ UpdateNextDeliveryDateInput(
+ report_id=report_id,
+ period_end=period_end,
+ generation_status=generation_status,
+ record_attempt=record_attempt,
+ advance_data_cursor=advance_data_cursor,
+ ),
+ start_to_close_timeout=UPDATE_SCHEDULE_ACTIVITY_TIMEOUT,
+ retry_policy=UPDATE_SCHEDULE_RETRY_POLICY,
+ )
+
+
@temporalio.workflow.defn(name=GENERATE_EVAL_REPORT_WORKFLOW_NAME)
class GenerateAndDeliverEvalReportWorkflow(PostHogWorkflow):
"""Per-report workflow: prepare context, run agent, store, deliver, update schedule."""
@@ -332,6 +354,22 @@ class GenerateAndDeliverEvalReportWorkflow(PostHogWorkflow):
retry_policy=STORE_RETRY_POLICY,
)
+ generation_status = (
+ agent_result.generation_status
+ if temporalio.workflow.patched("eval-report-generation-status-2026-07")
+ else "completed"
+ )
+ generation_completed = generation_status == "completed"
+ attempt_before_delivery = temporalio.workflow.patched("eval-report-attempt-before-delivery-2026-07")
+
+ if not inputs.manual and (attempt_before_delivery or not generation_completed):
+ await _update_report_schedule(
+ inputs.report_id,
+ context.period_end,
+ generation_status,
+ advance_data_cursor=False if attempt_before_delivery else None,
+ )
+
# 3b. Emit a signal for this report run (fire-and-forget).
# Runs on the same LLMA worker as the parent via LLMA_TASK_QUEUE; ABANDON
# parent-close lets the LLM summary call continue independently so it doesn't
@@ -341,7 +379,7 @@ class GenerateAndDeliverEvalReportWorkflow(PostHogWorkflow):
# Wrapped in workflow.patched so in-flight workflows started before this code
# was deployed don't hit a nondeterminism error on replay — they'll skip the
# child-workflow command entirely.
- if temporalio.workflow.patched("eval-report-emit-signal-2026-04"):
+ if generation_completed and temporalio.workflow.patched("eval-report-emit-signal-2026-04"):
try:
await temporalio.workflow.start_child_workflow(
EmitEvalReportSignalWorkflow.run,
@@ -384,14 +422,12 @@ class GenerateAndDeliverEvalReportWorkflow(PostHogWorkflow):
retry_policy=DELIVER_RETRY_POLICY,
)
- # 5. Update next delivery date (skip for manual runs to avoid disrupting schedule)
- if not inputs.manual:
- await temporalio.workflow.execute_activity(
- update_next_delivery_date_activity,
- UpdateNextDeliveryDateInput(
- report_id=inputs.report_id,
- period_end=context.period_end,
- ),
- start_to_close_timeout=UPDATE_SCHEDULE_ACTIVITY_TIMEOUT,
- retry_policy=UPDATE_SCHEDULE_RETRY_POLICY,
+ # 5. Advance the successful data cursor (skip for manual runs to avoid disrupting schedule)
+ if not inputs.manual and generation_completed:
+ await _update_report_schedule(
+ inputs.report_id,
+ context.period_end,
+ generation_status,
+ record_attempt=not attempt_before_delivery,
+ advance_data_cursor=True,
)
diff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.py
index 6379c55c3550..9bf4b8de5af2 100644
--- a/products/ai_observability/backend/api/evaluation_reports.py
+++ b/products/ai_observability/backend/api/evaluation_reports.py
@@ -21,6 +21,7 @@ from posthog.event_usage import report_user_action
from posthog.models.integration import Integration
from posthog.permissions import AccessControlPermission
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
+ EvalReportGenerationStatus,
normalize_metrics_payload,
normalize_report_content_payload,
)
@@ -460,10 +461,18 @@ class EvaluationReportRunContentSerializer(serializers.Serializer):
required=False,
help_text="References grounding findings in the report.",
)
+ generation_status = serializers.ChoiceField(
+ choices=[(status.value, status.value) for status in EvalReportGenerationStatus],
+ required=False,
+ help_text=(
+ "Whether report generation completed or metrics were temporarily unavailable. "
+ "Legacy runs without this field completed normally."
+ ),
+ )
metrics = EvaluationReportMetricsSerializer(
required=False,
allow_null=True,
- help_text="Structured metrics computed for the report period.",
+ help_text="Structured metrics for completed reports, or null when metrics were temporarily unavailable.",
)
diff --git a/products/ai_observability/backend/migrations/0030_evaluationreport_last_attempted_at.py b/products/ai_observability/backend/migrations/0030_evaluationreport_last_attempted_at.py
new file mode 100644
index 000000000000..69e56bdaa313
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0030_evaluationreport_last_attempted_at.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.14 on 2026-07-28 13:59
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0029_disable_reports_for_disabled_evaluations"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="evaluationreport",
+ name="last_attempted_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index bb48b46e9765..6ccaaf48b83c 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0029_disable_reports_for_disabled_evaluations
+0030_evaluationreport_last_attempted_at
diff --git a/products/ai_observability/backend/models/evaluation_reports.py b/products/ai_observability/backend/models/evaluation_reports.py
index 4e4fa1736373..8e8d44258b80 100644
--- a/products/ai_observability/backend/models/evaluation_reports.py
+++ b/products/ai_observability/backend/models/evaluation_reports.py
@@ -85,6 +85,7 @@ class EvaluationReport(UUIDTModel):
enabled = models.BooleanField(default=True)
deleted = models.BooleanField(default=False)
last_delivered_at = models.DateTimeField(null=True, blank=True)
+ last_attempted_at = models.DateTimeField(null=True, blank=True)
# Count-based trigger settings (only used when frequency='every_n')
trigger_threshold = models.IntegerField(
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx
index fa47ec2509ba..cb3895ea7cec 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx
@@ -15,11 +15,20 @@ function buildMetrics(fields: EvaluationReportStoredMetrics): EvaluationReportSt
}
}
-function buildReportRun(metrics: EvaluationReportStoredMetrics): EvaluationReportRun {
+function buildReportRun(
+ metrics: EvaluationReportStoredMetrics | null,
+ generationStatus: 'completed' | 'metrics_unavailable' = 'completed'
+): EvaluationReportRun {
return {
id: 'run-id',
report: 'report-id',
- content: { title: 'Evaluation report', sections: [], citations: [], metrics },
+ content: {
+ title: 'Evaluation report',
+ sections: [],
+ citations: [],
+ metrics,
+ generation_status: generationStatus,
+ },
metadata: null,
period_start: '2026-07-01T00:00:00Z',
period_end: '2026-07-02T00:00:00Z',
@@ -85,6 +94,13 @@ describe('EvaluationReportViewer', () => {
expect(screen.queryByText('(80.00%)')).toBeNull()
})
+ it('renders a metrics-unavailable notice instead of a zero-run table', () => {
+ render(<EvaluationReportViewer reportRun={buildReportRun(null, 'metrics_unavailable')} compact />)
+
+ expect(screen.getByText(/could not be calculated/)).toBeTruthy()
+ expect(screen.queryByText('Total runs')).toBeNull()
+ })
+
it('shows sentiment outcome distribution without boolean pass-rate framing', () => {
const metrics = buildMetrics({
output_type: 'sentiment',
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
index 1ff9f5c3524f..c4c0656897d0 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
@@ -130,6 +130,9 @@ const RESULT_ORDER: Record<EvaluationOutputType, string[]> = {
sentiment: ['positive', 'neutral', 'negative'],
}
+const METRICS_UNAVAILABLE_MESSAGE =
+ 'Metrics could not be calculated for this period because evaluation data was temporarily unavailable. This does not mean that no evaluations ran.'
+
interface EvaluationReportResultMetric {
key: string
label: string
@@ -314,6 +317,7 @@ export function EvaluationReportViewer({
const content = reportRun.content
const sections = useMemo(() => content.sections ?? [], [content.sections])
const metrics = content.metrics ?? reportRun.metadata
+ const metricsUnavailable = content.generation_status === 'metrics_unavailable'
const citations = useMemo(() => content.citations ?? [], [content.citations])
// Default to executive summary (first section) expanded. Memoized so Expand/Collapse all
@@ -374,7 +378,13 @@ export function EvaluationReportViewer({
</div>
)}
- {metrics && <MetricsCard metrics={metrics} />}
+ {metricsUnavailable ? (
+ <div className="bg-bg-light border rounded p-3 mb-3 text-sm text-muted">
+ {METRICS_UNAVAILABLE_MESSAGE}
+ </div>
+ ) : (
+ metrics && <MetricsCard metrics={metrics} />
+ )}
{sections.length > 0 && (
<>
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
index eba13df946bf..e054d6bb0ed2 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
@@ -104,6 +104,9 @@ export function EvaluationReportsTab({ evaluationId, onConfigureClick }: Evaluat
title: 'Results',
key: 'results',
render: (_, run: EvaluationReportRun) => {
+ if (run.content?.generation_status === 'metrics_unavailable') {
+ return 'Metrics unavailable'
+ }
const metrics = run.content?.metrics ?? run.metadata
return metrics ? summarizeEvaluationReportResults(metrics) : '–'
},
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index e4dec7a3c1af..584dec3829ab 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -1291,6 +1291,17 @@ export interface EvaluationReportCitationApi {
reason?: string
}
+/**
+ * * `completed` - completed
+ * * `metrics_unavailable` - metrics_unavailable
+ */
+export type GenerationStatusEnumApi = (typeof GenerationStatusEnumApi)[keyof typeof GenerationStatusEnumApi]
+
+export const GenerationStatusEnumApi = {
+ Completed: 'completed',
+ MetricsUnavailable: 'metrics_unavailable',
+} as const
+
/**
* Count by output-specific result label, such as pass/fail/N/A or positive/neutral/negative.
*/
@@ -1365,7 +1376,12 @@ export interface EvaluationReportRunContentApi {
sections?: EvaluationReportSectionApi[]
/** References grounding findings in the report. */
citations?: EvaluationReportCitationApi[]
- /** Structured metrics computed for the report period. */
+ /** Whether report generation completed or metrics were temporarily unavailable. Legacy runs without this field completed normally.
+ *
+ * * `completed` - completed
+ * * `metrics_unavailable` - metrics_unavailable */
+ generation_status?: GenerationStatusEnumApi
+ /** Structured metrics for completed reports, or null when metrics were temporarily unavailable. */
metrics?: EvaluationReportMetricsApi | null
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b3b810cd28e0..22833a5b4dc4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25975,6 +25975,18 @@ export namespace Schemas {
content?: string;
}
+ /**
+ * * `completed` - completed
+ * * `metrics_unavailable` - metrics_unavailable
+ */
+ export type GenerationStatusEnum = typeof GenerationStatusEnum[keyof typeof GenerationStatusEnum];
+
+
+ export const GenerationStatusEnum = {
+ Completed: 'completed',
+ MetricsUnavailable: 'metrics_unavailable',
+ } as const;
+
export interface EvaluationReportRunContent {
/** Evaluation target analyzed by this report run. Legacy runs without this field targeted generations.
*
@@ -25987,7 +25999,12 @@ export namespace Schemas {
sections?: EvaluationReportSection[];
/** References grounding findings in the report. */
citations?: EvaluationReportCitation[];
- /** Structured metrics computed for the report period. */
+ /** Whether report generation completed or metrics were temporarily unavailable. Legacy runs without this field completed normally.
+ *
+ * * `completed` - completed
+ * * `metrics_unavailable` - metrics_unavailable */
+ generation_status?: GenerationStatusEnum;
+ /** Structured metrics for completed reports, or null when metrics were temporarily unavailable. */
metrics?: EvaluationReportMetrics | null;
}