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.

feat(aio): batch count-triggered eval report checks per team (#71015)

Carlos Marchaldeddf1714f2e
diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.py
index 7eb75dc9f759..ce4e6824d199 100644
--- a/posthog/temporal/ai_observability/__init__.py
+++ b/posthog/temporal/ai_observability/__init__.py
@@ -1,5 +1,6 @@
from posthog.temporal.ai_observability.eval_reports.activities import (
check_count_triggered_eval_report_activity,
+ check_count_triggered_eval_reports_activity,
deliver_report_activity,
fetch_count_triggered_eval_report_candidates_activity,
fetch_due_eval_reports_activity,
@@ -154,6 +155,7 @@ ACTIVITIES = [
fetch_due_eval_reports_activity,
fetch_count_triggered_eval_report_candidates_activity,
check_count_triggered_eval_report_activity,
+ check_count_triggered_eval_reports_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.py
index 810ab96ba8ea..7c9b36c9b017 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -1,7 +1,8 @@
"""Activities for evaluation reports workflow."""
import datetime as dt
-from typing import TYPE_CHECKING
+from collections import defaultdict
+from typing import TYPE_CHECKING, NamedTuple
from zoneinfo import ZoneInfo
import temporalio.activity
@@ -12,6 +13,7 @@ from posthog.hogql import ast
from posthog.clickhouse.client.connection import Workload
from posthog.sync import database_sync_to_async
+from posthog.temporal.ai_observability.eval_reports.constants import COUNT_TRIGGER_QUERY_WIDTH
from posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition
from posthog.temporal.ai_observability.eval_reports.targets import (
GENERATION_TARGET,
@@ -21,6 +23,8 @@ from posthog.temporal.ai_observability.eval_reports.targets import (
from posthog.temporal.ai_observability.eval_reports.types import (
CheckCountTriggeredEvalReportInput,
CheckCountTriggeredEvalReportOutput,
+ CheckCountTriggeredEvalReportsBatchInput,
+ CheckCountTriggeredEvalReportsBatchOutput,
CheckCountTriggeredReportsWorkflowInputs,
DeliverReportInput,
FetchDueEvalReportsOutput,
@@ -36,6 +40,8 @@ from posthog.temporal.ai_observability.eval_reports.types import (
from posthog.temporal.common.heartbeat import Heartbeater
if TYPE_CHECKING:
+ from posthog.models import Team
+
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
logger = get_logger(__name__)
@@ -77,13 +83,15 @@ async def fetch_due_eval_reports_activity(
async def fetch_count_triggered_eval_report_candidates_activity(
inputs: CheckCountTriggeredReportsWorkflowInputs,
) -> FetchDueEvalReportsOutput:
- """Return count-triggered report IDs that need an independent count check."""
+ """Return count-triggered report IDs that need an independent count check, grouped
+ one team per group so each check activity runs a single shared count query."""
@database_sync_to_async(thread_sensitive=False)
- def get_report_ids() -> list[str]:
- return _fetch_count_triggered_eval_report_candidate_ids()
+ def get_report_id_groups() -> list[list[str]]:
+ return _fetch_count_triggered_eval_report_candidate_groups()
- report_ids = await get_report_ids()
+ report_id_groups = await get_report_id_groups()
+ report_ids = [report_id for group in report_id_groups for report_id in group]
await logger.ainfo(
"llma_eval_reports_coordinator_count_triggered_candidates_poll",
total_checked=len(report_ids),
@@ -91,14 +99,18 @@ async def fetch_count_triggered_eval_report_candidates_activity(
from posthog.temporal.ai_observability.eval_reports.metrics import record_coordinator_check_count
record_coordinator_check_count(len(report_ids), "count_triggered")
- return FetchDueEvalReportsOutput(report_ids=report_ids)
+ return FetchDueEvalReportsOutput(report_ids=report_ids, report_id_groups=report_id_groups)
@temporalio.activity.defn
async def check_count_triggered_eval_report_activity(
inputs: CheckCountTriggeredEvalReportInput,
) -> CheckCountTriggeredEvalReportOutput:
- """Check one count-triggered report against its threshold."""
+ """Check one count-triggered report against its threshold.
+
+ Superseded by check_count_triggered_eval_reports_activity (batched). Kept registered
+ so coordinator workflows started before the batched path was deployed can finish.
+ """
@database_sync_to_async(thread_sensitive=False)
def check_report() -> CheckCountTriggeredEvalReportOutput:
@@ -107,27 +119,44 @@ async def check_count_triggered_eval_report_activity(
return await check_report()
-def _fetch_count_triggered_eval_report_candidate_ids() -> list[str]:
+async def check_count_triggered_eval_reports_activity(
+ inputs: CheckCountTriggeredEvalReportsBatchInput,
+) -> CheckCountTriggeredEvalReportsBatchOutput:
+ """Check a batch of count-triggered reports, sharing one ClickHouse query per team."""
+
+ @database_sync_to_async(thread_sensitive=False)
+ def check_reports() -> list[CheckCountTriggeredEvalReportOutput]:
+ return _check_count_triggered_eval_reports_batch(inputs.report_ids)
+
+ results = await check_reports()
+ return CheckCountTriggeredEvalReportsBatchOutput(results=results)
+
+
+def _fetch_count_triggered_eval_report_candidate_groups() -> list[list[str]]:
+ """Return candidate report ids grouped one team per group, each group at most
+ COUNT_TRIGGER_QUERY_WIDTH wide, so one check activity runs exactly one ClickHouse
+ count query under its own timeout and retry policy."""
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
- return [
- str(pk)
- for pk in EvaluationReport.objects.deliverable()
+ ids_by_team: dict[int, list[str]] = defaultdict(list)
+ for pk, team_id in (
+ EvaluationReport.objects.deliverable()
.filter(
frequency=EvaluationReport.Frequency.EVERY_N,
trigger_threshold__isnull=False,
)
- .values_list("id", flat=True)
- ]
+ .order_by("team_id", "id")
+ .values_list("id", "team_id")
+ ):
+ ids_by_team[team_id].append(str(pk))
+ return [chunk for ids in ids_by_team.values() for chunk in _chunk(ids, COUNT_TRIGGER_QUERY_WIDTH)]
-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
+def _load_count_triggered_report(report_id: str) -> "EvaluationReport | None":
+ from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
- report = (
+ return (
EvaluationReport.objects.deliverable()
.filter(
id=report_id,
@@ -137,14 +166,23 @@ def _check_count_triggered_eval_report_sync(
.select_related("evaluation", "team")
.first()
)
- if report is None:
- return CheckCountTriggeredEvalReportOutput(report_id=report_id, due=False, skipped_reason="not_deliverable")
- now = now or dt.datetime.now(tz=dt.UTC)
+
+def _count_triggered_pg_gate(
+ report: "EvaluationReport",
+ now: dt.datetime,
+) -> tuple[str | None, dt.datetime | None]:
+ """Postgres-only eligibility checks shared by the single and batched count paths.
+
+ Returns (skipped_reason, since). When skipped_reason is None the report is eligible
+ for a count check and `since` is the lower bound of its count window.
+ """
+ from products.ai_observability.backend.models.evaluation_reports import EvaluationReportRun
+
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")
+ return "cooldown", None
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
today_runs = EvaluationReportRun.objects.filter(
@@ -152,15 +190,112 @@ def _check_count_triggered_eval_report_sync(
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")
+ return "daily_cap", None
since = report.last_delivered_at or report.starts_at or report.created_at
+ return None, since
+
+
+def _check_count_triggered_eval_report_sync(
+ report_id: str,
+ now: dt.datetime | None = None,
+) -> CheckCountTriggeredEvalReportOutput:
+ report = _load_count_triggered_report(report_id)
+ if report is None:
+ return CheckCountTriggeredEvalReportOutput(report_id=report_id, due=False, skipped_reason="not_deliverable")
+
+ now = now or dt.datetime.now(tz=dt.UTC)
+ skipped_reason, since = _count_triggered_pg_gate(report, now)
+ if skipped_reason is not None:
+ return CheckCountTriggeredEvalReportOutput(report_id=report_id, due=False, skipped_reason=skipped_reason)
+
+ assert since is not None
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 _chunk(items: list, size: int) -> list[list]:
+ return [items[index : index + size] for index in range(0, len(items), size)]
+
+
+def _check_count_triggered_eval_reports_batch(
+ report_ids: list[str],
+ now: dt.datetime | None = None,
+) -> list[CheckCountTriggeredEvalReportOutput]:
+ """Check a group of count-triggered reports, sharing one ClickHouse count query per team.
+
+ The input is normally one team's reports (the fetch activity groups candidates that way),
+ but multi-team input is handled by grouping — one query per team-chunk. The Postgres
+ gating (deliverability, cooldown, daily cap) and the `count >= threshold` decision are
+ identical to the single-report path — only the count query is shared.
+
+ A ClickHouse failure propagates and fails the whole activity, which normally spans just
+ one team's chunk — Temporal retries it under the activity's retry policy.
+ """
+ from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
+
+ now = now or dt.datetime.now(tz=dt.UTC)
+
+ reports = {
+ str(report.id): report
+ for report in EvaluationReport.objects.deliverable()
+ .filter(
+ id__in=report_ids,
+ frequency=EvaluationReport.Frequency.EVERY_N,
+ trigger_threshold__isnull=False,
+ )
+ .select_related("evaluation", "team")
+ }
+
+ outputs: dict[str, CheckCountTriggeredEvalReportOutput] = {}
+ # team_id -> list of (report_id, report, since) for reports that passed the Postgres gate
+ survivors: dict[int, list[tuple[str, EvaluationReport, dt.datetime]]] = defaultdict(list)
+
+ for report_id in report_ids:
+ report = reports.get(report_id)
+ if report is None:
+ outputs[report_id] = CheckCountTriggeredEvalReportOutput(
+ report_id=report_id, due=False, skipped_reason="not_deliverable"
+ )
+ continue
+ skipped_reason, since = _count_triggered_pg_gate(report, now)
+ if skipped_reason is not None:
+ outputs[report_id] = CheckCountTriggeredEvalReportOutput(
+ report_id=report_id, due=False, skipped_reason=skipped_reason
+ )
+ continue
+ assert since is not None
+ survivors[report.team_id].append((report_id, report, since))
+
+ for entries in survivors.values():
+ team = entries[0][1].team
+ # Cap the per-query width so a team with many reports doesn't build one giant query.
+ for chunk in _chunk(entries, COUNT_TRIGGER_QUERY_WIDTH):
+ counts = _count_eval_results_for_reports(
+ team,
+ [
+ _CountEntry(
+ key=report_id,
+ evaluation_id=str(report.evaluation_id),
+ since=since,
+ event_predicate=get_outcome_definition(report.evaluation.output_type).event_predicate,
+ target_predicate=target_event_predicate(report.evaluation.target),
+ )
+ for report_id, report, since in chunk
+ ],
+ )
+ for report_id, report, _since in chunk:
+ assert report.trigger_threshold is not None
+ outputs[report_id] = CheckCountTriggeredEvalReportOutput(
+ report_id=report_id, due=counts.get(report_id, 0) >= report.trigger_threshold
+ )
+
+ # Preserve input order so the workflow's aggregation and logging stay deterministic.
+ return [outputs[report_id] for report_id in report_ids]
+
+
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
@@ -199,6 +334,75 @@ def _count_eval_results_for_report(report: "EvaluationReport", since: dt.datetim
return int(rows[0][0] or 0)
+class _CountEntry(NamedTuple):
+ key: str
+ evaluation_id: str
+ since: dt.datetime
+ event_predicate: str
+ target_predicate: str
+
+
+def _count_eval_results_for_reports(
+ team: "Team",
+ entries: list[_CountEntry],
+) -> dict[str, int]:
+ """Count `$ai_evaluation` events for many reports in a single ClickHouse query.
+
+ We emit one `countIf` column per entry, each carrying the exact per-report predicate
+ (evaluation_id + output-type `event_predicate` + `target_predicate` + `timestamp >=
+ since`), so every count equals what the single-report query would return. The shared
+ WHERE only narrows the scan (its `IN` set and `min(since)` never exclude a row any
+ countIf would have counted). Returns {key: count}.
+ """
+ from posthog.hogql.parser import parse_expr, parse_select
+ from posthog.hogql.query import execute_hogql_query
+
+ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+
+ if not entries:
+ return {}
+
+ # evaluation_id and since go in as ast.Constant placeholders (no interpolation to audit);
+ # `since` stays a datetime so HogQL prints toDateTime64(..., 6, <team_tz>) — a bare string
+ # would shift by the team's offset. The predicates are trusted internal output-type and
+ # target definitions (never user input), interpolated to match the single-report query
+ # exactly. Columns are read positionally below, so no aliases are needed.
+ select_columns: list[ast.Expr] = [
+ # nosemgrep: hogql-fstring-audit (the predicates come from fixed internal definitions)
+ parse_expr(
+ f"countIf(properties.$ai_evaluation_id = {{evaluation_id}}"
+ f" AND {entry.event_predicate} AND {entry.target_predicate} AND timestamp >= {{since}})",
+ placeholders={
+ "evaluation_id": ast.Constant(value=entry.evaluation_id),
+ "since": ast.Constant(value=entry.since),
+ },
+ )
+ for entry in entries
+ ]
+
+ unique_evaluation_ids = list(dict.fromkeys(entry.evaluation_id for entry in entries))
+ query = parse_select(
+ "SELECT 1 FROM events WHERE event = '$ai_evaluation' "
+ "AND properties.$ai_evaluation_id IN {evaluation_ids} AND timestamp >= {min_since}",
+ placeholders={
+ "evaluation_ids": ast.Tuple(exprs=[ast.Constant(value=e) for e in unique_evaluation_ids]),
+ "min_since": ast.Constant(value=min(entry.since for entry in entries)),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ # Replace the placeholder projection with the per-entry count columns.
+ query.select = select_columns
+
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.ENRICHMENT, team_id=team.pk):
+ result = execute_hogql_query(query=query, team=team, workload=Workload.OFFLINE)
+
+ rows = result.results or []
+ if not rows:
+ return {entry.key: 0 for entry in entries}
+ row = rows[0]
+ return {entries[index].key: int(row[index] or 0) for index in range(len(entries))}
+
+
def _find_nth_eval_timestamp(
team_id: int,
evaluation_id: str,
diff --git a/posthog/temporal/ai_observability/eval_reports/constants.py b/posthog/temporal/ai_observability/eval_reports/constants.py
index 142947120da8..0124a25918f3 100644
--- a/posthog/temporal/ai_observability/eval_reports/constants.py
+++ b/posthog/temporal/ai_observability/eval_reports/constants.py
@@ -24,6 +24,12 @@ COORDINATOR_EXECUTION_TIMEOUT = timedelta(hours=2)
# Activity timeouts
FETCH_ACTIVITY_TIMEOUT = timedelta(seconds=60)
COUNT_TRIGGER_CHECK_BATCH_SIZE = 5
+# Max number of per-report countIf columns in a single ClickHouse count query. Candidates
+# are grouped one team per group at this width, so one check activity runs exactly one query.
+COUNT_TRIGGER_QUERY_WIDTH = 100
+# Max batched check activities in flight at once, capping concurrent count queries at the
+# same ceiling as the legacy per-report path.
+COUNT_TRIGGER_MAX_CONCURRENT_CHECKS = 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)
diff --git a/posthog/temporal/ai_observability/eval_reports/metrics.py b/posthog/temporal/ai_observability/eval_reports/metrics.py
index 02b3afa072bc..837c350ede65 100644
--- a/posthog/temporal/ai_observability/eval_reports/metrics.py
+++ b/posthog/temporal/ai_observability/eval_reports/metrics.py
@@ -51,6 +51,7 @@ EVAL_REPORTS_ACTIVITY_TYPES = {
"fetch_due_eval_reports_activity",
"fetch_count_triggered_eval_report_candidates_activity",
"check_count_triggered_eval_report_activity",
+ "check_count_triggered_eval_reports_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.py
index 526404ff3fb4..66cc5a2c7c7f 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -2,15 +2,17 @@ import datetime as dt
from contextlib import asynccontextmanager
import pytest
-from posthog.test.base import BaseTest
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event
from unittest.mock import MagicMock, Mock, patch
from django.utils import timezone
+from posthog.models import Team
from posthog.temporal.ai_observability.eval_reports.activities import (
_check_count_triggered_eval_report_sync,
+ _check_count_triggered_eval_reports_batch,
_count_eval_results_for_report,
- _fetch_count_triggered_eval_report_candidate_ids,
+ _fetch_count_triggered_eval_report_candidate_groups,
_find_nth_eval_timestamp,
_load_evaluation_target,
_period_for_scheduled_report,
@@ -356,9 +358,10 @@ class TestPrepareReportContext(BaseTest):
class TestCountTriggeredReportChecks(BaseTest):
- def _create_report(self, **kwargs) -> EvaluationReport:
+ def _create_report(self, team: Team | None = None, **kwargs) -> EvaluationReport:
+ team = team or self.team
evaluation = Evaluation.objects.create(
- team=self.team,
+ team=team,
name="Test Eval",
evaluation_type="llm_judge",
evaluation_config={"prompt": "test prompt"},
@@ -369,7 +372,7 @@ class TestCountTriggeredReportChecks(BaseTest):
conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],
)
defaults = {
- "team": self.team,
+ "team": team,
"evaluation": evaluation,
"frequency": EvaluationReport.Frequency.EVERY_N,
"rrule": "",
@@ -390,11 +393,23 @@ class TestCountTriggeredReportChecks(BaseTest):
)
with patch("posthog.hogql.query.execute_hogql_query") as execute_hogql_query:
- report_ids = _fetch_count_triggered_eval_report_candidate_ids()
+ groups = _fetch_count_triggered_eval_report_candidate_groups()
- self.assertEqual(report_ids, [str(count_triggered_report.id)])
+ self.assertEqual(groups, [[str(count_triggered_report.id)]])
execute_hogql_query.assert_not_called()
+ def test_fetch_candidates_groups_by_team_and_chunks_by_width(self):
+ # One check activity handles one group, so a group must never span teams (its counts
+ # would run against the wrong team's data) nor exceed the per-query width cap.
+ team_a_report_ids = sorted(str(self._create_report().id) for _ in range(3))
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ team_b_report = self._create_report(team=other_team)
+
+ with patch("posthog.temporal.ai_observability.eval_reports.activities.COUNT_TRIGGER_QUERY_WIDTH", 2):
+ groups = _fetch_count_triggered_eval_report_candidate_groups()
+
+ self.assertEqual(groups, [team_a_report_ids[:2], team_a_report_ids[2:], [str(team_b_report.id)]])
+
def test_check_report_returns_due_when_threshold_is_crossed(self):
report = self._create_report(trigger_threshold=100)
@@ -436,6 +451,28 @@ class TestCountTriggeredReportChecks(BaseTest):
self.assertEqual(result.skipped_reason, "daily_cap")
execute_hogql_query.assert_not_called()
+ 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).
+ now = timezone.now()
+ not_deliverable = self._create_report(enabled=False)
+ cooldown = self._create_report(last_delivered_at=now - dt.timedelta(minutes=5), cooldown_minutes=60)
+ daily_cap = self._create_report(daily_run_cap=1)
+ EvaluationReportRun.objects.create(
+ report=daily_cap,
+ period_start=now - dt.timedelta(hours=1),
+ period_end=now,
+ )
+
+ report_ids = [str(not_deliverable.id), str(cooldown.id), str(daily_cap.id)]
+ with patch("posthog.hogql.query.execute_hogql_query") as execute_hogql_query:
+ results = _check_count_triggered_eval_reports_batch(report_ids, now)
+
+ execute_hogql_query.assert_not_called()
+ self.assertEqual([r.report_id for r in results], report_ids)
+ self.assertEqual([r.skipped_reason for r in results], ["not_deliverable", "cooldown", "daily_cap"])
+ self.assertTrue(all(r.due is False for r in results))
+
class TestPeriodForScheduledReport(BaseTest):
"""Unit-ish tests for the rrule period helper — uses in-memory instances to
@@ -490,3 +527,211 @@ class TestPeriodForScheduledReport(BaseTest):
now = dt.datetime(2026, 3, 8, 18, 0, tzinfo=dt.UTC) # 14:00 EDT, after 9am EDT fire
period = _period_for_scheduled_report(report, now)
self.assertEqual(period, dt.timedelta(hours=23))
+
+
+class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
+ """Exercises the batched count check against real ClickHouse events — no query mocking —
+ so it guards the properties Carlos cares about: each report's count is identical to the
+ single-report query (right evaluation, right `since` window, right threshold)."""
+
+ # Window anchor; reports use this as `since` (via last_delivered_at) unless overridden.
+ T0 = dt.datetime(2026, 6, 1, 9, 0, tzinfo=dt.UTC)
+ NOW = dt.datetime(2026, 6, 1, 12, 0, tzinfo=dt.UTC)
+
+ def _create_report(
+ self,
+ team: Team,
+ *,
+ threshold: int,
+ since: dt.datetime,
+ name: str,
+ output_type: str = "boolean",
+ target: str = "generation",
+ ) -> EvaluationReport:
+ if output_type == "sentiment":
+ evaluation_type, evaluation_config = "sentiment", {"source": "user_messages"}
+ else:
+ evaluation_type, evaluation_config = "llm_judge", {"prompt": "test prompt"}
+ evaluation = Evaluation.objects.create(
+ team=team,
+ name=name,
+ evaluation_type=evaluation_type,
+ evaluation_config=evaluation_config,
+ output_type=output_type,
+ output_config={},
+ target=target,
+ enabled=True,
+ conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],
+ )
+ return EvaluationReport.objects.create(
+ team=team,
+ evaluation=evaluation,
+ frequency=EvaluationReport.Frequency.EVERY_N,
+ rrule="",
+ starts_at=None,
+ trigger_threshold=threshold,
+ # since = last_delivered_at; cooldown default is 60min and NOW is 3h later, so it passes.
+ last_delivered_at=since,
+ delivery_targets=[{"type": "email", "value": "[email protected]"}],
+ )
+
+ def _emit_eval_events(self, team: Team, evaluation_id: str, timestamps: list[dt.datetime]) -> None:
+ for index, ts in enumerate(timestamps):
+ _create_event(
+ team=team,
+ event="$ai_evaluation",
+ distinct_id=f"d-{evaluation_id}-{index}",
+ timestamp=ts,
+ properties={"$ai_evaluation_id": evaluation_id},
+ )
+
+ def test_counts_respect_since_evaluation_and_threshold(self):
+ # A: 2 events in-window (threshold 2) -> due. One event before `since` must be excluded.
+ report_a = self._create_report(self.team, threshold=2, since=self.T0, name="A")
+ self._emit_eval_events(
+ self.team,
+ str(report_a.evaluation_id),
+ [self.T0 - dt.timedelta(hours=1), self.T0 + dt.timedelta(hours=1), self.T0 + dt.timedelta(hours=2)],
+ )
+ # B: same window as A but threshold 5 with only 2 events -> not due. Guards against
+ # B's count picking up A's events (evaluation isolation).
+ report_b = self._create_report(self.team, threshold=5, since=self.T0, name="B")
+ self._emit_eval_events(
+ self.team,
+ str(report_b.evaluation_id),
+ [self.T0 + dt.timedelta(hours=1), self.T0 + dt.timedelta(hours=2)],
+ )
+ # C: later `since` (11:00) than A/B — its only event (10:00) predates its window, so 0 -> not due.
+ # This proves each report applies its OWN since, not a shared one.
+ report_c = self._create_report(self.team, threshold=1, since=self.T0 + dt.timedelta(hours=2), name="C")
+ self._emit_eval_events(self.team, str(report_c.evaluation_id), [self.T0 + dt.timedelta(hours=1)])
+
+ report_ids = [str(report_a.id), str(report_b.id), str(report_c.id)]
+ results = _check_count_triggered_eval_reports_batch(report_ids, self.NOW)
+
+ due_by_id = {r.report_id: r.due for r in results}
+ self.assertEqual([r.report_id for r in results], report_ids)
+ self.assertTrue(due_by_id[str(report_a.id)])
+ self.assertFalse(due_by_id[str(report_b.id)])
+ self.assertFalse(due_by_id[str(report_c.id)])
+
+ def test_counts_are_scoped_per_team(self):
+ # One report per team, each with a single in-window event and threshold 1. If the batch
+ # ran both against one team's data, the other team's report would count 0 and be not-due.
+ report_a = self._create_report(self.team, threshold=1, since=self.T0, name="team1")
+ self._emit_eval_events(self.team, str(report_a.evaluation_id), [self.T0 + dt.timedelta(hours=1)])
+
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ report_b = self._create_report(other_team, threshold=1, since=self.T0, name="team2")
+ self._emit_eval_events(other_team, str(report_b.evaluation_id), [self.T0 + dt.timedelta(hours=1)])
+
+ results = _check_count_triggered_eval_reports_batch([str(report_a.id), str(report_b.id)], self.NOW)
+
+ due_by_id = {r.report_id: r.due for r in results}
+ self.assertTrue(due_by_id[str(report_a.id)])
+ self.assertTrue(due_by_id[str(report_b.id)])
+
+ def test_width_chunking_returns_all_counts(self):
+ # Force one countIf column per query so the per-team entries span multiple chunks;
+ # a chunk-merge bug (dropped/overwritten counts) would leave some report not-due.
+ reports = [self._create_report(self.team, threshold=1, since=self.T0, name=f"r{i}") for i in range(3)]
+ for report in reports:
+ self._emit_eval_events(self.team, str(report.evaluation_id), [self.T0 + dt.timedelta(hours=1)])
+
+ report_ids = [str(report.id) for report in reports]
+ with patch("posthog.temporal.ai_observability.eval_reports.activities.COUNT_TRIGGER_QUERY_WIDTH", 1):
+ results = _check_count_triggered_eval_reports_batch(report_ids, self.NOW)
+
+ self.assertEqual([r.report_id for r in results], report_ids)
+ self.assertTrue(all(r.due for r in results))
+
+ def test_sentiment_reports_are_checked_with_their_own_predicate(self):
+ # The loader must not restrict to boolean output types — a count-triggered sentiment
+ # report would silently resolve not_deliverable forever — and sentiment events must be
+ # counted with the sentiment predicate, not the boolean one.
+ boolean_report = self._create_report(self.team, threshold=1, since=self.T0, name="bool")
+ self._emit_eval_events(self.team, str(boolean_report.evaluation_id), [self.T0 + dt.timedelta(hours=1)])
+
+ sentiment_report = self._create_report(
+ self.team, threshold=2, since=self.T0, name="sent", output_type="sentiment"
+ )
+ for index, ts in enumerate([self.T0 + dt.timedelta(hours=1), self.T0 + dt.timedelta(hours=2)]):
+ _create_event(
+ team=self.team,
+ event="$ai_evaluation",
+ distinct_id=f"sent-{index}",
+ timestamp=ts,
+ properties={
+ "$ai_evaluation_id": str(sentiment_report.evaluation_id),
+ "$ai_evaluation_result_type": "sentiment",
+ "$ai_sentiment_label": "negative",
+ },
+ )
+
+ results = _check_count_triggered_eval_reports_batch(
+ [str(boolean_report.id), str(sentiment_report.id)], self.NOW
+ )
+
+ by_id = {r.report_id: r for r in results}
+ self.assertIsNone(by_id[str(sentiment_report.id)].skipped_reason)
+ self.assertTrue(by_id[str(sentiment_report.id)].due)
+ self.assertTrue(by_id[str(boolean_report.id)].due)
+
+ def test_trace_target_reports_exclude_generation_events(self):
+ # The batched countIf must carry the evaluation's target predicate like the
+ # single-report query does: after an evaluation switches to the trace target,
+ # stale generation-target events must not keep counting toward the threshold.
+ switched = self._create_report(self.team, threshold=2, since=self.T0, name="switched", target="trace")
+ for index, (ts, target_type) in enumerate(
+ [
+ # Two generation-shaped events (tagged + untagged legacy) and one trace event:
+ # counting the generation ones would wrongly cross the threshold of 2.
+ (self.T0 + dt.timedelta(hours=1), "generation_uuid"),
+ (self.T0 + dt.timedelta(minutes=90), None),
+ (self.T0 + dt.timedelta(hours=2), "trace_id"),
+ ]
+ ):
+ properties = {"$ai_evaluation_id": str(switched.evaluation_id)}
+ if target_type is not None:
+ properties["$ai_target_type"] = target_type
+ _create_event(
+ team=self.team,
+ event="$ai_evaluation",
+ distinct_id=f"switched-{index}",
+ timestamp=ts,
+ properties=properties,
+ )
+
+ # Trace events must still count for a trace report (the predicate isn't over-strict).
+ trace_only = self._create_report(self.team, threshold=1, since=self.T0, name="trace-only", target="trace")
+ _create_event(
+ team=self.team,
+ event="$ai_evaluation",
+ distinct_id="trace-only-0",
+ timestamp=self.T0 + dt.timedelta(hours=1),
+ properties={"$ai_evaluation_id": str(trace_only.evaluation_id), "$ai_target_type": "trace_id"},
+ )
+
+ results = _check_count_triggered_eval_reports_batch([str(switched.id), str(trace_only.id)], self.NOW)
+
+ by_id = {r.report_id: r for r in results}
+ self.assertFalse(by_id[str(switched.id)].due)
+ self.assertTrue(by_id[str(trace_only.id)].due)
+
+ def test_since_boundary_respects_non_utc_team_timezone(self):
+ # `since` is passed as an ast.Constant datetime so ClickHouse compares the same absolute
+ # instant whatever the team's timezone. If it were serialized as a bare string it would be
+ # read in the team's tz (America/New_York, -4h in June) and shift the boundary. Events sit
+ # an hour either side of `since`, so the ~4h shift a string would cause flips the result.
+ ny_team = Team.objects.create(organization=self.organization, name="ny", timezone="America/New_York")
+ report = self._create_report(ny_team, threshold=1, since=self.NOW, name="ny")
+ self._emit_eval_events(
+ ny_team,
+ str(report.evaluation_id),
+ [self.NOW - dt.timedelta(hours=1), self.NOW + dt.timedelta(hours=1)],
+ )
+
+ results = _check_count_triggered_eval_reports_batch([str(report.id)], self.NOW + dt.timedelta(hours=2))
+
+ # Only the event after `since` is counted: exactly 1, meeting the threshold of 1.
+ self.assertTrue(results[0].due)
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 ce32fbe126f6..09cde955b908 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
@@ -1,8 +1,11 @@
+import asyncio
+
import pytest
from unittest.mock import patch
from posthog.temporal.ai_observability.eval_reports.types import (
CheckCountTriggeredEvalReportOutput,
+ CheckCountTriggeredEvalReportsBatchOutput,
GenerateAndDeliverEvalReportWorkflowInput,
PrepareReportContextOutput,
RunEvalReportAgentInput,
@@ -12,6 +15,7 @@ from posthog.temporal.ai_observability.eval_reports.types import (
from posthog.temporal.ai_observability.eval_reports.workflow import (
GenerateAndDeliverEvalReportWorkflow,
_check_count_triggered_eval_report_candidates,
+ _check_count_triggered_eval_report_candidates_batched,
)
@@ -114,3 +118,81 @@ async def test_count_triggered_report_check_continues_after_activity_failure() -
"skipped_not_deliverable": 1,
},
)
+
+
+async def test_batched_count_check_aggregates_across_groups_and_isolates_group_failure() -> None:
+ # One failing group activity must not sink the others: every report in it is recorded as
+ # failed, while due/skipped reports from the surviving groups still aggregate correctly.
+ async def fake_execute_activity(_activity, inputs, **_kwargs):
+ if any(report_id.startswith("boom") for report_id in inputs.report_ids):
+ raise RuntimeError("clickhouse at capacity")
+ return CheckCountTriggeredEvalReportsBatchOutput(
+ results=[
+ CheckCountTriggeredEvalReportOutput(
+ report_id=report_id,
+ due=report_id == "due",
+ skipped_reason="cooldown" if report_id == "skip" else None,
+ )
+ for report_id in inputs.report_ids
+ ]
+ )
+
+ 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_batched([["due", "skip"], ["boom1", "boom2"]])
+
+ assert report_ids == ["due"]
+ record.assert_called_once_with(1, "count_triggered")
+ logger.warning.assert_called_once()
+ assert logger.warning.call_args.kwargs["extra"]["failed_count"] == 2
+ logger.info.assert_called_once_with(
+ "llma_eval_reports_coordinator_count_triggered_poll",
+ extra={
+ "reports_found": 1,
+ "total_checked": 4,
+ "skipped_cooldown": 1,
+ "skipped_daily_cap": 0,
+ "skipped_not_deliverable": 0,
+ },
+ )
+
+
+async def test_batched_count_check_caps_concurrent_group_activities() -> None:
+ # The window must keep at most COUNT_TRIGGER_MAX_CONCURRENT_CHECKS count queries in
+ # flight; losing it would fire every team's query at once — the exact ClickHouse
+ # capacity pressure this path exists to avoid.
+ active = 0
+ max_active = 0
+
+ async def fake_execute_activity(_activity, inputs, **_kwargs):
+ nonlocal active, max_active
+ active += 1
+ max_active = max(max_active, active)
+ await asyncio.sleep(0)
+ active -= 1
+ return CheckCountTriggeredEvalReportsBatchOutput(
+ results=[
+ CheckCountTriggeredEvalReportOutput(report_id=report_id, due=False) for report_id in inputs.report_ids
+ ]
+ )
+
+ 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.COUNT_TRIGGER_MAX_CONCURRENT_CHECKS", 2),
+ patch("posthog.temporal.ai_observability.eval_reports.workflow.record_coordinator_reports_found"),
+ patch("posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.logger"),
+ ):
+ await _check_count_triggered_eval_report_candidates_batched([[f"report-{index}"] for index in range(5)])
+
+ assert max_active == 2
diff --git a/posthog/temporal/ai_observability/eval_reports/types.py b/posthog/temporal/ai_observability/eval_reports/types.py
index d19389e2d777..7aaffe4f19a4 100644
--- a/posthog/temporal/ai_observability/eval_reports/types.py
+++ b/posthog/temporal/ai_observability/eval_reports/types.py
@@ -26,9 +26,23 @@ class CheckCountTriggeredEvalReportOutput:
skipped_reason: str | None = None
+class CheckCountTriggeredEvalReportsBatchInput:
+ report_ids: list[str]
+
+
+class CheckCountTriggeredEvalReportsBatchOutput:
+ results: list[CheckCountTriggeredEvalReportOutput]
+
+
@dataclasses.dataclass
class FetchDueEvalReportsOutput:
report_ids: list[str]
+ # Count-triggered candidates grouped one team per group, each group at most
+ # COUNT_TRIGGER_QUERY_WIDTH wide. None when emitted by a pre-batching worker;
+ # the workflow then keeps the legacy per-report path.
+ report_id_groups: list[list[str]] | 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 986edb1eb754..fe224675b9e7 100644
--- a/posthog/temporal/ai_observability/eval_reports/workflow.py
+++ b/posthog/temporal/ai_observability/eval_reports/workflow.py
@@ -13,6 +13,7 @@ from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.temporal.ai_observability.eval_reports.activities import (
check_count_triggered_eval_report_activity,
+ check_count_triggered_eval_reports_activity,
deliver_report_activity,
fetch_count_triggered_eval_report_candidates_activity,
fetch_due_eval_reports_activity,
@@ -28,6 +29,7 @@ from posthog.temporal.ai_observability.eval_reports.constants import (
CHECK_COUNT_TRIGGERED_REPORTS_WORKFLOW_NAME,
COUNT_TRIGGER_CHECK_ACTIVITY_TIMEOUT,
COUNT_TRIGGER_CHECK_BATCH_SIZE,
+ COUNT_TRIGGER_MAX_CONCURRENT_CHECKS,
DELIVER_ACTIVITY_TIMEOUT,
DELIVER_HEARTBEAT_TIMEOUT,
DELIVER_RETRY_POLICY,
@@ -49,6 +51,7 @@ from posthog.temporal.ai_observability.eval_reports.emit_signal import (
from posthog.temporal.ai_observability.eval_reports.metrics import record_coordinator_reports_found
from posthog.temporal.ai_observability.eval_reports.types import (
CheckCountTriggeredEvalReportInput,
+ CheckCountTriggeredEvalReportsBatchInput,
CheckCountTriggeredReportsWorkflowInputs,
DeliverReportInput,
GenerateAndDeliverEvalReportWorkflowInput,
@@ -123,7 +126,15 @@ class CheckCountTriggeredReportsWorkflow(PostHogWorkflow):
start_to_close_timeout=FETCH_ACTIVITY_TIMEOUT,
retry_policy=FETCH_RETRY_POLICY,
)
- report_ids = await _check_count_triggered_eval_report_candidates(result.report_ids)
+ # Batched path: one check activity per team-group, each sharing one ClickHouse
+ # count query, instead of one activity per report. Gated on the fetch output so
+ # the decision is replay-deterministic: histories recorded before batching (and
+ # fetch results produced by a pre-batching worker mid-deploy) decode
+ # report_id_groups as None and keep their per-report command sequence.
+ if result.report_id_groups is not None:
+ report_ids = await _check_count_triggered_eval_report_candidates_batched(result.report_id_groups)
+ else:
+ report_ids = await _check_count_triggered_eval_report_candidates(result.report_ids)
if not report_ids:
return
@@ -190,6 +201,64 @@ async def _check_count_triggered_eval_report_candidates(report_ids: list[str]) -
return due_report_ids
+async def _check_count_triggered_eval_report_candidates_batched(report_id_groups: list[list[str]]) -> list[str]:
+ due_report_ids: list[str] = []
+ failed: list[tuple[str, str]] = []
+ skipped_counts = {
+ "cooldown": 0,
+ "daily_cap": 0,
+ "not_deliverable": 0,
+ }
+
+ # Each group holds one team's reports capped at COUNT_TRIGGER_QUERY_WIDTH, so one
+ # activity runs one count query under its own timeout and Temporal retry policy, and
+ # a ClickHouse failure is contained to that group. The window keeps at most
+ # COUNT_TRIGGER_MAX_CONCURRENT_CHECKS count queries in flight — the legacy path's ceiling.
+ for index in range(0, len(report_id_groups), COUNT_TRIGGER_MAX_CONCURRENT_CHECKS):
+ window = report_id_groups[index : index + COUNT_TRIGGER_MAX_CONCURRENT_CHECKS]
+ tasks = [
+ temporalio.workflow.execute_activity(
+ check_count_triggered_eval_reports_activity,
+ CheckCountTriggeredEvalReportsBatchInput(report_ids=group),
+ start_to_close_timeout=COUNT_TRIGGER_CHECK_ACTIVITY_TIMEOUT,
+ retry_policy=FETCH_RETRY_POLICY,
+ )
+ for group in window
+ ]
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+ for group, group_result in zip(window, results):
+ if isinstance(group_result, BaseException):
+ # A group's activity exhausted its retries — attribute every report in it so
+ # the failure is visible, while other groups still contribute their results.
+ for report_id in group:
+ failed.append((report_id, f"{type(group_result).__name__}: {group_result}"))
+ continue
+ for output in group_result.results:
+ if output.due:
+ due_report_ids.append(output.report_id)
+ elif output.skipped_reason is not None:
+ skipped_counts[output.skipped_reason] = skipped_counts.get(output.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": sum(len(group) for group in report_id_groups),
+ "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)]
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index 4a5da101a28c..47fdc406dce5 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -339,6 +339,7 @@ class TestAIObservabilityModuleIntegrity:
"fetch_due_eval_reports_activity",
"fetch_count_triggered_eval_report_candidates_activity",
"check_count_triggered_eval_report_activity",
+ "check_count_triggered_eval_reports_activity",
"prepare_report_context_activity",
"run_eval_report_agent_activity",
"store_report_run_activity",