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): keep a running count for count-triggered eval reports (#107176)

posthog[bot]6c4b8a6c4934
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 28f245f98b69..0a4fa1de2817 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 time
+import hashlib
import datetime as dt
from collections import defaultdict
from dataclasses import replace
@@ -21,6 +22,7 @@ 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_CURSOR_SETTLE_LAG,
COUNT_TRIGGER_QUERY_MAX_EXECUTION_TIME_SECONDS,
COUNT_TRIGGER_QUERY_MIN_EXECUTION_TIME_SECONDS,
COUNT_TRIGGER_QUERY_MIN_SPLIT_RANGE,
@@ -267,8 +269,7 @@ def _check_count_triggered_eval_reports_batch(
}
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)
+ survivors: dict[int, list[_CountCandidate]] = defaultdict(list)
for report_id in report_ids:
report = reports.get(report_id)
@@ -284,41 +285,113 @@ def _check_count_triggered_eval_reports_batch(
)
continue
assert since is not None
- survivors[report.team_id].append((report_id, report, since))
+ survivors[report.team_id].append(_CountCandidate.start(report_id, report, since))
deadline = time.monotonic() + COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS
- for entries in survivors.values():
- team = entries[0][1].team
- # Sort by `since` before capping the per-query width, so entries sharing a chunk
+ settle_until = now - COUNT_TRIGGER_CURSOR_SETTLE_LAG
+ for candidates in survivors.values():
+ team = candidates[0].report.team
+ # Sort by cursor 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 batched(entries, COUNT_TRIGGER_QUERY_WIDTH, strict=False):
- counts = _count_eval_results_for_reports_with_split_retry(
+ candidates.sort(key=lambda candidate: candidate.cursor)
+ for chunk in batched(candidates, COUNT_TRIGGER_QUERY_WIDTH, strict=False):
+ result = _count_eval_results_for_reports_with_split_retry(
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),
+ key=candidate.report_id,
+ evaluation_id=str(candidate.report.evaluation_id),
+ since=candidate.cursor,
+ event_predicate=candidate.event_predicate,
+ target_predicate=candidate.target_predicate,
)
- for report_id, report, since in chunk
+ for candidate in chunk
],
until=now,
+ settle_until=settle_until,
deadline=deadline,
)
- 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
+ if result.covered_before <= now:
+ # The check still succeeds, so this log is the only sign that a team is catching up.
+ logger.warning(
+ "count_triggered_eval_report_check.partial_count",
+ team_id=team.pk,
+ report_count=len(chunk),
+ scan_start=chunk[0].cursor.isoformat(),
+ covered_before=result.covered_before.isoformat(),
+ )
+ for candidate in chunk:
+ count = result.counts.get(candidate.report_id, _EntryCount(total=0, settled=0))
+ _save_running_count(
+ candidate,
+ cursor=max(candidate.cursor, min(result.covered_before, settle_until)),
+ counted_results=candidate.counted_results + count.settled,
+ )
+ assert candidate.report.trigger_threshold is not None
+ outputs[candidate.report_id] = CheckCountTriggeredEvalReportOutput(
+ report_id=candidate.report_id,
+ due=candidate.counted_results + count.total >= candidate.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]
+class _CountCandidate(NamedTuple):
+ report_id: str
+ report: "EvaluationReport"
+ anchor: dt.datetime
+ event_predicate: str
+ target_predicate: str
+ predicates_hash: str
+ # The check counts from here; `counted_results` already covers anchor..cursor.
+ cursor: dt.datetime
+ counted_results: int
+
+ @classmethod
+ def start(cls, report_id: str, report: "EvaluationReport", anchor: dt.datetime) -> "_CountCandidate":
+ event_predicate = get_outcome_definition(report.evaluation.output_type).event_predicate
+ target_predicate = target_event_predicate(report.evaluation.target)
+ predicates_hash = hashlib.sha256(f"{event_predicate}\n{target_predicate}".encode()).hexdigest()
+ cursor, counted_results = anchor, 0
+ # A saved count only holds while the rows it counted still match the evaluation's predicates.
+ if (
+ report.count_anchor_at == anchor
+ and report.count_predicates_hash == predicates_hash
+ and report.count_cursor_at is not None
+ and report.counted_results is not None
+ ):
+ cursor, counted_results = report.count_cursor_at, report.counted_results
+ return cls(
+ report_id, report, anchor, event_predicate, target_predicate, predicates_hash, cursor, counted_results
+ )
+
+
+def _save_running_count(candidate: _CountCandidate, cursor: dt.datetime, counted_results: int) -> None:
+ from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
+
+ report = candidate.report
+ if (
+ report.count_anchor_at == candidate.anchor
+ and report.count_predicates_hash == candidate.predicates_hash
+ and report.count_cursor_at == cursor
+ ):
+ return
+ # Match the values this check read, so a concurrent check or a reset does not get overwritten.
+ EvaluationReport.objects.filter(
+ id=report.id,
+ count_anchor_at=report.count_anchor_at,
+ count_predicates_hash=report.count_predicates_hash,
+ count_cursor_at=report.count_cursor_at,
+ ).update(
+ count_anchor_at=candidate.anchor,
+ count_predicates_hash=candidate.predicates_hash,
+ count_cursor_at=cursor,
+ counted_results=counted_results,
+ )
+
+
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
@@ -365,23 +438,36 @@ class _CountEntry(NamedTuple):
target_predicate: str
+class _EntryCount(NamedTuple):
+ total: int
+ # The part of `total` with a timestamp before `settle_until`.
+ settled: int
+
+
+class _CountResult(NamedTuple):
+ counts: dict[str, _EntryCount]
+ # The counts cover the requested range from its start up to, but not including, this instant.
+ covered_before: dt.datetime
+
+
def _count_eval_results_for_reports(
team: "Team",
entries: list[_CountEntry],
since: dt.datetime,
until: dt.datetime,
+ settle_until: dt.datetime,
max_execution_time: int,
-) -> dict[str, int]:
+) -> dict[str, _EntryCount]:
"""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
+ We emit two `countIf` columns per entry, each carrying the exact per-report predicate
(evaluation_id + output-type `event_predicate` + `target_predicate` + `timestamp >=
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}.
+ query would. The second column also requires `timestamp < settle_until`. 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.
"""
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.parser import parse_expr, parse_select
@@ -401,13 +487,15 @@ def _count_eval_results_for_reports(
# 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}})",
+ f" AND {entry.event_predicate} AND {entry.target_predicate} AND timestamp >= {{since}}{extra_predicate})",
placeholders={
"evaluation_id": ast.Constant(value=entry.evaluation_id),
"since": ast.Constant(value=entry.since),
+ "settle_until": ast.Constant(value=settle_until),
},
)
for entry in entries
+ for extra_predicate in ("", " AND timestamp < {settle_until}")
]
unique_evaluation_ids = list(dict.fromkeys(entry.evaluation_id for entry in entries))
@@ -437,19 +525,23 @@ def _count_eval_results_for_reports(
rows = result.results or []
if not rows:
- return {entry.key: 0 for entry in entries}
+ return {entry.key: _EntryCount(total=0, settled=0) for entry in entries}
row = rows[0]
- return {entries[index].key: int(row[index] or 0) for index in range(len(entries))}
+ return {
+ entry.key: _EntryCount(total=int(row[2 * index] or 0), settled=int(row[2 * index + 1] or 0))
+ for index, entry in enumerate(entries)
+ }
def _count_eval_results_for_reports_with_split_retry(
team: "Team",
entries: list[_CountEntry],
until: dt.datetime,
+ settle_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]:
+) -> _CountResult:
"""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.
@@ -466,6 +558,10 @@ def _count_eval_results_for_reports_with_split_retry(
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.
+
+ The halves run oldest first. When a later part cannot finish, the result keeps the counts
+ of the finished earlier part and `covered_before` marks where they stop, so the caller can
+ save that progress. The timeout surfaces only when no part of the range finished.
"""
if since is None:
since = min(entry.since for entry in entries)
@@ -475,33 +571,45 @@ def _count_eval_results_for_reports_with_split_retry(
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.")
+ # The events table stores timestamps as DateTime64(6), so one microsecond past an instant
+ # is the next representable one and adjacent ranges cannot overlap.
try:
- return _count_eval_results_for_reports(team, entries, since=since, until=until, max_execution_time=budget)
+ counts = _count_eval_results_for_reports(
+ team, entries, since=since, until=until, settle_until=settle_until, max_execution_time=budget
+ )
+ return _CountResult(counts=counts, covered_before=until + dt.timedelta(microseconds=1))
except ClickHouseQueryTimeOut:
if (until - since) <= COUNT_TRIGGER_QUERY_MIN_SPLIT_RANGE:
raise
midpoint = since + (until - since) / 2
- counts = _count_eval_results_for_reports_with_split_retry(
+ earlier_half = _count_eval_results_for_reports_with_split_retry(
team,
entries,
since=since,
until=midpoint,
+ settle_until=settle_until,
deadline=deadline,
max_execution_time=COUNT_TRIGGER_QUERY_RETRY_MAX_EXECUTION_TIME_SECONDS,
)
- # 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
+ if earlier_half.covered_before <= midpoint:
+ return earlier_half
+ try:
+ later_half = _count_eval_results_for_reports_with_split_retry(
+ team,
+ entries,
+ since=midpoint + dt.timedelta(microseconds=1),
+ until=until,
+ settle_until=settle_until,
+ deadline=deadline,
+ max_execution_time=COUNT_TRIGGER_QUERY_RETRY_MAX_EXECUTION_TIME_SECONDS,
+ )
+ except ClickHouseQueryTimeOut:
+ return earlier_half
+ counts = dict(earlier_half.counts)
+ for key, count in later_half.counts.items():
+ earlier = counts.get(key, _EntryCount(total=0, settled=0))
+ counts[key] = _EntryCount(total=earlier.total + count.total, settled=earlier.settled + count.settled)
+ return _CountResult(counts=counts, covered_before=later_half.covered_before)
def _find_nth_eval_timestamp(
diff --git a/posthog/temporal/ai_observability/eval_reports/constants.py b/posthog/temporal/ai_observability/eval_reports/constants.py
index 27d78db0d66f..010e1abe2a97 100644
--- a/posthog/temporal/ai_observability/eval_reports/constants.py
+++ b/posthog/temporal/ai_observability/eval_reports/constants.py
@@ -53,6 +53,9 @@ COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS = 100
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)
+# A check saves its running count only up to this long before its own time, so results that
+# arrive late still land after the saved cursor and count on a later check.
+COUNT_TRIGGER_CURSOR_SETTLE_LAG = timedelta(hours=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 23ed1b90eb5c..78b4401a451d 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -31,6 +31,7 @@ from posthog.temporal.ai_observability.eval_reports.activities import (
store_report_run_activity,
)
from posthog.temporal.ai_observability.eval_reports.constants import (
+ COUNT_TRIGGER_CURSOR_SETTLE_LAG,
COUNT_TRIGGER_QUERY_MAX_EXECUTION_TIME_SECONDS,
COUNT_TRIGGER_QUERY_MIN_EXECUTION_TIME_SECONDS,
COUNT_TRIGGER_QUERY_OVERSHOOT_FACTOR,
@@ -704,12 +705,14 @@ class TestCountEvalResultsForReportsSplitRetry(BaseTest):
# 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]])]
+ side_effects = [ClickHouseQueryTimeOut(), Mock(results=[[1, 1, 2, 2]]), Mock(results=[[30, 30, 40, 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(2, since), until=until)
+ result = _count_eval_results_for_reports_with_split_retry(
+ self.team, self._entries(2, since), until=until, settle_until=until
+ )
- self.assertEqual(counts, {"r0": 31, "r1": 42})
+ self.assertEqual({key: count.total for key, count in result.counts.items()}, {"r0": 31, "r1": 42})
self.assertEqual(
[call.kwargs["settings"].max_execution_time for call in execute_hogql_query.call_args_list], [30, 15, 15]
)
@@ -729,7 +732,7 @@ class TestCountEvalResultsForReportsSplitRetry(BaseTest):
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 - dt.timedelta(seconds=30)), until=until
+ self.team, self._entries(1, until - dt.timedelta(seconds=30)), until=until, settle_until=until
)
def test_stops_splitting_once_shared_budget_is_exhausted(self):
@@ -749,7 +752,7 @@ class TestCountEvalResultsForReportsSplitRetry(BaseTest):
):
with self.assertRaises(ClickHouseQueryTimeOut):
_count_eval_results_for_reports_with_split_retry(
- self.team, self._entries(4, until - dt.timedelta(days=8)), until=until
+ self.team, self._entries(4, until - dt.timedelta(days=8)), until=until, settle_until=until
)
self.assertEqual(execute_hogql_query.call_count, 1)
@@ -766,7 +769,7 @@ class TestCountEvalResultsForReportsSplitRetry(BaseTest):
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]])
+ return Mock(results=[[0, 0]])
clock[0] = COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS - remaining_after_first_attempt
raise ClickHouseQueryTimeOut()
@@ -775,7 +778,7 @@ class TestCountEvalResultsForReportsSplitRetry(BaseTest):
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.team, self._entries(1, until - dt.timedelta(days=8)), until=until, settle_until=until
)
self.assertEqual(execution_limits[0], COUNT_TRIGGER_QUERY_MAX_EXECUTION_TIME_SECONDS)
@@ -787,9 +790,9 @@ class TestCountEvalResultsForReportsSplitRetry(BaseTest):
until = timezone.now()
with patch("posthog.hogql.query.execute_hogql_query") as execute_hogql_query:
- execute_hogql_query.return_value = Mock(results=[[7]])
+ execute_hogql_query.return_value = Mock(results=[[7, 7]])
_count_eval_results_for_reports_with_split_retry(
- self.team, self._entries(1, until - dt.timedelta(days=1)), until=until
+ self.team, self._entries(1, until - dt.timedelta(days=1)), until=until, settle_until=until
)
self.assertEqual(execute_hogql_query.call_args.kwargs["settings"].timeout_overflow_mode, "throw")
@@ -1081,6 +1084,56 @@ class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
self.assertTrue(due_by_id[str(at_threshold.id)])
self.assertFalse(due_by_id[str(above_threshold.id)])
+ def test_running_count_adds_up_across_checks_and_resets_when_the_anchor_moves(self):
+ # Catches a check that rescans the whole window, loses the saved count, or keeps a
+ # count from before the last delivery.
+ report = self._create_report(self.team, threshold=3, since=self.T0, name="running")
+ evaluation_id = str(report.evaluation_id)
+ self._emit_eval_events(self.team, evaluation_id, [self.T0 + dt.timedelta(hours=1)] * 2)
+
+ self.assertFalse(_check_count_triggered_eval_reports_batch([str(report.id)], self.NOW)[0].due)
+ report.refresh_from_db()
+ first_cursor = self.NOW - COUNT_TRIGGER_CURSOR_SETTLE_LAG
+ self.assertEqual((report.count_cursor_at, report.counted_results), (first_cursor, 2))
+
+ later = self.NOW + dt.timedelta(days=2)
+ self._emit_eval_events(self.team, evaluation_id, [later - dt.timedelta(hours=2)])
+ with patch("posthog.hogql.query.execute_hogql_query", side_effect=execute_hogql_query) as spy:
+ self.assertTrue(_check_count_triggered_eval_reports_batch([str(report.id)], later)[0].due)
+ self.assertEqual(_scanned_window(spy.call_args.kwargs["query"])[0], first_cursor)
+
+ EvaluationReport.objects.filter(id=report.id).update(last_delivered_at=later - dt.timedelta(hours=1))
+ self.assertFalse(
+ _check_count_triggered_eval_reports_batch([str(report.id)], later + dt.timedelta(hours=2))[0].due
+ )
+ report.refresh_from_db()
+ self.assertEqual(report.counted_results, 0)
+
+ def test_saves_the_finished_part_of_a_count_that_runs_out_of_budget(self):
+ # Catches a window too large for one check that fails every retry and never fires.
+ midpoint = self.T0 + (self.NOW - self.T0) / 2
+ report = self._create_report(self.team, threshold=3, since=self.T0, name="catch up")
+ self._emit_eval_events(
+ self.team,
+ str(report.evaluation_id),
+ [self.T0 + dt.timedelta(minutes=10), self.T0 + dt.timedelta(minutes=20), self.NOW - dt.timedelta(hours=1)],
+ )
+ attempts = 0
+
+ def finish_only_the_earlier_half(*args, **kwargs):
+ nonlocal attempts
+ attempts += 1
+ if attempts == 2:
+ return execute_hogql_query(*args, **kwargs)
+ raise ClickHouseQueryTimeOut()
+
+ with patch("posthog.hogql.query.execute_hogql_query", side_effect=finish_only_the_earlier_half):
+ self.assertFalse(_check_count_triggered_eval_reports_batch([str(report.id)], self.NOW)[0].due)
+ report.refresh_from_db()
+ self.assertEqual((report.count_cursor_at, report.counted_results), (midpoint + dt.timedelta(microseconds=1), 2))
+
+ self.assertTrue(_check_count_triggered_eval_reports_batch([str(report.id)], self.NOW)[0].due)
+
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.
@@ -1193,8 +1246,9 @@ class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
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")
+ # stale generation-target events must not keep counting toward the threshold,
+ # neither through the scan nor through a running count saved before the switch.
+ switched = self._create_report(self.team, threshold=2, since=self.T0, name="switched", target="generation")
for index, (ts, target_type) in enumerate(
[
# Two generation-shaped events (tagged + untagged legacy) and one trace event:
@@ -1225,7 +1279,12 @@ class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
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)
+ self.assertTrue(_check_count_triggered_eval_reports_batch([str(switched.id)], self.NOW)[0].due)
+ Evaluation.objects.filter(id=switched.evaluation_id).update(target="trace")
+
+ results = _check_count_triggered_eval_reports_batch(
+ [str(switched.id), str(trace_only.id)], self.NOW + dt.timedelta(hours=1)
+ )
by_id = {r.report_id: r for r in results}
self.assertFalse(by_id[str(switched.id)].due)
diff --git a/products/ai_observability/backend/migrations/0060_evaluationreport_running_count.py b/products/ai_observability/backend/migrations/0060_evaluationreport_running_count.py
new file mode 100644
index 000000000000..1590e16df2ae
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0060_evaluationreport_running_count.py
@@ -0,0 +1,32 @@
+# Generated by Django 5.2.17 on 2026-09-26 00:22
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0059_categorical_evaluation_output"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="evaluationreport",
+ name="count_anchor_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="evaluationreport",
+ name="count_cursor_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="evaluationreport",
+ name="counted_results",
+ field=models.IntegerField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="evaluationreport",
+ name="count_predicates_hash",
+ field=models.CharField(blank=True, max_length=64, null=True),
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index 3fab3df7673c..a8d8650a8ef4 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0059_categorical_evaluation_output
+0060_evaluationreport_running_count
diff --git a/products/ai_observability/backend/models/evaluation_reports.py b/products/ai_observability/backend/models/evaluation_reports.py
index a4ec908255b1..c3533b05b31c 100644
--- a/products/ai_observability/backend/models/evaluation_reports.py
+++ b/products/ai_observability/backend/models/evaluation_reports.py
@@ -111,6 +111,13 @@ class EvaluationReport(UUIDTModel):
default=10,
help_text="Maximum count-triggered report runs per calendar day (UTC)",
)
+ # Running count for count-triggered reports. `counted_results` covers results from
+ # `count_anchor_at` up to, but not including, `count_cursor_at`, and holds only for the
+ # count predicates hashed in `count_predicates_hash`.
+ count_anchor_at = models.DateTimeField(null=True, blank=True)
+ count_cursor_at = models.DateTimeField(null=True, blank=True)
+ counted_results = models.IntegerField(null=True, blank=True)
+ count_predicates_hash = models.CharField(max_length=64, null=True, blank=True)
# Optional per-report custom guidance appended to the agent's system prompt.
# Lets users steer focus/scope/section choices without touching the base prompt.