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): stop batched eval-report count queries from racing their timeout (#76183)

posthog[bot]be52ef2f261d
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 69a4544a1f08..48817d72c2d4 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -1,5 +1,6 @@
"""Activities for evaluation reports workflow."""
+import time
import datetime as dt
from collections import defaultdict
from typing import TYPE_CHECKING, NamedTuple
@@ -14,8 +15,14 @@ from structlog import get_logger
from posthog.hogql import ast
from posthog.clickhouse.client.connection import Workload
+from posthog.exceptions import ClickHouseQueryTimeOut
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.constants import (
+ COUNT_TRIGGER_QUERY_MAX_EXECUTION_TIME_SECONDS,
+ COUNT_TRIGGER_QUERY_MIN_EXECUTION_TIME_SECONDS,
+ COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS,
+ 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,
@@ -273,11 +280,15 @@ def _check_count_triggered_eval_reports_batch(
assert since is not None
survivors[report.team_id].append((report_id, report, since))
+ deadline = time.monotonic() + COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS
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.
+ # Sort by `since` before capping the per-query width, so entries sharing a chunk
+ # have a comparable window — one stale report no longer sets the scan's lower
+ # bound for every other report queued alongside it.
+ entries.sort(key=lambda entry: entry[2])
for chunk in _chunk(entries, COUNT_TRIGGER_QUERY_WIDTH):
- counts = _count_eval_results_for_reports(
+ counts = _count_eval_results_for_reports_with_split_retry(
team,
[
_CountEntry(
@@ -289,6 +300,8 @@ def _check_count_triggered_eval_reports_batch(
)
for report_id, report, since in chunk
],
+ until=now,
+ deadline=deadline,
)
for report_id, report, _since in chunk:
assert report.trigger_threshold is not None
@@ -349,15 +362,18 @@ class _CountEntry(NamedTuple):
def _count_eval_results_for_reports(
team: "Team",
entries: list[_CountEntry],
+ until: dt.datetime,
+ max_execution_time: int,
) -> 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}.
+ WHERE only narrows the scan (its `IN` set, `min(since)`, and `until` upper bound never
+ exclude a row any countIf would have counted). Returns {key: count}.
"""
+ from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.query import execute_hogql_query
@@ -387,10 +403,12 @@ def _count_eval_results_for_reports(
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}",
+ "AND properties.$ai_evaluation_id IN {evaluation_ids} "
+ "AND timestamp >= {min_since} AND timestamp <= {until}",
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)),
+ "until": ast.Constant(value=until),
},
)
assert isinstance(query, ast.SelectQuery)
@@ -398,7 +416,12 @@ def _count_eval_results_for_reports(
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)
+ result = execute_hogql_query(
+ query=query,
+ team=team,
+ workload=Workload.OFFLINE,
+ settings=HogQLGlobalSettings(max_execution_time=max_execution_time),
+ )
rows = result.results or []
if not rows:
@@ -407,6 +430,45 @@ def _count_eval_results_for_reports(
return {entries[index].key: int(row[index] or 0) for index in range(len(entries))}
+def _count_eval_results_for_reports_with_split_retry(
+ team: "Team",
+ entries: list[_CountEntry],
+ until: dt.datetime,
+ deadline: float | None = None,
+) -> dict[str, int]:
+ """Run the batched count query, halving the chunk and retrying narrower if ClickHouse
+ can't finish it inside its own execution-time budget.
+
+ A `ClickHouseQueryTimeOut` on a width-N query means N countIf columns over that team's
+ event volume don't fit the budget — replaying the identical query would just time out
+ again. Splitting also narrows each half's own `since`-sorted window independently.
+
+ Every attempt draws on one shared wall-clock budget (`deadline`, in `time.monotonic()`
+ seconds), capping its own execution time by what remains, so the whole split tree
+ concludes before the activity's own timeout. Once the remainder can't fund a meaningful
+ query, the timeout surfaces and the activity fails cleanly instead of being killed
+ mid-split by Temporal.
+ """
+ if deadline is None:
+ deadline = time.monotonic() + COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS
+ budget = min(COUNT_TRIGGER_QUERY_MAX_EXECUTION_TIME_SECONDS, int(deadline - time.monotonic()))
+ if budget < COUNT_TRIGGER_QUERY_MIN_EXECUTION_TIME_SECONDS:
+ raise ClickHouseQueryTimeOut("Count query budget exhausted before the split could finish.")
+ try:
+ return _count_eval_results_for_reports(team, entries, until=until, max_execution_time=budget)
+ except ClickHouseQueryTimeOut:
+ if len(entries) == 1:
+ raise
+ midpoint = len(entries) // 2
+ counts = _count_eval_results_for_reports_with_split_retry(
+ team, entries[:midpoint], until=until, deadline=deadline
+ )
+ counts.update(
+ _count_eval_results_for_reports_with_split_retry(team, entries[midpoint:], until=until, deadline=deadline)
+ )
+ return counts
+
+
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 0124a25918f3..687206aab813 100644
--- a/posthog/temporal/ai_observability/eval_reports/constants.py
+++ b/posthog/temporal/ai_observability/eval_reports/constants.py
@@ -25,12 +25,28 @@ COORDINATOR_EXECUTION_TIMEOUT = timedelta(hours=2)
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
+# are grouped one team per group at this width, so one check activity runs exactly one query,
+# and entries are chunked in `since`-sorted order so one stale report's window doesn't widen
+# the scan for its neighbors. Kept well below the activity/query time budget so a chunk this
+# wide, on a team's worst-case event volume, still finishes comfortably inside it.
+COUNT_TRIGGER_QUERY_WIDTH = 20
# 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)
+COUNT_TRIGGER_CHECK_ACTIVITY_TIMEOUT = timedelta(seconds=120)
+# Per-attempt ClickHouse budget. A too-slow count query fails with a catchable
+# ClickHouseQueryTimeOut the activity can split-and-retry, unlike a Temporal activity
+# timeout, which kills the split midway and replays the same sequence on every retry.
+COUNT_TRIGGER_QUERY_MAX_EXECUTION_TIME_SECONDS = 30
+# Wall-clock budget shared by all of one activity's count queries, split retries included.
+# Sized so a complete first-level split (a full-width timeout, then both halves running to
+# their full per-attempt budget) fits, and kept below COUNT_TRIGGER_CHECK_ACTIVITY_TIMEOUT
+# with headroom for the Postgres gate and per-query overhead, so the split tree always
+# concludes inside the activity instead of racing its timeout.
+COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS = 90
+# With less remaining budget than this a retry can't do useful work (and a zero budget would
+# mean "unlimited" to ClickHouse), so the split re-raises the timeout instead of querying.
+COUNT_TRIGGER_QUERY_MIN_EXECUTION_TIME_SECONDS = 5
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/test/test_activities.py b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
index c9b858e0749f..125381ed13ac 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -10,11 +10,14 @@ from django.utils import timezone
from parameterized import parameterized
+from posthog.exceptions import ClickHouseQueryTimeOut
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,
+ _count_eval_results_for_reports_with_split_retry,
+ _CountEntry,
_fetch_count_triggered_eval_report_candidate_groups,
_find_nth_eval_timestamp,
_load_evaluation_target,
@@ -23,6 +26,10 @@ from posthog.temporal.ai_observability.eval_reports.activities import (
run_eval_report_agent_activity,
store_report_run_activity,
)
+from posthog.temporal.ai_observability.eval_reports.constants import (
+ COUNT_TRIGGER_QUERY_MIN_EXECUTION_TIME_SECONDS,
+ COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS,
+)
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import EvalReportContent, EvalReportMetrics
from posthog.temporal.ai_observability.eval_reports.targets import target_event_predicate
from posthog.temporal.ai_observability.eval_reports.types import (
@@ -635,6 +642,60 @@ class TestCountTriggeredReportChecks(BaseTest):
self.assertTrue(all(r.due is False for r in results))
+class TestCountEvalResultsForReportsSplitRetry(BaseTest):
+ """Guards the retry behavior a `ClickHouseQueryTimeOut` needs: split the chunk and
+ retry narrower, rather than replaying the identical too-wide query."""
+
+ def _entries(self, count: int) -> list[_CountEntry]:
+ now = timezone.now()
+ return [
+ _CountEntry(
+ key=f"r{i}",
+ evaluation_id=f"e{i}",
+ since=now,
+ event_predicate="1 = 1",
+ target_predicate="1 = 1",
+ )
+ for i in range(count)
+ ]
+
+ def test_splits_chunk_in_half_on_timeout_and_merges_results(self):
+ # Full width times out once; each half then succeeds. If the timeout instead
+ # propagated unhandled, this would raise instead of returning merged counts.
+ side_effects = [ClickHouseQueryTimeOut(), Mock(results=[[1, 2]]), Mock(results=[[3, 4]])]
+ with patch("posthog.hogql.query.execute_hogql_query", side_effect=side_effects) as execute_hogql_query:
+ counts = _count_eval_results_for_reports_with_split_retry(self.team, self._entries(4), until=timezone.now())
+
+ self.assertEqual(counts, {"r0": 1, "r1": 2, "r2": 3, "r3": 4})
+ self.assertEqual(execute_hogql_query.call_count, 3)
+
+ def test_reraises_when_a_single_entry_still_times_out(self):
+ # A width-1 query has nothing narrower to split into — the failure must surface
+ # so the activity retries (or fails visibly) instead of looping forever.
+ with patch("posthog.hogql.query.execute_hogql_query", side_effect=ClickHouseQueryTimeOut()):
+ with self.assertRaises(ClickHouseQueryTimeOut):
+ _count_eval_results_for_reports_with_split_retry(self.team, self._entries(1), until=timezone.now())
+
+ def test_stops_splitting_once_shared_budget_is_exhausted(self):
+ # A first attempt that burns nearly the whole wall-clock budget must not be followed
+ # by narrower retries: if each half drew a fresh budget instead of sharing the
+ # deadline, the split tree could outlive the activity timeout again.
+ clock = [0.0]
+
+ def timeout_burning_budget(*args, **kwargs):
+ clock[0] += COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS - COUNT_TRIGGER_QUERY_MIN_EXECUTION_TIME_SECONDS + 1
+ raise ClickHouseQueryTimeOut()
+
+ with (
+ patch("time.monotonic", side_effect=lambda: clock[0]),
+ patch("posthog.hogql.query.execute_hogql_query", side_effect=timeout_burning_budget) as execute_hogql_query,
+ ):
+ with self.assertRaises(ClickHouseQueryTimeOut):
+ _count_eval_results_for_reports_with_split_retry(self.team, self._entries(4), until=timezone.now())
+
+ self.assertEqual(execute_hogql_query.call_count, 1)
+
+
class TestPeriodForScheduledReport(BaseTest):
"""Unit-ish tests for the rrule period helper — uses in-memory instances to
bypass model save validation so we can exercise fallback paths."""
@@ -782,6 +843,16 @@ class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
self.assertFalse(due_by_id[str(report_b.id)])
self.assertFalse(due_by_id[str(report_c.id)])
+ def test_events_after_check_time_are_excluded(self):
+ # An event timestamped after the check's `now` must not count — guards the explicit
+ # upper bound that keeps the scan from silently reading past the check time.
+ report = self._create_report(self.team, threshold=1, since=self.T0, name="future")
+ self._emit_eval_events(self.team, str(report.evaluation_id), [self.NOW + dt.timedelta(hours=1)])
+
+ results = _check_count_triggered_eval_reports_batch([str(report.id)], self.NOW)
+
+ self.assertFalse(results[0].due)
+
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.