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 slow eval report counts over smaller time ranges (#97110)

posthog[bot]2625e909f7df
diff --git a/docs/internal/ai-observability-evaluation-reports.md b/docs/internal/ai-observability-evaluation-reports.md
new file mode 100644
index 000000000000..b9907d34f7f8
--- /dev/null
+++ b/docs/internal/ai-observability-evaluation-reports.md
@@ -0,0 +1,20 @@
+# Evaluation report count triggers
+
+An evaluation report configured for "Every N evaluations" counts matching results since its last delivery.
+For a report that has not been delivered, the count starts at its configured start time or creation time.
+Results remain eligible until a report is delivered, even when reaching the threshold takes more than seven days.
+For example, a report with a threshold of 100 and 10 new results per day becomes due after ten days.
+Cooldowns and daily delivery limits still apply.
+
+## Query time limits
+
+The coordinator checks count-triggered reports every five minutes and groups queries by team.
+Each report retains its own start time within the shared query.
+If a query times out, the check divides its time range and adds the counts from the two non-overlapping ranges.
+The check requests an error on timeout so partial counts cannot be mistaken for complete results.
+
+Queries and their split retries share a 100-second execution budget within a 120-second activity timeout.
+The initial query keeps its 30-second limit; split retries request at most 15 seconds each.
+Each attempt reserves room for a twofold overrun and reduces its limit when the remaining budget requires it.
+If the remaining budget cannot support another attempt, the activity fails and follows its retry policy.
+The execution budget limits query work; it does not discard older results or guarantee that every report can be checked within that budget.
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 1f2a66fe32c6..60fd07e88b15 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -21,6 +21,9 @@ from posthog.sync import database_sync_to_async
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_MIN_SPLIT_RANGE,
+ COUNT_TRIGGER_QUERY_OVERSHOOT_FACTOR,
+ COUNT_TRIGGER_QUERY_RETRY_MAX_EXECUTION_TIME_SECONDS,
COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS,
COUNT_TRIGGER_QUERY_WIDTH,
)
@@ -361,16 +364,20 @@ class _CountEntry(NamedTuple):
def _count_eval_results_for_reports(
team: "Team",
entries: list[_CountEntry],
+ since: dt.datetime,
until: dt.datetime,
max_execution_time: int,
) -> dict[str, int]:
- """Count `$ai_evaluation` events for many reports in a single ClickHouse query.
+ """Count `$ai_evaluation` events for many reports over one time range, 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, `min(since)`, and `until` upper bound never
- exclude a row any countIf would have counted). Returns {key: count}.
+ entry.since`), so a call covering every entry's own window returns what the single-report
+ query would. The shared WHERE narrows the scan to `since`..`until` and to the entries'
+ evaluation ids. Callers that pass a range narrower than an entry's own window get that
+ range's share of the count, and must sum the shares to get the entry's total.
+ Returns {key: count}.
"""
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.parser import parse_expr, parse_select
@@ -403,10 +410,10 @@ def _count_eval_results_for_reports(
query = parse_select(
"SELECT 1 FROM events WHERE event = '$ai_evaluation' "
"AND properties.$ai_evaluation_id IN {evaluation_ids} "
- "AND timestamp >= {min_since} AND timestamp <= {until}",
+ "AND timestamp >= {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)),
+ "since": ast.Constant(value=since),
"until": ast.Constant(value=until),
},
)
@@ -419,7 +426,9 @@ def _count_eval_results_for_reports(
query=query,
team=team,
workload=Workload.OFFLINE,
- settings=HogQLGlobalSettings(max_execution_time=max_execution_time),
+ # "throw", not the profile default: the split retry needs the timeout to raise. A
+ # partial count reads as below threshold and silently keeps the report from firing.
+ settings=HogQLGlobalSettings(max_execution_time=max_execution_time, timeout_overflow_mode="throw"),
)
rows = result.results or []
@@ -433,38 +442,61 @@ def _count_eval_results_for_reports_with_split_retry(
team: "Team",
entries: list[_CountEntry],
until: dt.datetime,
+ since: dt.datetime | None = None,
deadline: float | None = None,
+ max_execution_time: int = COUNT_TRIGGER_QUERY_MAX_EXECUTION_TIME_SECONDS,
) -> 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.
+ """Run the batched count query, halving the time range and retrying over each half 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.
+ A `ClickHouseQueryTimeOut` means the rows in `since`..`until` don't fit the budget, so
+ replaying the identical query would just time out again. Halving the range halves the
+ rows each attempt reads, and the two halves sum to the same per-entry counts. Splitting
+ the countIf columns instead would leave both halves reading almost the same rows, because
+ the columns share one scan and the width barely moves its cost.
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.
+ concludes before the activity's own timeout. ClickHouse can overrun its execution limit,
+ so an attempt only claims a limit it can afford to overshoot by
+ COUNT_TRIGGER_QUERY_OVERSHOOT_FACTOR. 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 since is None:
+ since = min(entry.since for entry in entries)
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()))
+ affordable_execution_time = int((deadline - time.monotonic()) / COUNT_TRIGGER_QUERY_OVERSHOOT_FACTOR)
+ budget = min(max_execution_time, affordable_execution_time)
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)
+ return _count_eval_results_for_reports(team, entries, since=since, until=until, max_execution_time=budget)
except ClickHouseQueryTimeOut:
- if len(entries) == 1:
+ if (until - since) <= COUNT_TRIGGER_QUERY_MIN_SPLIT_RANGE:
raise
- midpoint = len(entries) // 2
+ midpoint = since + (until - since) / 2
counts = _count_eval_results_for_reports_with_split_retry(
- team, entries[:midpoint], until=until, deadline=deadline
+ team,
+ entries,
+ since=since,
+ until=midpoint,
+ deadline=deadline,
+ max_execution_time=COUNT_TRIGGER_QUERY_RETRY_MAX_EXECUTION_TIME_SECONDS,
)
- counts.update(
- _count_eval_results_for_reports_with_split_retry(team, entries[midpoint:], until=until, deadline=deadline)
+ # The events table stores timestamps as DateTime64(6), so one microsecond past the
+ # midpoint is the next representable instant and the halves cannot overlap.
+ later_half = _count_eval_results_for_reports_with_split_retry(
+ team,
+ entries,
+ since=midpoint + dt.timedelta(microseconds=1),
+ until=until,
+ deadline=deadline,
+ max_execution_time=COUNT_TRIGGER_QUERY_RETRY_MAX_EXECUTION_TIME_SECONDS,
)
+ for key, count in later_half.items():
+ counts[key] = counts.get(key, 0) + count
return counts
diff --git a/posthog/temporal/ai_observability/eval_reports/constants.py b/posthog/temporal/ai_observability/eval_reports/constants.py
index 687206aab813..27d78db0d66f 100644
--- a/posthog/temporal/ai_observability/eval_reports/constants.py
+++ b/posthog/temporal/ai_observability/eval_reports/constants.py
@@ -38,15 +38,21 @@ COUNT_TRIGGER_CHECK_ACTIVITY_TIMEOUT = timedelta(seconds=120)
# 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
+# Keep the full-window allowance; smaller retries leave time to check both halves.
+COUNT_TRIGGER_QUERY_RETRY_MAX_EXECUTION_TIME_SECONDS = 15
+# ClickHouse checks max_execution_time between blocks rather than stopping at it exactly, so an
+# attempt can run past its own limit. Every attempt reserves this multiple of its limit against
+# the shared budget, so an overshooting query cannot eat the share of the retries after it.
+COUNT_TRIGGER_QUERY_OVERSHOOT_FACTOR = 2.0
# 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
+# Kept below COUNT_TRIGGER_CHECK_ACTIVITY_TIMEOUT with headroom for the Postgres gate and
+# per-query overhead. Retries reduce their allowance when earlier attempts consume the budget.
+COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS = 100
# 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
+# Narrower than this, halving the range no longer removes enough rows to be worth an attempt.
+COUNT_TRIGGER_QUERY_MIN_SPLIT_RANGE = timedelta(minutes=1)
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 eea9fabb0dae..e11cc3b88aac 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -11,6 +11,10 @@ from django.utils import timezone
from asgiref.sync import sync_to_async
from parameterized import parameterized
+from posthog.hogql import ast
+from posthog.hogql.query import execute_hogql_query
+from posthog.hogql.visitor import TraversingVisitor
+
from posthog.exceptions import ClickHouseQueryTimeOut
from posthog.models import Team
from posthog.temporal.ai_observability.eval_reports.activities import (
@@ -30,7 +34,10 @@ from posthog.temporal.ai_observability.eval_reports.activities import (
store_report_run_activity,
)
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_OVERSHOOT_FACTOR,
+ COUNT_TRIGGER_QUERY_RETRY_MAX_EXECUTION_TIME_SECONDS,
COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS,
)
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import EvalReportContent, EvalReportMetrics
@@ -46,6 +53,20 @@ from products.ai_observability.backend.models.evaluation_reports import Evaluati
from products.ai_observability.backend.models.evaluations import Evaluation
+def _scanned_window(query: ast.SelectQuery) -> list[dt.datetime]:
+ class CollectTimestamps(TraversingVisitor):
+ def __init__(self) -> None:
+ self.timestamps: list[dt.datetime] = []
+
+ def visit_constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, dt.datetime):
+ self.timestamps.append(node.value)
+
+ visitor = CollectTimestamps()
+ visitor.visit(query.where)
+ return sorted(visitor.timestamps)
+
+
class TestUpdateNextDeliveryDate(SimpleTestCase):
@parameterized.expand(
[
@@ -699,46 +720,80 @@ class TestCountTriggeredReportChecks(BaseTest):
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))
+ @parameterized.expand(
+ [
+ ("created_at",),
+ ("starts_at",),
+ ("last_delivered_at",),
+ ]
+ )
+ def test_count_window_preserves_older_report_anchor(self, anchor_field: str) -> None:
+ now = timezone.now()
+ since = now - dt.timedelta(days=10)
+ report = self._create_report()
+ EvaluationReport.objects.filter(id=report.id).update(**{anchor_field: since})
+
+ with patch("posthog.hogql.query.execute_hogql_query") as execute_hogql_query:
+ execute_hogql_query.return_value = Mock(results=[[1]])
+ _check_count_triggered_eval_report_sync(str(report.id), now)
+
+ self.assertEqual(_scanned_window(execute_hogql_query.call_args.kwargs["query"]), [since])
+
class TestCountEvalResultsForReportsSplitRetry(BaseTest):
- """Guards the retry behavior a `ClickHouseQueryTimeOut` needs: split the chunk and
- retry narrower, rather than replaying the identical too-wide query."""
+ """Guards the retry behavior a `ClickHouseQueryTimeOut` needs: halve the time range and
+ retry over each half, rather than replaying a query over the same rows."""
- def _entries(self, count: int) -> list[_CountEntry]:
- now = timezone.now()
+ def _entries(self, count: int, since: dt.datetime) -> list[_CountEntry]:
return [
_CountEntry(
key=f"r{i}",
evaluation_id=f"e{i}",
- since=now,
+ since=since,
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]])]
+ def test_splits_time_range_in_half_on_timeout_and_sums_the_halves(self):
+ # Catches a retry that reads the same range again, as the old column split did.
+ until = timezone.now()
+ since = until - dt.timedelta(days=8)
+ side_effects = [ClickHouseQueryTimeOut(), Mock(results=[[1, 2]]), Mock(results=[[30, 40]])]
+
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())
+ counts = _count_eval_results_for_reports_with_split_retry(self.team, self._entries(2, since), until=until)
- self.assertEqual(counts, {"r0": 1, "r1": 2, "r2": 3, "r3": 4})
- self.assertEqual(execute_hogql_query.call_count, 3)
+ self.assertEqual(counts, {"r0": 31, "r1": 42})
+ self.assertEqual(
+ [call.kwargs["settings"].max_execution_time for call in execute_hogql_query.call_args_list], [30, 15, 15]
+ )
+ midpoint = since + (until - since) / 2
+ self.assertEqual(
+ [_scanned_window(call.kwargs["query"]) for call in execute_hogql_query.call_args_list],
+ [
+ [since, until],
+ [since, midpoint],
+ [midpoint + dt.timedelta(microseconds=1), until],
+ ],
+ )
- 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.
+ def test_reraises_when_the_narrowest_range_still_times_out(self):
+ # A range too narrow to halve has nothing cheaper to retry, so the failure must surface.
+ until = timezone.now()
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())
+ _count_eval_results_for_reports_with_split_retry(
+ self.team, self._entries(1, until - dt.timedelta(seconds=30)), until=until
+ )
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]
+ until = timezone.now()
def timeout_burning_budget(*args, **kwargs):
clock[0] += COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS - COUNT_TRIGGER_QUERY_MIN_EXECUTION_TIME_SECONDS + 1
@@ -749,10 +804,52 @@ class TestCountEvalResultsForReportsSplitRetry(BaseTest):
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())
+ _count_eval_results_for_reports_with_split_retry(
+ self.team, self._entries(4, until - dt.timedelta(days=8)), until=until
+ )
self.assertEqual(execute_hogql_query.call_count, 1)
+ def test_execution_limit_leaves_room_for_clickhouse_to_overshoot_it(self):
+ # Catches a retry that claims the whole remaining budget as its limit. ClickHouse can
+ # run past that limit, so the attempt would overshoot the deadline and Temporal would
+ # kill the split midway.
+ clock = [0.0]
+ until = timezone.now()
+ remaining_after_first_attempt = COUNT_TRIGGER_QUERY_RETRY_MAX_EXECUTION_TIME_SECONDS * 1.5
+ execution_limits: list[int] = []
+
+ def record_limit_then_time_out_once(*args, **kwargs):
+ execution_limits.append(kwargs["settings"].max_execution_time)
+ if len(execution_limits) > 1:
+ return Mock(results=[[0]])
+ clock[0] = COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS - remaining_after_first_attempt
+ raise ClickHouseQueryTimeOut()
+
+ with (
+ patch("time.monotonic", side_effect=lambda: clock[0]),
+ patch("posthog.hogql.query.execute_hogql_query", side_effect=record_limit_then_time_out_once),
+ ):
+ _count_eval_results_for_reports_with_split_retry(
+ self.team, self._entries(1, until - dt.timedelta(days=8)), until=until
+ )
+
+ self.assertEqual(execution_limits[0], COUNT_TRIGGER_QUERY_MAX_EXECUTION_TIME_SECONDS)
+ self.assertEqual(execution_limits[1], int(remaining_after_first_attempt / COUNT_TRIGGER_QUERY_OVERSHOOT_FACTOR))
+
+ def test_asks_clickhouse_to_raise_on_timeout_rather_than_return_a_partial_count(self):
+ # Catches a query that inherits the cluster's overflow mode. Under "break" the timeout
+ # never raises, so the split never runs and a partial count decides the threshold.
+ until = timezone.now()
+
+ with patch("posthog.hogql.query.execute_hogql_query") as execute_hogql_query:
+ execute_hogql_query.return_value = Mock(results=[[7]])
+ _count_eval_results_for_reports_with_split_retry(
+ self.team, self._entries(1, until - dt.timedelta(days=1)), until=until
+ )
+
+ self.assertEqual(execute_hogql_query.call_args.kwargs["settings"].timeout_overflow_mode, "throw")
+
class TestPeriodForScheduledReport(BaseTest):
"""Unit-ish tests for the rrule period helper — uses in-memory instances to
@@ -871,13 +968,16 @@ class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
properties={"$ai_evaluation_id": evaluation_id, **(extra_properties or {})},
)
- def test_counts_respect_since_evaluation_and_threshold(self):
+ @parameterized.expand([("same_day", dt.timedelta(hours=3)), ("over_seven_days", dt.timedelta(days=10))])
+ def test_counts_respect_since_evaluation_and_threshold(self, _name: str, window: dt.timedelta) -> None:
+ now = self.T0 + window
+ in_window = [self.T0 + dt.timedelta(hours=1), now - dt.timedelta(hours=1)]
# 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)],
+ [self.T0 - dt.timedelta(hours=1), *in_window],
)
# 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).
@@ -885,7 +985,7 @@ class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
self._emit_eval_events(
self.team,
str(report_b.evaluation_id),
- [self.T0 + dt.timedelta(hours=1), self.T0 + dt.timedelta(hours=2)],
+ in_window,
)
# 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.
@@ -893,7 +993,7 @@ class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
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)
+ results = _check_count_triggered_eval_reports_batch(report_ids, now)
due_by_id = {r.report_id: r.due for r in results}
self.assertEqual([r.report_id for r in results], report_ids)
@@ -901,6 +1001,35 @@ class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
self.assertFalse(due_by_id[str(report_b.id)])
self.assertFalse(due_by_id[str(report_c.id)])
+ def test_split_after_a_timeout_counts_a_midpoint_event_exactly_once(self):
+ # An event on the split boundary must count once. Dropped, a report at its threshold
+ # stops firing; counted twice, a report below its threshold fires early.
+ midpoint = self.T0 + (self.NOW - self.T0) / 2
+ timestamps = [self.T0 + dt.timedelta(hours=1), midpoint, self.NOW - dt.timedelta(hours=1)]
+ at_threshold = self._create_report(self.team, threshold=3, since=self.T0, name="at threshold")
+ self._emit_eval_events(self.team, str(at_threshold.evaluation_id), timestamps)
+ above_threshold = self._create_report(self.team, threshold=4, since=self.T0, name="above threshold")
+ self._emit_eval_events(self.team, str(above_threshold.evaluation_id), timestamps)
+
+ attempts = 0
+
+ def time_out_the_first_attempt(*args, **kwargs):
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise ClickHouseQueryTimeOut()
+ return execute_hogql_query(*args, **kwargs)
+
+ with patch("posthog.hogql.query.execute_hogql_query", side_effect=time_out_the_first_attempt):
+ results = _check_count_triggered_eval_reports_batch(
+ [str(at_threshold.id), str(above_threshold.id)], self.NOW
+ )
+
+ self.assertEqual(attempts, 3)
+ due_by_id = {r.report_id: r.due for r in results}
+ self.assertTrue(due_by_id[str(at_threshold.id)])
+ self.assertFalse(due_by_id[str(above_threshold.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.