: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(aio): isolate count-triggered eval report checks (#69738)
Radu Raicea69eae91726c3
diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.pyindex 3fb55bd461ae..7eb75dc9f759 100644--- a/posthog/temporal/ai_observability/__init__.py+++ b/posthog/temporal/ai_observability/__init__.py@@ -1,6 +1,7 @@from posthog.temporal.ai_observability.eval_reports.activities import (+ check_count_triggered_eval_report_activity,deliver_report_activity,- fetch_count_triggered_eval_reports_activity,+ fetch_count_triggered_eval_report_candidates_activity,fetch_due_eval_reports_activity,prepare_report_context_activity,run_eval_report_agent_activity,@@ -151,7 +152,8 @@ ACTIVITIES = [emit_cluster_events_activity,# Evaluation report activitiesfetch_due_eval_reports_activity,- fetch_count_triggered_eval_reports_activity,+ fetch_count_triggered_eval_report_candidates_activity,+ check_count_triggered_eval_report_activity,prepare_report_context_activity,run_eval_report_agent_activity,store_report_run_activity,diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.pyindex 323f38c49ab4..d3a92aabbb1b 100644--- a/posthog/temporal/ai_observability/eval_reports/activities.py+++ b/posthog/temporal/ai_observability/eval_reports/activities.py@@ -1,6 +1,7 @@"""Activities for evaluation reports workflow."""import datetime as dt+from typing import TYPE_CHECKINGfrom zoneinfo import ZoneInfoimport temporalio.activity@@ -11,6 +12,8 @@ from posthog.hogql import astfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.eval_reports.types import (+ CheckCountTriggeredEvalReportInput,+ CheckCountTriggeredEvalReportOutput,CheckCountTriggeredReportsWorkflowInputs,DeliverReportInput,FetchDueEvalReportsOutput,@@ -25,6 +28,9 @@ from posthog.temporal.ai_observability.eval_reports.types import ()from posthog.temporal.common.heartbeat import Heartbeater+if TYPE_CHECKING:+ from products.ai_observability.backend.models.evaluation_reports import EvaluationReport+logger = get_logger(__name__)@@ -62,109 +68,124 @@ async def fetch_due_eval_reports_activity(@temporalio.activity.defn-async def fetch_count_triggered_eval_reports_activity(+async def fetch_count_triggered_eval_report_candidates_activity(inputs: CheckCountTriggeredReportsWorkflowInputs,) -> FetchDueEvalReportsOutput:- """Check count-based reports and return those whose eval count exceeds the threshold."""+ """Return count-triggered report IDs that need an independent count check."""@database_sync_to_async(thread_sensitive=False)- def check_reports() -> tuple[list[str], int, int, int]:- from posthog.hogql.parser import parse_select- from posthog.hogql.query import execute_hogql_query+ def get_report_ids() -> list[str]:+ return _fetch_count_triggered_eval_report_candidate_ids()- from posthog.clickhouse.query_tagging import Feature, Product, tags_context- from posthog.models import Team+ report_ids = await get_report_ids()+ await logger.ainfo(+ "llma_eval_reports_coordinator_count_triggered_candidates_poll",+ total_checked=len(report_ids),+ )+ from posthog.temporal.ai_observability.eval_reports.metrics import record_coordinator_check_count- from products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRun+ record_coordinator_check_count(len(report_ids), "count_triggered")+ return FetchDueEvalReportsOutput(report_ids=report_ids)- now = dt.datetime.now(tz=dt.UTC)- due: list[str] = []- skipped_cooldown = 0- skipped_daily_cap = 0- reports = list(- EvaluationReport.objects.deliverable()- .filter(- frequency=EvaluationReport.Frequency.EVERY_N,- trigger_threshold__isnull=False,- evaluation__output_type="boolean",- )- .select_related("evaluation")- )- total_checked = len(reports)-- for report in reports:- # Cooldown: skip if last delivery was too recent- if report.last_delivered_at:- cooldown_delta = dt.timedelta(minutes=report.cooldown_minutes)- if (now - report.last_delivered_at) < cooldown_delta:- skipped_cooldown += 1- continue-- # Daily cap: skip if too many runs today- today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)- today_runs = EvaluationReportRun.objects.filter(- report=report,- created_at__gte=today_start,- ).count()- if today_runs >= report.daily_run_cap:- skipped_daily_cap += 1- continue-- # Count evals since last delivery (or since report creation if first run).- # starts_at is nullable for count-triggered reports, so fall back to created_at.- # Pass the datetime directly to ast.Constant — HogQL's printer serializes it- # as toDateTime64(..., 6, <team_tz>) with correct TZ alignment. A bare string- # would be coerced in the team's timezone and silently shift the comparison- # by the team's offset.- since = report.last_delivered_at or report.starts_at or report.created_at-- team = Team.objects.get(id=report.team_id)- query = parse_select(- """- SELECT count() as total- FROM events- WHERE event = '$ai_evaluation'- AND properties.$ai_evaluation_id = {evaluation_id}- AND timestamp >= {since}- """,- placeholders={- "evaluation_id": ast.Constant(value=str(report.evaluation_id)),- "since": ast.Constant(value=since),- },- )- with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team.pk):- result = execute_hogql_query(query=query, team=team)- rows = result.results or []- count = rows[0][0] if rows else 0+async def check_count_triggered_eval_report_activity(+ inputs: CheckCountTriggeredEvalReportInput,+) -> CheckCountTriggeredEvalReportOutput:+ """Check one count-triggered report against its threshold."""- # The queryset filters trigger_threshold__isnull=False above, so this is- # always set on rows we iterate — assert for mypy.- assert report.trigger_threshold is not None- if count >= report.trigger_threshold:- due.append(str(report.id))+ @database_sync_to_async(thread_sensitive=False)+ def check_report() -> CheckCountTriggeredEvalReportOutput:+ return _check_count_triggered_eval_report_sync(inputs.report_id)- return due, total_checked, skipped_cooldown, skipped_daily_cap+ return await check_report()- # Heartbeat while the sync loop runs — prevents activity timeout as the- # number of count-triggered reports grows (each report = 1 HogQL query).- async with Heartbeater():- report_ids, total_checked, skipped_cooldown, skipped_daily_cap = await check_reports()- await logger.ainfo(- "llma_eval_reports_coordinator_count_triggered_poll",- reports_found=len(report_ids),- total_checked=total_checked,- skipped_cooldown=skipped_cooldown,- skipped_daily_cap=skipped_daily_cap,- )- from posthog.temporal.ai_observability.eval_reports.metrics import (- record_coordinator_check_count,- record_coordinator_reports_found,++def _fetch_count_triggered_eval_report_candidate_ids() -> list[str]:+ from products.ai_observability.backend.models.evaluation_reports import EvaluationReport++ return [+ str(pk)+ for pk in EvaluationReport.objects.deliverable()+ .filter(+ frequency=EvaluationReport.Frequency.EVERY_N,+ trigger_threshold__isnull=False,+ evaluation__output_type="boolean",+ )+ .values_list("id", flat=True)+ ]+++def _check_count_triggered_eval_report_sync(+ report_id: str,+ now: dt.datetime | None = None,+) -> CheckCountTriggeredEvalReportOutput:+ from products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRun++ report = (+ EvaluationReport.objects.deliverable()+ .filter(+ id=report_id,+ frequency=EvaluationReport.Frequency.EVERY_N,+ trigger_threshold__isnull=False,+ evaluation__output_type="boolean",+ )+ .select_related("evaluation", "team")+ .first())+ if report is None:+ return CheckCountTriggeredEvalReportOutput(report_id=report_id, due=False, skipped_reason="not_deliverable")- record_coordinator_check_count(total_checked, "count_triggered")- record_coordinator_reports_found(len(report_ids), "count_triggered")- return FetchDueEvalReportsOutput(report_ids=report_ids)+ now = now or dt.datetime.now(tz=dt.UTC)+ if report.last_delivered_at:+ cooldown_delta = dt.timedelta(minutes=report.cooldown_minutes)+ if (now - report.last_delivered_at) < cooldown_delta:+ return CheckCountTriggeredEvalReportOutput(report_id=report_id, due=False, skipped_reason="cooldown")++ today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)+ today_runs = EvaluationReportRun.objects.filter(+ report=report,+ created_at__gte=today_start,+ ).count()+ if today_runs >= report.daily_run_cap:+ return CheckCountTriggeredEvalReportOutput(report_id=report_id, due=False, skipped_reason="daily_cap")++ since = report.last_delivered_at or report.starts_at or report.created_at+ count = _count_eval_results_for_report(report, since)++ assert report.trigger_threshold is not None+ return CheckCountTriggeredEvalReportOutput(report_id=report_id, due=count >= report.trigger_threshold)+++def _count_eval_results_for_report(report: "EvaluationReport", since: dt.datetime) -> int:+ from posthog.hogql.parser import parse_select+ from posthog.hogql.query import execute_hogql_query++ from posthog.clickhouse.query_tagging import Feature, Product, tags_context++ # Pass the datetime directly to ast.Constant. HogQL's printer serializes it+ # as toDateTime64(..., 6, <team_tz>) with correct TZ alignment. A bare string+ # would be coerced in the team's timezone and silently shift the comparison+ # by the team's offset.+ query = parse_select(+ """+ SELECT count() as total+ FROM events+ WHERE event = '$ai_evaluation'+ AND properties.$ai_evaluation_id = {evaluation_id}+ AND timestamp >= {since}+ """,+ placeholders={+ "evaluation_id": ast.Constant(value=str(report.evaluation_id)),+ "since": ast.Constant(value=since),+ },+ )+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.ENRICHMENT, team_id=report.team_id):+ result = execute_hogql_query(query=query, team=report.team)+ rows = result.results or []+ if not rows:+ return 0+ return int(rows[0][0] or 0)def _find_nth_eval_timestamp(diff --git a/posthog/temporal/ai_observability/eval_reports/constants.py b/posthog/temporal/ai_observability/eval_reports/constants.pyindex 743e702a44cc..142947120da8 100644--- a/posthog/temporal/ai_observability/eval_reports/constants.py+++ b/posthog/temporal/ai_observability/eval_reports/constants.py@@ -23,6 +23,8 @@ COORDINATOR_EXECUTION_TIMEOUT = timedelta(hours=2)# Activity timeoutsFETCH_ACTIVITY_TIMEOUT = timedelta(seconds=60)+COUNT_TRIGGER_CHECK_BATCH_SIZE = 5+COUNT_TRIGGER_CHECK_ACTIVITY_TIMEOUT = timedelta(seconds=60)PREPARE_ACTIVITY_TIMEOUT = timedelta(seconds=60)AGENT_ACTIVITY_TIMEOUT = timedelta(seconds=660) # 11 minutes (agent timeout + buffer)STORE_ACTIVITY_TIMEOUT = timedelta(seconds=60)diff --git a/posthog/temporal/ai_observability/eval_reports/metrics.py b/posthog/temporal/ai_observability/eval_reports/metrics.pyindex 911b958f394d..02b3afa072bc 100644--- a/posthog/temporal/ai_observability/eval_reports/metrics.py+++ b/posthog/temporal/ai_observability/eval_reports/metrics.py@@ -49,7 +49,8 @@ EVAL_REPORTS_LATENCY_HISTOGRAM_BUCKETS = [EVAL_REPORTS_ACTIVITY_TYPES = {"fetch_due_eval_reports_activity",- "fetch_count_triggered_eval_reports_activity",+ "fetch_count_triggered_eval_report_candidates_activity",+ "check_count_triggered_eval_report_activity","prepare_report_context_activity","run_eval_report_agent_activity","store_report_run_activity",diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py b/posthog/temporal/ai_observability/eval_reports/test/test_activities.pyindex 81686dc8d62d..8745ca3fa1c3 100644--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py@@ -1,12 +1,17 @@import datetime as dtfrom posthog.test.base import BaseTest+from unittest.mock import Mock, patchfrom django.utils import timezone-from posthog.temporal.ai_observability.eval_reports.activities import _period_for_scheduled_report+from posthog.temporal.ai_observability.eval_reports.activities import (+ _check_count_triggered_eval_report_sync,+ _fetch_count_triggered_eval_report_candidate_ids,+ _period_for_scheduled_report,+)-from products.ai_observability.backend.models.evaluation_reports import EvaluationReport+from products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRunfrom products.ai_observability.backend.models.evaluations import Evaluation@@ -143,6 +148,88 @@ class TestPrepareReportContext(BaseTest):self.assertEqual(result["team_id"], self.team.id)+class TestCountTriggeredReportChecks(BaseTest):+ def _create_report(self, **kwargs) -> EvaluationReport:+ evaluation = Evaluation.objects.create(+ team=self.team,+ name="Test Eval",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "test prompt"},+ output_type="boolean",+ output_config={},+ enabled=True,+ created_by=self.user,+ conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],+ )+ defaults = {+ "team": self.team,+ "evaluation": evaluation,+ "frequency": EvaluationReport.Frequency.EVERY_N,+ "rrule": "",+ "starts_at": None,+ "trigger_threshold": 100,+ "delivery_targets": [{"type": "email", "value": "[email protected]"}],+ }+ defaults.update(kwargs)+ return EvaluationReport.objects.create(**defaults)++ def test_fetch_candidates_returns_only_deliverable_count_triggered_reports(self):+ count_triggered_report = self._create_report()+ self._create_report(enabled=False)+ self._create_report(+ frequency=EvaluationReport.Frequency.SCHEDULED,+ rrule="FREQ=HOURLY",+ starts_at=timezone.now() - dt.timedelta(hours=5),+ )++ with patch("posthog.hogql.query.execute_hogql_query") as execute_hogql_query:+ report_ids = _fetch_count_triggered_eval_report_candidate_ids()++ self.assertEqual(report_ids, [str(count_triggered_report.id)])+ execute_hogql_query.assert_not_called()++ def test_check_report_returns_due_when_threshold_is_crossed(self):+ report = self._create_report(trigger_threshold=100)++ 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), timezone.now())++ self.assertTrue(result.due)+ self.assertIsNone(result.skipped_reason)+ execute_hogql_query.assert_called_once()++ def test_check_report_skips_cooldown_without_clickhouse_query(self):+ now = timezone.now()+ report = self._create_report(+ last_delivered_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)+ EvaluationReportRun.objects.create(+ report=report,+ period_start=now - dt.timedelta(hours=1),+ period_end=now,+ )++ 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, "daily_cap")+ execute_hogql_query.assert_not_called()++class TestPeriodForScheduledReport(BaseTest):"""Unit-ish tests for the rrule period helper — uses in-memory instances tobypass model save validation so we can exercise fallback paths."""diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py b/posthog/temporal/ai_observability/eval_reports/test/test_workflow.pynew file mode 100644index 000000000000..25ce3506690b--- /dev/null+++ b/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py@@ -0,0 +1,54 @@+import pytest+from unittest.mock import patch++from posthog.temporal.ai_observability.eval_reports.types import CheckCountTriggeredEvalReportOutput+from posthog.temporal.ai_observability.eval_reports.workflow import _check_count_triggered_eval_report_candidates+++async def test_count_triggered_report_check_continues_after_activity_failure() -> None:+ checked_report_ids: list[str] = []+ skipped_reasons = {+ "cooldown": "cooldown",+ "daily_cap": "daily_cap",+ "not_deliverable": "not_deliverable",+ }++ async def fake_execute_activity(_activity, inputs, **_kwargs):+ checked_report_ids.append(inputs.report_id)+ if inputs.report_id == "failed":+ raise RuntimeError("clickhouse at capacity")+ return CheckCountTriggeredEvalReportOutput(+ report_id=inputs.report_id,+ due=inputs.report_id == "due",+ skipped_reason=skipped_reasons.get(inputs.report_id),+ )++ 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.record_coordinator_reports_found") as record,+ patch("posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.logger") as logger,+ ):+ report_ids = await _check_count_triggered_eval_report_candidates(+ ["due", "failed", "not_due", "cooldown", "daily_cap", "not_deliverable"]+ )++ assert report_ids == ["due"]+ assert checked_report_ids == ["due", "failed", "not_due", "cooldown", "daily_cap", "not_deliverable"]+ record.assert_called_once_with(1, "count_triggered")+ logger.warning.assert_called_once()+ assert logger.warning.call_args.args == ("count_triggered_eval_report_check.activity_errors",)+ assert logger.warning.call_args.kwargs["extra"]["failed_count"] == 1+ logger.info.assert_called_once_with(+ "llma_eval_reports_coordinator_count_triggered_poll",+ extra={+ "reports_found": 1,+ "total_checked": 6,+ "skipped_cooldown": 1,+ "skipped_daily_cap": 1,+ "skipped_not_deliverable": 1,+ },+ )diff --git a/posthog/temporal/ai_observability/eval_reports/types.py b/posthog/temporal/ai_observability/eval_reports/types.pyindex f08ba4bf8ea9..31ab51310b19 100644--- a/posthog/temporal/ai_observability/eval_reports/types.py+++ b/posthog/temporal/ai_observability/eval_reports/types.py@@ -14,6 +14,18 @@ class CheckCountTriggeredReportsWorkflowInputs:pass+class CheckCountTriggeredEvalReportInput:+ report_id: str+++class CheckCountTriggeredEvalReportOutput:+ report_id: str+ due: bool+ skipped_reason: str | None = None++@dataclasses.dataclassclass FetchDueEvalReportsOutput:report_ids: list[str]diff --git a/posthog/temporal/ai_observability/eval_reports/workflow.py b/posthog/temporal/ai_observability/eval_reports/workflow.pyindex 0db75e781c2e..caa41f69cacf 100644--- a/posthog/temporal/ai_observability/eval_reports/workflow.py+++ b/posthog/temporal/ai_observability/eval_reports/workflow.py@@ -12,8 +12,9 @@ from temporalio.common import WorkflowIDReusePolicyfrom temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.temporal.ai_observability.eval_reports.activities import (+ check_count_triggered_eval_report_activity,deliver_report_activity,- fetch_count_triggered_eval_reports_activity,+ fetch_count_triggered_eval_report_candidates_activity,fetch_due_eval_reports_activity,prepare_report_context_activity,run_eval_report_agent_activity,@@ -25,6 +26,8 @@ from posthog.temporal.ai_observability.eval_reports.constants import (AGENT_HEARTBEAT_TIMEOUT,AGENT_RETRY_POLICY,CHECK_COUNT_TRIGGERED_REPORTS_WORKFLOW_NAME,+ COUNT_TRIGGER_CHECK_ACTIVITY_TIMEOUT,+ COUNT_TRIGGER_CHECK_BATCH_SIZE,DELIVER_ACTIVITY_TIMEOUT,DELIVER_HEARTBEAT_TIMEOUT,DELIVER_RETRY_POLICY,@@ -43,7 +46,9 @@ from posthog.temporal.ai_observability.eval_reports.emit_signal import (EmitEvalReportSignalInputs,EmitEvalReportSignalWorkflow,)+from posthog.temporal.ai_observability.eval_reports.metrics import record_coordinator_reports_foundfrom posthog.temporal.ai_observability.eval_reports.types import (+ CheckCountTriggeredEvalReportInput,CheckCountTriggeredReportsWorkflowInputs,DeliverReportInput,GenerateAndDeliverEvalReportWorkflowInput,@@ -113,17 +118,18 @@ class CheckCountTriggeredReportsWorkflow(PostHogWorkflow):@temporalio.workflow.runasync def run(self, inputs: CheckCountTriggeredReportsWorkflowInputs) -> None:result = await temporalio.workflow.execute_activity(- fetch_count_triggered_eval_reports_activity,+ fetch_count_triggered_eval_report_candidates_activity,inputs,start_to_close_timeout=FETCH_ACTIVITY_TIMEOUT,retry_policy=FETCH_RETRY_POLICY,)+ report_ids = await _check_count_triggered_eval_report_candidates(result.report_ids)- if not result.report_ids:+ if not report_ids:returntasks = []- for report_id in result.report_ids:+ for report_id in report_ids:task = temporalio.workflow.execute_child_workflow(GenerateAndDeliverEvalReportWorkflow.run,GenerateAndDeliverEvalReportWorkflowInput(report_id=report_id),@@ -133,7 +139,59 @@ class CheckCountTriggeredReportsWorkflow(PostHogWorkflow):tasks.append(task)results = await asyncio.gather(*tasks, return_exceptions=True)- _log_fan_out_failures("count_triggered_eval_report", result.report_ids, results)+ _log_fan_out_failures("count_triggered_eval_report", report_ids, results)+++async def _check_count_triggered_eval_report_candidates(report_ids: list[str]) -> list[str]:+ due_report_ids: list[str] = []+ failed: list[tuple[str, str]] = []+ skipped_counts = {+ "cooldown": 0,+ "daily_cap": 0,+ "not_deliverable": 0,+ }++ for batch in _batch_report_ids(report_ids, COUNT_TRIGGER_CHECK_BATCH_SIZE):+ tasks = [+ temporalio.workflow.execute_activity(+ check_count_triggered_eval_report_activity,+ CheckCountTriggeredEvalReportInput(report_id=report_id),+ start_to_close_timeout=COUNT_TRIGGER_CHECK_ACTIVITY_TIMEOUT,+ retry_policy=FETCH_RETRY_POLICY,+ )+ for report_id in batch+ ]+ results = await asyncio.gather(*tasks, return_exceptions=True)+ for report_id, result in zip(batch, results):+ if isinstance(result, BaseException):+ failed.append((report_id, f"{type(result).__name__}: {result}"))+ elif result.due:+ due_report_ids.append(result.report_id)+ elif result.skipped_reason is not None:+ skipped_counts[result.skipped_reason] = skipped_counts.get(result.skipped_reason, 0) + 1++ if failed:+ temporalio.workflow.logger.warning(+ "count_triggered_eval_report_check.activity_errors",+ extra={"failed_count": len(failed), "failures": failed},+ )++ temporalio.workflow.logger.info(+ "llma_eval_reports_coordinator_count_triggered_poll",+ extra={+ "reports_found": len(due_report_ids),+ "total_checked": len(report_ids),+ "skipped_cooldown": skipped_counts["cooldown"],+ "skipped_daily_cap": skipped_counts["daily_cap"],+ "skipped_not_deliverable": skipped_counts["not_deliverable"],+ },+ )+ record_coordinator_reports_found(len(due_report_ids), "count_triggered")+ return due_report_ids+++def _batch_report_ids(report_ids: list[str], batch_size: int) -> list[list[str]]:+ return [report_ids[index : index + batch_size] for index in range(0, len(report_ids), batch_size)]def _log_fan_out_failures(kind: str, report_ids: list[str], results: list) -> None:diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex 257e12ca120b..4a5da101a28c 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -337,7 +337,8 @@ class TestAIObservabilityModuleIntegrity:"compute_cluster_aggregates_activity","emit_cluster_events_activity","fetch_due_eval_reports_activity",- "fetch_count_triggered_eval_reports_activity",+ "fetch_count_triggered_eval_report_candidates_activity",+ "check_count_triggered_eval_report_activity","prepare_report_context_activity","run_eval_report_agent_activity","store_report_run_activity",diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportConfig.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportConfig.tsxindex 72abb757fca6..466c3aee263b 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportConfig.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportConfig.tsx@@ -1,6 +1,14 @@import { useActions, useValues } from 'kea'-import { LemonButton, LemonInput, LemonSegmentedButton, LemonSwitch, LemonTag, LemonTextArea } from '@posthog/lemon-ui'+import {+ LemonButton,+ LemonInput,+ LemonSegmentedButton,+ LemonSkeleton,+ LemonSwitch,+ LemonTag,+ LemonTextArea,+} from '@posthog/lemon-ui'import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'import { integrationsLogic } from 'lib/integrations/integrationsLogic'@@ -302,7 +310,13 @@ function ExistingReportConfig({ evaluationId }: { evaluationId: string }): JSX.E/></div>- {activeReport ? (+ {reportsLoading && !activeReport ? (+ <div className="space-y-3 mt-4">+ <LemonSkeleton className="h-9 w-full" />+ <LemonSkeleton className="h-9 w-full" />+ <LemonSkeleton className="h-20 w-full" />+ </div>+ ) : activeReport ? (<><ReportFormFields evaluationId={evaluationId} />{configDraft.frequency === 'every_n'diff --git a/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts b/products/ai_observability/frontend/evaluations/evaluationReportLogic.tsindex b1166ba24be6..0c3f2d7aa52c 100644--- a/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts+++ b/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts@@ -221,12 +221,11 @@ export async function persistReportDraft(activeReport: EvaluationReport | null): Promise<boolean> {const targets = buildDeliveryTargets(draft)- const report = activeReport ?? (await loadReportsForEvaluation(teamId, evaluationId))[0] ?? null- if (report) {+ if (activeReport) {await llmAnalyticsEvaluationReportsPartialUpdate(teamId.toString(),- report.id,- buildReportUpdatePayload(draft, report, targets) as EvaluationReportPatchBody+ activeReport.id,+ buildReportUpdatePayload(draft, activeReport, targets) as EvaluationReportPatchBody)return true}diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.tsindex fb38600b4ed8..1560659a414d 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts@@ -1,3 +1,4 @@+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'@@ -5,8 +6,9 @@ import { initKeaTests } from '~/test/init'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import { EVALUATION_SUMMARY_MAX_RUNS } from './constants'+import { evaluationReportLogic } from './evaluationReportLogic'import { DEFAULT_HOG_SOURCE, DEFAULT_TRACE_HOG_SOURCE, llmEvaluationLogic } from './llmEvaluationLogic'-import { EvaluationConfig, EvaluationRun } from './types'+import { EvaluationConfig, EvaluationReport, EvaluationRun } from './types'const mockProviderKeys: LLMProviderKey[] = [{@@ -88,6 +90,27 @@ const mockEvaluation: EvaluationConfig = {updated_at: '2024-01-01T00:00:00Z',}+const mockEvaluationReport: EvaluationReport = {+ id: 'report-123',+ evaluation: 'eval-123',+ frequency: 'scheduled',+ rrule: 'FREQ=WEEKLY;BYDAY=FR',+ starts_at: '2024-01-01T00:00:00Z',+ timezone_name: 'UTC',+ next_delivery_date: '2024-01-05T00:00:00Z',+ delivery_targets: [{ type: 'email', value: '[email protected]' }],+ max_sample_size: 200,+ enabled: true,+ deleted: false,+ last_delivered_at: null,+ report_prompt_guidance: 'Focus on regressions.',+ trigger_threshold: 500,+ cooldown_minutes: 180,+ daily_run_cap: 8,+ created_by: null,+ created_at: '2024-01-01T00:00:00Z',+}+const mockRuns: EvaluationRun[] = [{id: 'run-1',@@ -1173,6 +1196,72 @@ describe('llmEvaluationLogic', () => {})})+ describe('saveEvaluation report persistence', () => {+ it('does not overwrite a saved report with defaults before the report load finishes', async () => {+ let reportWriteCount = 0+ let reportListRequestCount = 0+ let resolveInitialReports: (value: { results: EvaluationReport[] }) => void = () => {}+ const initialReportsPromise = new Promise<{ results: EvaluationReport[] }>((resolve) => {+ resolveInitialReports = resolve+ })+ let resolveNavigation: () => void = () => {}+ const navigationPromise = new Promise<void>((resolve) => {+ resolveNavigation = resolve+ })+ const pushSpy = jest.spyOn(router.actions, 'push').mockImplementation(() => {+ resolveNavigation()+ })++ useMocks({+ get: {+ '/api/projects/:teamId/llm_analytics/evaluation_reports/': () => {+ reportListRequestCount += 1+ return reportListRequestCount === 1+ ? initialReportsPromise+ : { results: [mockEvaluationReport] }+ },+ },+ patch: {+ '/api/environments/:teamId/evaluations/:id/': () => mockEvaluation,+ '/api/projects/:teamId/llm_analytics/evaluation_reports/:id/': () => {+ reportWriteCount += 1+ return mockEvaluationReport+ },+ },+ post: {+ '/api/projects/:teamId/llm_analytics/evaluation_reports/': () => {+ reportWriteCount += 1+ return mockEvaluationReport+ },+ },+ })++ logic = llmEvaluationLogic({ evaluationId: 'eval-123' })+ const reportLogic = evaluationReportLogic({ evaluationId: 'eval-123' })+ logic.mount()+ reportLogic.mount()++ try {+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])+ expect(reportLogic.values.reportsLoading).toBe(true)+ expect(reportLogic.values.activeReport).toBeNull()++ logic.actions.setEvaluationName('Renamed evaluation')+ logic.actions.saveEvaluation()++ await navigationPromise++ expect(reportListRequestCount).toBe(1)+ expect(reportWriteCount).toBe(0)+ resolveInitialReports({ results: [mockEvaluationReport] })+ await expectLogic(reportLogic).toFinishAllListeners()+ } finally {+ pushSpy.mockRestore()+ reportLogic.unmount()+ }+ })+ })+describe('saveEvaluation failure handling', () => {beforeEach(() => {useMocks({diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.tsindex 79c1f8975265..388616466e07 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts@@ -709,6 +709,13 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([const reportLogicKey = isNew ? 'new' : props.evaluationIdconst reportLogic = evaluationReportLogic({ evaluationId: reportLogicKey })if (response?.id && evaluationSupportsReports(response) && reportLogic.isMounted()) {+ const reportConfigStillLoading =+ !isNew && reportLogic.values.reportsLoading && !reportLogic.values.activeReport+ if (reportConfigStillLoading) {+ router.actions.push(urls.aiObservabilityEvaluations(), router.values.searchParams)+ return+ }+try {await persistReportDraft(teamId,