:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): run evaluations over historical units from a backfill workflow (#96228)
Bernat Torres07c7e0193ee3
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex fc086763065c..c706c367a194 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -376,6 +376,7 @@ rules:|ChannelFeedMessage|EmailChannel|EvaluationReport+ |EvaluationBackfill|Text|Threshold|ToleratedHash@@ -772,6 +773,7 @@ rules:|ChannelFeedMessage|EmailChannel|EvaluationReport+ |EvaluationBackfill|Text|Threshold|ToleratedHashdiff --git a/posthog/hogql/functions/clickhouse/conversions.py b/posthog/hogql/functions/clickhouse/conversions.pyindex 638aaa8edf7c..e1f434fa0010 100644--- a/posthog/hogql/functions/clickhouse/conversions.py+++ b/posthog/hogql/functions/clickhouse/conversions.py@@ -140,6 +140,7 @@ TYPE_CONVERSION_FUNCTIONS: dict[str, HogQLFunctionMeta] = {"toTypeName": HogQLFunctionMeta("toTypeName", 1, 1),"defaultValueOfTypeName": HogQLFunctionMeta("defaultValueOfTypeName", 1, 1),"cityHash64": HogQLFunctionMeta("cityHash64", 1, 1),+ "MD5": HogQLFunctionMeta("MD5", 1, 1),"UUIDv7ToDateTime": HogQLFunctionMeta("UUIDv7ToDateTime", 1, 1, tz_aware=True),}diff --git a/posthog/hogql_queries/ai/test/test_trace_query_runner.py b/posthog/hogql_queries/ai/test/test_trace_query_runner.pyindex e8aa9fbe76c2..018f1a59a5bd 100644--- a/posthog/hogql_queries/ai/test/test_trace_query_runner.py+++ b/posthog/hogql_queries/ai/test/test_trace_query_runner.py@@ -966,6 +966,83 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):self.assertEqual(trace.totalLatency, 3.9)self.assertEqual(trace.events[0].properties.get("$ai_input"), [{"role": "user", "content": "Foo"}])+ def test_bound_events_to_date_range_holds_events_and_totals_to_date_to(self):+ trace_id = str(uuid.uuid4())+ start = datetime(2024, 12, 1, 0, 0, tzinfo=UTC)++ def generation(timestamp: datetime, latency: float, tokens: int, cost: float) -> dict[str, Any]:+ return {+ "event": "$ai_generation",+ "team": self.team,+ "distinct_id": "person1",+ "timestamp": timestamp,+ "properties": {+ "$ai_trace_id": trace_id,+ "$ai_parent_id": trace_id,+ "$ai_latency": latency,+ "$ai_input_tokens": tokens,+ "$ai_output_tokens": tokens,+ "$ai_total_cost_usd": cost,+ },+ }++ # The later generation sits past date_to but inside the 7 day forward capture buffer, so it+ # is only excluded if the exact upper bound is applied.+ bulk_create_ai_events(+ [+ generation(start, latency=1.5, tokens=10, cost=0.02),+ generation(start + timedelta(hours=2), latency=3.0, tokens=7, cost=0.05),+ ]+ )++ query = TraceQuery(+ traceId=trace_id,+ dateRange=DateRange(date_from="2024-12-01T00:00:00Z", date_to="2024-12-01T00:10:00Z"),+ )++ unbounded = TraceQueryRunner(team=self.team, query=query).calculate().results[0]+ self.assertEqual(len(unbounded.events), 2)+ self.assertEqual(unbounded.totalLatency, 4.5)+ self.assertEqual(unbounded.totalCost, 0.07)+ self.assertEqual(unbounded.inputTokens, 17)+ self.assertEqual(unbounded.outputTokens, 17)++ bounded = TraceQueryRunner(team=self.team, query=query, bound_events_to_date_range=True).calculate().results[0]+ self.assertEqual(len(bounded.events), 1)+ self.assertEqual(bounded.totalLatency, 1.5)+ self.assertEqual(bounded.totalCost, 0.02)+ self.assertEqual(bounded.inputTokens, 10)+ self.assertEqual(bounded.outputTokens, 10)++ def test_bound_events_to_date_range_keeps_sub_second_events(self):+ trace_id = str(uuid.uuid4())+ # A cutoff rounded down to the whole second would drop this event.+ bulk_create_ai_events(+ [+ {+ "event": "$ai_generation",+ "team": self.team,+ "distinct_id": "person1",+ "timestamp": datetime(2024, 12, 1, 0, 10, 0, 250000, tzinfo=UTC),+ "properties": {"$ai_trace_id": trace_id, "$ai_parent_id": trace_id, "$ai_latency": 1.0},+ }+ ]+ )++ trace = (+ TraceQueryRunner(+ team=self.team,+ query=TraceQuery(+ traceId=trace_id,+ dateRange=DateRange(date_from="2024-12-01T00:00:00Z", date_to="2024-12-01T00:10:00.500000Z"),+ ),+ bound_events_to_date_range=True,+ )+ .calculate()+ .results[0]+ )+ self.assertEqual(len(trace.events), 1)+def test_sums_distinguish_reported_zero_from_no_report(self):zero_trace_id = str(uuid.uuid4())unpriced_trace_id = str(uuid.uuid4())diff --git a/posthog/hogql_queries/ai/trace_query_runner.py b/posthog/hogql_queries/ai/trace_query_runner.pyindex 65282222a20b..ef983d3e3d3f 100644--- a/posthog/hogql_queries/ai/trace_query_runner.py+++ b/posthog/hogql_queries/ai/trace_query_runner.py@@ -74,13 +74,33 @@ class TraceQueryDateRange(QueryDateRange):def date_to(self) -> datetime:return super().date_to() + timedelta(minutes=self.FORWARD_CAPTURE_RANGE_MINUTES)+ def date_to_for_filtering_as_hogql(self) -> ast.Expr:+ # `format_date` rounds down to a whole second, which would drop the events inside the final+ # second of the bound. Event timestamps carry microseconds, so the bound carries them too.+ return ast.Call(+ name="assumeNotNull",+ args=[+ ast.Call(+ name="toDateTime64",+ args=[+ ast.Constant(value=self.date_to_for_filtering().strftime("%Y-%m-%d %H:%M:%S.%f")),+ ast.Constant(value=6),+ ],+ )+ ],+ )+class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):query: TraceQuerycached_response: CachedTraceQueryResponse- def __init__(self, *args: Any, **kwargs: Any):+ def __init__(self, *args: Any, bound_events_to_date_range: bool = False, **kwargs: Any):super().__init__(*args, **kwargs)+ # The trace view wants the whole trace whatever the date picker says, so the default reads+ # `ai_events` unbounded. A caller that grades a trace "as of" an instant opts in here, which+ # holds the event rows to `dateRange.date_to` before the SQL aggregates the totals.+ self._bound_events_to_date_range = bound_events_to_date_rangedef _calculate(self):query_result = query_ai_events(@@ -247,6 +267,9 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):**super().get_cache_payload(),# When the response schema changes, increment this version to invalidate the cache."schema_version": 11,+ # Not part of the query schema, but it changes the rows the response is built from, so+ # a bounded and an unbounded read of the same trace must not share a cache entry.+ "bound_events_to_date_range": self._bound_events_to_date_range,}@cached_property@@ -278,6 +301,18 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):])+ if self._bound_events_to_date_range:+ # `date_to_as_hogql` above carries the 7 day forward buffer, which is wider than the+ # caller's bound, so the exact upper bound is added as its own clause. Only the upper+ # bound: a lower bound would drop the early events of the trace.+ where_exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq,+ left=ast.Field(chain=["ai_events", "timestamp"]),+ right=self._date_range.date_to_for_filtering_as_hogql(),+ )+ )+where_exprs.append(ast.CompareOperation(left=ast.Field(chain=["trace_id"]),diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 85adfca32709..90cff6ece2b8 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -857,6 +857,7 @@ field_exclusions: dict[AuditableScope, list[str]] = {"directory",# Reverse relations — auto-managed by FK creates, not user intent."reports",+ "backfills",],"SignalScoutConfig": [# Run bookkeeping, not user intent — keep it out of change detection even when itdiff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 8f8c7e32f45c..ae97a84a8d30 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -279,6 +279,12 @@ SURFACING_SCORING_SWEEP_TASK_QUEUE = SESSION_REPLAY_TASK_QUEUEWEEKLY_DIGEST_TASK_QUEUE = _set_temporal_task_queue("weekly-digest-task-queue")LLMA_EVALS_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-evals-task-queue")LLMA_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-task-queue")+# Units one evaluation backfill dispatches per tick, one tick per BACKFILL_TICK_INTERVAL.+# evaluation_backfill.py clamps this to 1..1000 where it reads the setting, because the candidate+# page crosses a Temporal activity boundary as one payload, capped at about 2 MiB.+# A tick costs one candidate query whatever it dispatches, so a larger batch means fewer ticks and+# less ClickHouse work for the same backfill.+LLMA_EVAL_BACKFILL_BATCH_SIZE: int = get_from_env("LLMA_EVAL_BACKFILL_BATCH_SIZE", 500, type_cast=int)# Defaults to the general-purpose fleet so dispatch always has a live worker; set the env to# "mcp-analytics-task-queue" to route MCP analytics clustering to a dedicated, separately-scalable# worker once one is deployed.diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.pyindex c2e826ff9252..713b879d738e 100644--- a/posthog/temporal/ai_observability/__init__.py+++ b/posthog/temporal/ai_observability/__init__.py@@ -18,6 +18,13 @@ from posthog.temporal.ai_observability.eval_reports.workflow import (GenerateAndDeliverEvalReportWorkflow,ScheduleAllEvalReportsWorkflow,)+from posthog.temporal.ai_observability.evaluation_backfill import (+ EvaluationBackfillWorkflow,+ advance_evaluation_backfill_cursor_activity,+ fail_evaluation_backfill_activity,+ find_evaluation_backfill_candidates_activity,+ prepare_evaluation_backfill_tick_activity,+)from posthog.temporal.ai_observability.evaluation_clustering import (AIObservabilityEvaluationClusteringCoordinatorWorkflow,AIObservabilityEvaluationClusteringWorkflow,@@ -47,6 +54,7 @@ from posthog.temporal.ai_observability.run_aggregate_evaluation import (RunAggregateEvaluationWorkflow,check_session_settled_activity,check_trace_settled_activity,+ find_evaluation_quiet_point_activity,)from posthog.temporal.ai_observability.run_evaluation import RunEvaluationWorkflowfrom posthog.temporal.ai_observability.run_session_evaluation import (@@ -111,6 +119,7 @@ EVAL_ACTIVITIES = [execute_session_hog_eval_activity,check_trace_settled_activity,check_session_settled_activity,+ find_evaluation_quiet_point_activity,emit_evaluation_event_activity,emit_trace_evaluation_event_activity,emit_internal_telemetry_activity,@@ -144,6 +153,8 @@ WORKFLOWS = [AIObservabilityEvaluationSamplerWorkflow,AIObservabilityEvaluationClusteringCoordinatorWorkflow,AIObservabilityEvaluationClusteringWorkflow,+ # Evaluation backfills+ EvaluationBackfillWorkflow,# Keep eval workflow registered here temporarily so orphaned workflows on general-purpose queue can completeRunEvaluationWorkflow,]@@ -181,6 +192,11 @@ ACTIVITIES = [generate_evaluation_cluster_labels_activity,compute_evaluation_cluster_aggregates_activity,emit_evaluation_cluster_events_activity,+ # Evaluation backfill activities+ prepare_evaluation_backfill_tick_activity,+ find_evaluation_backfill_candidates_activity,+ advance_evaluation_backfill_cursor_activity,+ fail_evaluation_backfill_activity,# Keep eval activities registered here temporarily so orphaned workflows on general-purpose queue can completefetch_evaluation_activity,run_local_evaluation_activity,diff --git a/posthog/temporal/ai_observability/evaluation_backfill.py b/posthog/temporal/ai_observability/evaluation_backfill.pynew file mode 100644index 000000000000..a1d93e1a9dd1--- /dev/null+++ b/posthog/temporal/ai_observability/evaluation_backfill.py@@ -0,0 +1,481 @@+"""Backfill loop: walk a date window newest-first and start one evaluation child per unit.++The `EvaluationBackfill` row holds every piece of progress, so the workflow keeps no state of its+own and continues as new after each batch, however long the window takes to drain.+"""++import asyncio+import hashlib+from dataclasses import replace+from datetime import datetime, timedelta+from enum import StrEnum+from typing import Any+from uuid import UUID++from django.conf import settings+from django.db.models import F+from django.utils import timezone++import temporalio+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError, is_cancelled_exception+from temporalio.workflow import ParentClosePolicy++from posthog.dataclasses import frozen+from posthog.models.team import Team+from posthog.sync import database_sync_to_async+from posthog.temporal.ai_observability.evaluation_event_io import as_utc_datetime+from posthog.temporal.ai_observability.evaluation_types import EVALUATION_WORKFLOW_PREFIXES+from posthog.temporal.ai_observability.evaluation_workflow_activities import RunEvaluationInputs+from posthog.temporal.ai_observability.run_aggregate_evaluation import (+ INGESTION_LAG_MARGIN_SECONDS,+ RunAggregateEvaluationInputs,+ resolve_settle_plan,+)+from posthog.temporal.common.base import PostHogWorkflow++from products.ai_observability.backend.backfill_candidates import fetch_backfill_candidates+from products.ai_observability.backend.models.evaluation_backfill import (+ ACTIVE_BACKFILL_STATUSES,+ EvaluationBackfill,+ EvaluationBackfillStatus,+)+from products.ai_observability.backend.models.evaluations import EvaluationTarget++BACKFILL_WORKFLOW_NAME = "llma-evaluation-backfill"+BACKFILL_TICK_INTERVAL = timedelta(seconds=60)+# Long enough for the slowest child: a trace evaluation can settle for its 2 hour maximum age+# before the judge even starts.+CHILD_EXECUTION_TIMEOUT = timedelta(hours=3)++ACTIVITY_TIMEOUT = timedelta(seconds=30)+# A tick that cannot reach a worker must fail rather than sit in the queue, because the loop only+# continues as new once the tick returns. The bound covers every attempt the retry policy makes.+ACTIVITY_SCHEDULE_TO_CLOSE = timedelta(minutes=10)+ACTIVITY_RETRY_POLICY = RetryPolicy(maximum_attempts=3)+# A row stuck at RUNNING blocks every later backfill through the one-active constraint, so the+# activity that clears it retries harder than an ordinary tick activity.+FAIL_BACKFILL_RETRY_POLICY = RetryPolicy(maximum_attempts=5)+# One page of candidates crosses the activity boundary as a Temporal payload, which the server+# caps at about 2 MiB, and each candidate carries user-controlled ids. A misconfigured setting+# must not push a page past that limit or make the walk stop dispatching at all.+MIN_BACKFILL_BATCH_SIZE = 1+MAX_BACKFILL_BATCH_SIZE = 1000+# A tick that keeps failing would otherwise leave the row RUNNING and the loop spinning forever.+BACKFILL_MAX_CONSECUTIVE_FAILURES = 5+++def settle_horizon(target: str, settle: dict[str, Any] | None) -> timedelta:+ """How long after its first event a unit is still being graded by the live path.++ Zero for a generation, which is complete when it lands. For a trace or a session it is the+ settle ceiling the evaluation is configured with, which reaches 7 days for a session, not the+ 24 hour default. Two things read it: the window a backfill may cover, and how far past that+ window a live verdict for one of its units can still be stamped.+ """+ if target == EvaluationTarget.GENERATION.value:+ return timedelta(0)+ plan = resolve_settle_plan(settle, target)+ return timedelta(seconds=plan.max_age_seconds + INGESTION_LAG_MARGIN_SECONDS)+++def backfill_workflow_id(backfill_id: str) -> str:+ return f"{BACKFILL_WORKFLOW_NAME}-{backfill_id}"+++@frozen+class EvaluationBackfillInputs:+ backfill_id: str+ team_id: int+ # Reset by any tick that succeeds.+ consecutive_failures: int = 0+++class TickAction(StrEnum):+ DISPATCH = "dispatch"+ # Terminal row, missing row, or an evaluation that can no longer run: the loop stops.+ FINISHED = "finished"+++@frozen+class PrepareTickOutput:+ action: TickAction+ evaluation_id: str = ""+ target: str = "generation"+ evaluation_type: str = "hog"+ settle: dict[str, Any] | None = None+ rerun_existing: bool = False+ batch_size: int = 0+++@frozen+class FindCandidatesInputs:+ backfill_id: str+ team_id: int+ limit: int+++@frozen+class CandidatePayload:+ unit_id: str+ # ISO string rather than datetime: avoids a naive/aware round trip through the payload+ # converter, and downstream consumers (anchor_timestamp, event_data["timestamp"]) want a+ # string anyway.+ unit_timestamp: str+ distinct_id: str+ session_id: str | None+ trace_id: str | None+++@frozen+class FindCandidatesOutput:+ candidates: list[CandidatePayload]+ next_cursor_timestamp: str | None+ next_cursor_unit_id: str+ exhausted: bool+ # The cursor the walk started from, threaded into the advance so it can match on it.+ started_from_cursor_timestamp: str | None+ started_from_cursor_unit_id: str+++@frozen+class AdvanceCursorInputs:+ backfill_id: str+ team_id: int+ expected_cursor_timestamp: str | None+ expected_cursor_unit_id: str+ new_cursor_timestamp: str | None+ new_cursor_unit_id: str+ dispatched_delta: int+ skipped_delta: int+ exhausted: bool+++@frozen+class AdvanceCursorOutput:+ finished: bool+++def _workflow_safe_id(value: str) -> str:+ # Trace and session ids are user-controlled and unbounded, so the live scheduler hashes long+ # ones to keep the workflow id valid. Backfill ids must collide with the live path's ids to+ # inherit its at-most-once guard, so the same threshold and hash apply here.+ return hashlib.md5(value.encode(), usedforsecurity=False).hexdigest() if len(value) > 128 else value+++@frozen+class ChildWorkflow:+ name: str+ workflow_id: str+++def child_workflow_name_and_id(+ *,+ evaluation_id: str,+ evaluation_type: str,+ target: str,+ unit_id: str,+ backfill_id: str,+ rerun_existing: bool,+) -> ChildWorkflow:+ if target == "generation":+ name = "run-evaluation"+ # The live scheduler suffixes "-ingestion"; matching it is what makes a unit the live path+ # already covered collide instead of running twice.+ workflow_id = f"{EVALUATION_WORKFLOW_PREFIXES[evaluation_type]}-{evaluation_id}-{unit_id}"+ live_suffix = "-ingestion"+ else:+ name = "run-aggregate-evaluation"+ workflow_id = f"llma-{target}-eval-{evaluation_id}-{_workflow_safe_id(unit_id)}"+ live_suffix = ""+ # A fresh id sidesteps the live path's at-most-once guard on purpose.+ workflow_id += f"-backfill-{backfill_id}" if rerun_existing else live_suffix+ return ChildWorkflow(name=name, workflow_id=workflow_id)+++def cancel_backfill(team_id: int, backfill_id: str | UUID) -> int:+ """Move a RUNNING backfill to CANCELLED, returning how many rows changed."""+ return (+ EvaluationBackfill.objects.for_team(team_id)+ .filter(pk=backfill_id, status=EvaluationBackfillStatus.RUNNING)+ .update(status=EvaluationBackfillStatus.CANCELLED, finished_at=timezone.now())+ )+++async def fail_evaluation_backfill_activity(inputs: EvaluationBackfillInputs) -> None:+ """Stop a backfill whose ticks keep failing, so the row does not stay RUNNING forever."""+ await database_sync_to_async(cancel_backfill, thread_sensitive=False)(inputs.team_id, inputs.backfill_id)+++def _prepare_backfill_tick(inputs: EvaluationBackfillInputs) -> PrepareTickOutput:+ row = (+ EvaluationBackfill.objects.for_team(inputs.team_id)+ .select_related("evaluation")+ .filter(pk=inputs.backfill_id)+ .first()+ )+ if row is None or row.status not in ACTIVE_BACKFILL_STATUSES:+ return PrepareTickOutput(action=TickAction.FINISHED)++ evaluation = row.evaluation+ # Three ways an evaluation can no longer produce a run, all ending the backfill. An unknown+ # evaluation type has no workflow id prefix, so cancelling here keeps that failure in an+ # activity rather than raising a KeyError inside workflow code. A disabled evaluation ends the+ # backfill too, because nothing would tell the loop the evaluation came back, so holding the+ # cursor would leave the row RUNNING and the workflow ticking forever.+ if evaluation.deleted or not evaluation.enabled or evaluation.evaluation_type not in EVALUATION_WORKFLOW_PREFIXES:+ cancel_backfill(inputs.team_id, inputs.backfill_id)+ return PrepareTickOutput(action=TickAction.FINISHED)++ return PrepareTickOutput(+ action=TickAction.DISPATCH,+ evaluation_id=str(row.evaluation_id),+ # The row's target, not the evaluation's: an edit mid-run must not change what the walk+ # already dispatched against.+ target=row.target,+ evaluation_type=evaluation.evaluation_type,+ settle=evaluation.target_config,+ rerun_existing=row.rerun_existing,+ batch_size=max(MIN_BACKFILL_BATCH_SIZE, min(settings.LLMA_EVAL_BACKFILL_BATCH_SIZE, MAX_BACKFILL_BATCH_SIZE)),+ )+++async def prepare_evaluation_backfill_tick_activity(inputs: EvaluationBackfillInputs) -> PrepareTickOutput:+ return await database_sync_to_async(_prepare_backfill_tick, thread_sensitive=False)(inputs)+++def _find_backfill_candidates(inputs: FindCandidatesInputs) -> FindCandidatesOutput:+ row = EvaluationBackfill.objects.for_team(inputs.team_id).select_related("evaluation").get(pk=inputs.backfill_id)+ team = Team.objects.get(pk=inputs.team_id)+ page = fetch_backfill_candidates(+ team=team,+ evaluation_id=str(row.evaluation_id),+ target=row.target,+ settle_horizon=settle_horizon(row.target, row.evaluation.target_config),+ conditions=row.conditions,+ window_start=row.window_start,+ window_end=row.window_end,+ rerun_existing=row.rerun_existing,+ cursor_timestamp=row.cursor_timestamp,+ cursor_unit_id=row.cursor_unit_id,+ limit=inputs.limit,+ )+ return FindCandidatesOutput(+ candidates=[+ CandidatePayload(+ unit_id=candidate.unit_id,+ unit_timestamp=as_utc_datetime(candidate.unit_timestamp).isoformat(),+ distinct_id=candidate.distinct_id,+ session_id=candidate.session_id,+ trace_id=candidate.trace_id,+ )+ for candidate in page.candidates+ ],+ # ClickHouse hands back naive datetimes, and the cursor is compared against a tz-aware+ # column, so it has to be stamped before it is written back.+ next_cursor_timestamp=(+ as_utc_datetime(page.next_cursor_timestamp).isoformat() if page.next_cursor_timestamp else None+ ),+ next_cursor_unit_id=page.next_cursor_unit_id,+ exhausted=page.exhausted,+ started_from_cursor_timestamp=row.cursor_timestamp.isoformat() if row.cursor_timestamp else None,+ started_from_cursor_unit_id=row.cursor_unit_id,+ )+++async def find_evaluation_backfill_candidates_activity(inputs: FindCandidatesInputs) -> FindCandidatesOutput:+ return await database_sync_to_async(_find_backfill_candidates, thread_sensitive=False)(inputs)+++def _advance_backfill_cursor(inputs: AdvanceCursorInputs) -> AdvanceCursorOutput:+ updates: dict[str, Any] = {+ "dispatched_count": F("dispatched_count") + inputs.dispatched_delta,+ "skipped_count": F("skipped_count") + inputs.skipped_delta,+ }+ if inputs.new_cursor_timestamp is not None:+ updates["cursor_timestamp"] = datetime.fromisoformat(inputs.new_cursor_timestamp)+ updates["cursor_unit_id"] = inputs.new_cursor_unit_id+ if inputs.exhausted:+ updates["status"] = EvaluationBackfillStatus.COMPLETED+ updates["finished_at"] = timezone.now()++ expected_timestamp = (+ datetime.fromisoformat(inputs.expected_cursor_timestamp) if inputs.expected_cursor_timestamp else None+ )+ row = EvaluationBackfill.objects.for_team(inputs.team_id).filter(pk=inputs.backfill_id)+ # Matching the starting cursor makes this idempotent: Temporal retries an activity whose+ # result was lost after it committed, and a second blind increment would inflate progress.+ # Filtering on RUNNING lets a concurrent cancel win over the advance.+ updated = row.filter(+ status=EvaluationBackfillStatus.RUNNING,+ cursor_timestamp=expected_timestamp,+ cursor_unit_id=inputs.expected_cursor_unit_id,+ ).update(**updates)+ if updated:+ return AdvanceCursorOutput(finished=inputs.exhausted)+ # Zero rows has two causes that end differently. If the row is no longer RUNNING, someone+ # cancelled or completed it and the loop stops. If it is still RUNNING, an earlier attempt of+ # this same advance already committed and only its result was lost, so the loop must carry on+ # from the stored cursor instead of stalling with the window half walked.+ status = row.values_list("status", flat=True).first()+ return AdvanceCursorOutput(finished=status != EvaluationBackfillStatus.RUNNING)+++async def advance_evaluation_backfill_cursor_activity(inputs: AdvanceCursorInputs) -> AdvanceCursorOutput:+ return await database_sync_to_async(_advance_backfill_cursor, thread_sensitive=False)(inputs)++[email protected](name=BACKFILL_WORKFLOW_NAME)+class EvaluationBackfillWorkflow(PostHogWorkflow):+ inputs_cls = EvaluationBackfillInputs++ @temporalio.workflow.run+ async def run(self, inputs: EvaluationBackfillInputs) -> None:+ try:+ tick = await temporalio.workflow.execute_activity(+ prepare_evaluation_backfill_tick_activity,+ inputs,+ start_to_close_timeout=ACTIVITY_TIMEOUT,+ schedule_to_close_timeout=ACTIVITY_SCHEDULE_TO_CLOSE,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ if tick.action == TickAction.FINISHED:+ return+ finished = await self._dispatch_batch(inputs, tick)+ except Exception as error:+ # A cancel reaches the workflow as a cancelled activity, which is not a tick that+ # failed. Let it end the run instead of logging it and counting it against the+ # failure budget.+ if is_cancelled_exception(error):+ raise+ await self._handle_failed_tick(inputs)+ return+ if finished:+ return++ await temporalio.workflow.sleep(BACKFILL_TICK_INTERVAL)+ temporalio.workflow.continue_as_new(replace(inputs, consecutive_failures=0))++ async def _dispatch_batch(self, inputs: EvaluationBackfillInputs, tick: PrepareTickOutput) -> bool:+ """Walk one page, start a child per unit, and advance the cursor. True ends the loop."""+ found = await temporalio.workflow.execute_activity(+ find_evaluation_backfill_candidates_activity,+ FindCandidatesInputs(backfill_id=inputs.backfill_id, team_id=inputs.team_id, limit=tick.batch_size),+ start_to_close_timeout=timedelta(seconds=120),+ schedule_to_close_timeout=ACTIVITY_SCHEDULE_TO_CLOSE,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ # A page whose children mostly went out must not be re-dispatched because one start+ # raised: the retry would collide with every child already running. The unit that failed+ # is left to a later backfill and counted as skipped, so the totals still add up.+ results = await asyncio.gather(+ *(self._start_child(inputs, tick, candidate) for candidate in found.candidates),+ return_exceptions=True,+ )+ failed = [result for result in results if isinstance(result, BaseException)]+ for error in failed:+ temporalio.workflow.logger.warning(+ "llma.evaluation_backfill_child_start_failed",+ extra={"backfill_id": inputs.backfill_id, "error": str(error)},+ )+ dispatched = sum(1 for result in results if result is True)+ skipped = len(results) - dispatched+ advance = await temporalio.workflow.execute_activity(+ advance_evaluation_backfill_cursor_activity,+ AdvanceCursorInputs(+ backfill_id=inputs.backfill_id,+ team_id=inputs.team_id,+ expected_cursor_timestamp=found.started_from_cursor_timestamp,+ expected_cursor_unit_id=found.started_from_cursor_unit_id,+ new_cursor_timestamp=found.next_cursor_timestamp,+ new_cursor_unit_id=found.next_cursor_unit_id,+ dispatched_delta=dispatched,+ skipped_delta=skipped,+ exhausted=found.exhausted,+ ),+ start_to_close_timeout=ACTIVITY_TIMEOUT,+ schedule_to_close_timeout=ACTIVITY_SCHEDULE_TO_CLOSE,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )+ return advance.finished++ async def _handle_failed_tick(self, inputs: EvaluationBackfillInputs) -> None:+ failures = inputs.consecutive_failures + 1+ temporalio.workflow.logger.exception(+ "llma.evaluation_backfill_tick_failed",+ extra={"backfill_id": inputs.backfill_id, "consecutive_failures": failures},+ )+ if failures >= BACKFILL_MAX_CONSECUTIVE_FAILURES:+ # Raising if this still fails is the whole recovery: the API asks Temporal whether the+ # row's workflow is alive before it refuses a new backfill, so a failed workflow with a+ # RUNNING row is recoverable there.+ await temporalio.workflow.execute_activity(+ fail_evaluation_backfill_activity,+ inputs,+ start_to_close_timeout=ACTIVITY_TIMEOUT,+ schedule_to_close_timeout=ACTIVITY_SCHEDULE_TO_CLOSE,+ retry_policy=FAIL_BACKFILL_RETRY_POLICY,+ )+ return+ await temporalio.workflow.sleep(BACKFILL_TICK_INTERVAL)+ temporalio.workflow.continue_as_new(replace(inputs, consecutive_failures=failures))++ async def _start_child(+ self, inputs: EvaluationBackfillInputs, tick: PrepareTickOutput, candidate: CandidatePayload+ ) -> bool:+ """Start one evaluation child. False means the unit already had a run, so it was skipped."""+ unit_id = candidate.unit_id+ child = child_workflow_name_and_id(+ evaluation_id=tick.evaluation_id,+ evaluation_type=tick.evaluation_type,+ target=tick.target,+ unit_id=unit_id,+ backfill_id=inputs.backfill_id,+ rerun_existing=tick.rerun_existing,+ )+ args: RunEvaluationInputs | RunAggregateEvaluationInputs+ if tick.target == "generation":+ args = RunEvaluationInputs(+ evaluation_id=tick.evaluation_id,+ # The child fetches the generation itself; the trace id and timestamp narrow+ # its scan.+ event_data={+ "uuid": unit_id,+ "team_id": inputs.team_id,+ "timestamp": candidate.unit_timestamp,+ "trace_id": candidate.trace_id,+ },+ backfill_id=inputs.backfill_id,+ )+ else:+ args = RunAggregateEvaluationInputs(+ evaluation_id=tick.evaluation_id,+ team_id=inputs.team_id,+ trace_id=unit_id if tick.target == "trace" else "",+ distinct_id=candidate.distinct_id,+ session_id=candidate.session_id,+ ai_session_id=unit_id if tick.target == "session" else None,+ target=tick.target,+ settle=tick.settle,+ # A historical unit is settled already, so the child skips its settling phase and+ # aggregates from this anchor.+ anchor_timestamp=candidate.unit_timestamp,+ backfill_id=inputs.backfill_id,+ )+ try:+ await temporalio.workflow.start_child_workflow(+ child.name,+ args,+ id=child.workflow_id,+ task_queue=settings.LLMA_EVALS_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ parent_close_policy=ParentClosePolicy.ABANDON,+ execution_timeout=CHILD_EXECUTION_TIMEOUT,+ )+ return True+ except WorkflowAlreadyStartedError:+ return Falsediff --git a/posthog/temporal/ai_observability/evaluation_event_io.py b/posthog/temporal/ai_observability/evaluation_event_io.pyindex 8bcb203a6ba6..c91b2bfaec06 100644--- a/posthog/temporal/ai_observability/evaluation_event_io.py+++ b/posthog/temporal/ai_observability/evaluation_event_io.py@@ -1,6 +1,18 @@+from datetime import datetimefrom typing import Any+from temporalio.exceptions import ApplicationError+from posthog.dataclasses import frozen+from posthog.utils import ensure_utc++from products.ai_observability.backend.ai_event_lookup import fetch_generation_event+++def as_utc_datetime(value: str | datetime) -> datetime:+ """Read a ClickHouse event timestamp, which reaches us as a naive datetime on a direct call+ and as an ISO string once Temporal has serialized it through a payload."""+ return ensure_utc(value if isinstance(value, datetime) else datetime.fromisoformat(value))@frozen@@ -49,3 +61,25 @@ def extract_event_tools(properties: dict[str, Any]) -> Any:`$ai_tools` drives whether the Tools section renders."""return properties.get("$ai_tools")+++def hydrate_event_reference(event_data: dict[str, Any]) -> dict[str, Any]:+ """Load the generation when `event_data` carries only a reference to it.++ Capture accepts an AI event up to 8 MiB while a Temporal payload is capped near 2 MiB, so a+ large generation cannot cross the workflow boundary at all. A backfill dispatcher therefore+ ships the uuid, plus the timestamp and trace id that turn the read into a point lookup on the+ ai_events sort key, and every activity that needs the body reads it here.+ """+ if "properties" in event_data:+ return event_data+ raw_timestamp = event_data.get("timestamp")+ event = fetch_generation_event(+ int(event_data["team_id"]),+ str(event_data["uuid"]),+ as_utc_datetime(raw_timestamp) if raw_timestamp else None,+ event_data.get("trace_id"),+ )+ if event is None:+ raise ApplicationError("Generation not found", type="generation_not_found", non_retryable=True)+ return eventdiff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex a7373d1b7cab..15be9f320179 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -16,7 +16,11 @@ from posthog.temporal.ai_observability.evaluation_errors import (terminal_user_error_result,terminal_user_error_result_from_application_error,)-from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io, extract_event_tools+from posthog.temporal.ai_observability.evaluation_event_io import (+ extract_event_io,+ extract_event_tools,+ hydrate_event_reference,+)from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResultfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messages, format_tool_definitionsfrom posthog.temporal.ai_observability.metrics import (@@ -212,7 +216,7 @@ def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActivdef _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActivityResult:evaluation = inputs.evaluation- event_data = inputs.event_data+ event_data = hydrate_event_reference(inputs.event_data)if evaluation["evaluation_type"] != "llm_judge":raise ApplicationError(diff --git a/posthog/temporal/ai_observability/evaluation_types.py b/posthog/temporal/ai_observability/evaluation_types.pyindex 9613e7a708a3..5a35886967cb 100644--- a/posthog/temporal/ai_observability/evaluation_types.py+++ b/posthog/temporal/ai_observability/evaluation_types.py@@ -1,5 +1,14 @@from typing import Any, Literal, NotRequired, Required, TypedDict+# Workflow id prefix per evaluation type. The Node scheduler builds the live path's ids from+# the same prefixes (nodejs/src/ai-observability/services/temporal.service.ts), so a backfill+# child collides with a live run of the same unit instead of evaluating it twice.+EVALUATION_WORKFLOW_PREFIXES = {+ "hog": "llma-hog-eval",+ "llm_judge": "llma-llm-eval",+ "sentiment": "llma-sentiment-eval",+}+class EvaluationActivityResult(TypedDict, total=False):"""Result produced by evaluation execution activities.diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex c44ebefea8f7..94e726b888d6 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -1,7 +1,8 @@import jsonimport uuid+import hashlibfrom dataclasses import dataclass-from datetime import datetime+from datetime import datetime, timedeltafrom typing import Anyfrom django.conf import settings@@ -17,6 +18,7 @@ from posthog.dataclasses import frozenfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_async, database_sync_to_async_poolfrom posthog.temporal.ai_observability.evaluation_errors import is_terminal_user_error_result+from posthog.temporal.ai_observability.evaluation_event_io import as_utc_datetime, hydrate_event_referencefrom posthog.temporal.ai_observability.evaluation_hog import run_hog_eval_for_eventfrom posthog.temporal.ai_observability.evaluation_llm_judge import DEFAULT_JUDGE_MODELfrom posthog.temporal.ai_observability.evaluation_sentiment import run_sentiment_eval@@ -34,10 +36,25 @@ SOURCE_AI_PROPERTIES_TO_COPY = ("$ai_prompt_name", "$ai_prompt_version")EMIT_EVALUATION_EVENT_FAILED_ERROR_TYPE = "EmitEvaluationEventFailed"-@dataclass+def backfill_verdict_timestamp(+ unit_timestamp: datetime, evaluation_id: str, backfill_id: str, unit_id: str+) -> datetime:+ """Spread a backfilled verdict inside the second its unit sits in.++ The Kafka deduplicator keys a row on (timestamp, distinct_id, team_id, event), so backfilled+ `$ai_evaluation` events that share a timestamp collide and all but one are dropped. Hashing all+ three ids keeps the offset stable across activity retries, so a retried emit still collapses+ into the original. Ingestion keeps millisecond precision, so the spread is about 1000 buckets.+ """+ digest = hashlib.sha256(f"{evaluation_id}:{backfill_id}:{unit_id}".encode()).digest()+ return unit_timestamp + timedelta(microseconds=int.from_bytes(digest[:8], "big") % 1_000_000)+++@frozenclass RunEvaluationInputs:evaluation_id: strevent_data: dict[str, Any]+ backfill_id: str | None = None@propertydef properties_to_log(self) -> dict[str, Any]:@@ -212,12 +229,13 @@ async def send_evaluation_disabled_email_activity(inputs: SendEvaluationDisabledawait database_sync_to_async(_send)()-@dataclass+@frozenclass EmitEvaluationEventInputs:evaluation: dict[str, Any]event_data: dict[str, Any]result: EvaluationActivityResultstart_time: datetime+ backfill_id: str | None = None@propertydef properties_to_log(self) -> dict[str, Any]:@@ -228,7 +246,10 @@ class EmitEvaluationEventInputs:def build_evaluation_event_properties(- evaluation: dict[str, Any], result: EvaluationActivityResult, start_time: datetime+ evaluation: dict[str, Any],+ result: EvaluationActivityResult,+ start_time: datetime,+ backfill_id: str | None = None,) -> dict[str, Any]:"""Assemble the target-independent `$ai_evaluation` properties shared by all emit paths.@@ -246,8 +267,12 @@ def build_evaluation_event_properties("$ai_evaluation_result_type": result["result_type"],"$ai_evaluation_start_time": start_time.isoformat(),"$ai_evaluation_reasoning": result["reasoning"],+ "$ai_evaluation_trigger": "backfill" if backfill_id else "live",}+ if backfill_id:+ properties["$ai_evaluation_backfill_id"] = backfill_id+if result.get("skipped"):properties["$ai_evaluation_skipped"] = Trueproperties["$ai_evaluation_skip_reason"] = result.get("skip_reason")@@ -295,11 +320,14 @@ def _evaluation_event_uuid() -> str | None:async def emit_generation_evaluation_event(inputs: EmitEvaluationEventInputs) -> None:"""Emit the $ai_evaluation event via capture_internal so it routes through the ingestionpipeline for cost calculation. A billing-limited capture drops the event without failing- the caller. The event timestamp is the workflow start time, not emit time: ingestion dedup- keys on (timestamp, event, distinct_id, token), so only a stable timestamp lets a retried- emit collapse into the original."""+ the caller. The event timestamp never comes from emit time: ingestion dedup keys on+ (timestamp, event, distinct_id, token), so only a stable timestamp lets a retried emit+ collapse into the original."""evaluation = inputs.evaluation- event_data = inputs.event_data+ # The judge path reads the same generation twice, once here and once in the judge activity.+ # Both are point lookups on the ai_events sort key, which is cheaper than pushing an event+ # that capture accepts up to 8 MiB through a Temporal payload capped near 2 MiB.+ event_data = await database_sync_to_async(hydrate_event_reference, thread_sensitive=False)(inputs.event_data)result = inputs.resultstart_time = inputs.start_time@@ -310,7 +338,7 @@ async def emit_generation_evaluation_event(inputs: EmitEvaluationEventInputs) ->else event_data["properties"])- properties = build_evaluation_event_properties(evaluation, result, start_time)+ properties = build_evaluation_event_properties(evaluation, result, start_time, inputs.backfill_id)properties.update({"$ai_target_event_id": event_data["uuid"],@@ -331,7 +359,18 @@ async def emit_generation_evaluation_event(inputs: EmitEvaluationEventInputs) ->event_name="$ai_evaluation",event_source="llm_analytics_evaluation",distinct_id=event_data["distinct_id"],- timestamp=start_time,+ # A backfilled verdict sits at its generation's time so time-bucketed views line it+ # up with the trace it grades instead of with the day the backfill ran.+ timestamp=(+ backfill_verdict_timestamp(+ as_utc_datetime(event_data["timestamp"]),+ str(evaluation["id"]),+ inputs.backfill_id,+ str(event_data["uuid"]),+ )+ if inputs.backfill_id+ else start_time+ ),properties=properties,event_uuid=_evaluation_event_uuid(),)@@ -409,6 +448,7 @@ class RunLocalEvaluationInputs:evaluation_id: strevent_data: dict[str, Any]start_time: datetime+ backfill_id: str | None = None@propertydef properties_to_log(self) -> dict[str, Any]:@@ -443,12 +483,15 @@ async def run_local_evaluation_activity(inputs: RunLocalEvaluationInputs) -> Locevaluation = await database_sync_to_async_pool(fetch_evaluation)(inputs.evaluation_id, inputs.event_data["team_id"])evaluation_type = evaluation.get("evaluation_type", "llm_judge")+ if evaluation_type not in ("hog", "sentiment"):+ # An llm_judge returns before the read: its own activity hydrates what it grades.+ return LocalEvaluationOutcome(evaluation=evaluation, result=None, emitted=False)++ event_data = await database_sync_to_async(hydrate_event_reference, thread_sensitive=False)(inputs.event_data)if evaluation_type == "hog":- result = await run_hog_eval_for_event(evaluation, inputs.event_data)- elif evaluation_type == "sentiment":- result = await run_sentiment_eval(evaluation, inputs.event_data)+ result = await run_hog_eval_for_event(evaluation, event_data)else:- return LocalEvaluationOutcome(evaluation=evaluation, result=None, emitted=False)+ result = await run_sentiment_eval(evaluation, event_data)emitted = Falseif not is_terminal_user_error_result(result):@@ -456,9 +499,10 @@ async def run_local_evaluation_activity(inputs: RunLocalEvaluationInputs) -> Locawait emit_generation_evaluation_event(EmitEvaluationEventInputs(evaluation=evaluation,- event_data=inputs.event_data,+ event_data=event_data,result=result,start_time=inputs.start_time,+ backfill_id=inputs.backfill_id,))except Exception as error:diff --git a/posthog/temporal/ai_observability/run_aggregate_evaluation.py b/posthog/temporal/ai_observability/run_aggregate_evaluation.pyindex ec64af1b24d8..98b9ef585dfc 100644--- a/posthog/temporal/ai_observability/run_aggregate_evaluation.py+++ b/posthog/temporal/ai_observability/run_aggregate_evaluation.py@@ -33,6 +33,7 @@ from posthog.dataclasses import frozenfrom posthog.hogql_queries.ai.ai_table_resolver import query_ai_eventsfrom posthog.models.team import Teamfrom posthog.temporal.ai_observability.evaluation_errors import is_terminal_user_error_result+from posthog.temporal.ai_observability.evaluation_event_io import as_utc_datetimefrom posthog.temporal.ai_observability.evaluation_llm_judge import LLM_JUDGE_RETRY_POLICYfrom posthog.temporal.ai_observability.evaluation_workflow_activities import (EmitInternalTelemetryInputs,@@ -245,6 +246,94 @@ def check_session_settled_activity(inputs: CheckSessionSettledInputs) -> str:return last_seen.isoformat()+# Bounds the array the quiet-point query builds. A unit with more liveness events than this is+# past every evaluation cap already, so the fetch skips it whatever window we pick.+QUIET_POINT_MAX_EVENTS = SESSION_RUNAWAY_CIRCUIT_BREAKER_EVENTS++# Reads the client-set `timestamp`, not the arrival `_timestamp` the live probe polls on: the gap+# this looks for has to sit on the same clock the fetch bounds by, or the window would cut the+# transcript somewhere the events do not.+_QUIET_POINT_SQL = """+SELECT arraySort(groupArray(timestamp)) AS timestamps+FROM (+ SELECT timestamp+ FROM posthog.ai_events AS ai_events+ WHERE event IN {liveness_events}+ AND {unit_predicate}+ AND timestamp >= {window_start}+ AND timestamp <= {window_cap}+ ORDER BY timestamp ASC+ LIMIT {max_events}+)+"""+++@frozen+class FindQuietPointInputs:+ team_id: int+ target: str+ unit_id: str+ window_start: str+ quiet_period_seconds: int+ max_age_seconds: int++ @property+ def properties_to_log(self) -> dict[str, Any]:+ return {"team_id": self.team_id, "target": self.target, "unit_id": self.unit_id}+++def _quiet_point(timestamps: list[datetime], window_start: datetime, quiet: timedelta, cap: datetime) -> datetime:+ """The instant an inactivity-settled run would have graded this unit.++ The live path polls until the unit has been silent for the quiet period, then reads up to that+ moment, so events after the first long gap never reach its verdict. A historical unit has all+ its events already, so the same point is the first gap of at least the quiet period.+ """+ for index, timestamp in enumerate(timestamps):+ following = timestamps[index + 1] if index + 1 < len(timestamps) else None+ if following is None or following - timestamp >= quiet:+ return min(timestamp + quiet, cap)+ return cap+++@close_db_connections+def find_evaluation_quiet_point_activity(inputs: FindQuietPointInputs) -> str:+ """Where an inactivity-settled backfill stops reading a unit, as an ISO timestamp."""+ team = Team.objects.get(id=inputs.team_id)+ window_start = as_utc_datetime(inputs.window_start)+ quiet = timedelta(seconds=inputs.quiet_period_seconds + INGESTION_LAG_MARGIN_SECONDS)+ cap = window_start + timedelta(seconds=inputs.max_age_seconds + INGESTION_LAG_MARGIN_SECONDS)+ unit_field = "session_id" if inputs.target == "session" else "trace_id"+ with tags_context(product=Product.LLM_ANALYTICS):+ result = query_ai_events(+ query=parse_select(_QUIET_POINT_SQL),+ placeholders={+ "liveness_events": ast.Constant(value=list(_LIVENESS_EVENTS)),+ "unit_predicate": ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["ai_events", unit_field]),+ right=ast.Constant(value=inputs.unit_id),+ ),+ "window_start": ast.Constant(value=window_start),+ "window_cap": ast.Constant(value=cap),+ "max_events": ast.Constant(value=QUIET_POINT_MAX_EVENTS),+ },+ team=team,+ query_type="EvaluationBackfillQuietPoint",+ fall_back_to_events=False,+ workload=Workload.OFFLINE,+ )+ rows = result.results or []+ timestamps = [as_utc_datetime(value) if isinstance(value, str) else value for value in (rows[0][0] if rows else [])]+ return _quiet_point(+ [timestamp.replace(tzinfo=UTC) if timestamp.tzinfo is None else timestamp for timestamp in timestamps],+ window_start,+ quiet,+ cap,+ ).isoformat()++def _clamp(value: Any, floor: int, ceiling: int, default: int) -> int:if not isinstance(value, (int, float)) or isinstance(value, bool):return default@@ -326,7 +415,7 @@ def resolve_settle_plan(settle: dict[str, Any] | None, target: str = "trace") ->return SettlePlan(strategy="fixed_window", primary_seconds=window, max_age_seconds=window)-@dataclass+@frozenclass RunAggregateEvaluationInputs:evaluation_id: strteam_id: int@@ -336,6 +425,8 @@ class RunAggregateEvaluationInputs:ai_session_id: str | None = Nonetarget: str = "trace"settle: dict[str, Any] | None = None+ anchor_timestamp: str | None = None+ backfill_id: str | None = None@propertydef properties_to_log(self) -> dict[str, Any]:@@ -384,7 +475,15 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):@temporalio.workflow.runasync def run(self, inputs: RunAggregateEvaluationInputs) -> WorkflowResult:- window_start = temporalio.workflow.now()+ # A historical unit is settled by definition, so a backfill skips the settle wait and+ # aggregates from the anchor, its first matching generation. Live starts carry no anchor,+ # so old histories never take this branch and it needs no patch marker.+ is_backfill = inputs.anchor_timestamp is not None+ window_start = (+ as_utc_datetime(inputs.anchor_timestamp)+ if inputs.anchor_timestamp is not None+ else temporalio.workflow.now()+ )# Fail loudly rather than falling through to the trace path, which would grade `trace_id`# and emit a trace-shaped verdict under a session evaluation's name. Unreachable from the@@ -397,7 +496,38 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):plan = resolve_settle_plan(inputs.settle, inputs.target)is_session = inputs.target == "session" and inputs.ai_session_id is not None- if plan.strategy == "inactivity":++ # A backfilled unit is graded over the span the live path would have covered from its+ # anchor, so events that arrived after that span stay out of the verdict.+ window_end: str | None = None+ if is_backfill:+ window_end = (+ window_start + timedelta(seconds=plan.max_age_seconds + INGESTION_LAG_MARGIN_SECONDS)+ ).isoformat()+ if plan.strategy == "inactivity":+ # Under inactivity the live path stops at the first long gap, which is usually far+ # short of the maximum age. Reading to the ceiling instead would hand the judge a+ # transcript live never saw, and a long enough unit would cross the size cap and+ # come back skipped where live returned a verdict.+ unit_id = inputs.trace_id+ if is_session and inputs.ai_session_id is not None:+ unit_id = inputs.ai_session_id+ quiet_point: str = await temporalio.workflow.execute_activity(+ find_evaluation_quiet_point_activity,+ FindQuietPointInputs(+ team_id=inputs.team_id,+ target=inputs.target,+ unit_id=unit_id,+ window_start=window_start.isoformat(),+ quiet_period_seconds=plan.primary_seconds,+ max_age_seconds=plan.max_age_seconds,+ ),+ start_to_close_timeout=timedelta(seconds=60),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ window_end = quiet_point++ if plan.strategy == "inactivity" and not is_backfill:# Sleep past the lag margin too: a probe at exactly quiet_period can never pass# the `quiet_period + margin` settled bar, so it would burn a poll for nothing.initial_sleep_seconds = min(plan.primary_seconds + INGESTION_LAG_MARGIN_SECONDS, plan.max_age_seconds)@@ -450,7 +580,7 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):await asyncio.sleep(remaining)else:raise- elif plan.primary_seconds:+ elif plan.primary_seconds and not is_backfill:await asyncio.sleep(plan.primary_seconds)eval_start = temporalio.workflow.now()@@ -481,6 +611,7 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):team_id=inputs.team_id,session_id=inputs.ai_session_id,window_start=window_start.isoformat(),+ window_end=window_end,)if evaluation_type == "hog":result = await temporalio.workflow.execute_activity(@@ -509,6 +640,7 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):team_id=inputs.team_id,trace_id=inputs.trace_id,window_start=window_start.isoformat(),+ window_end=window_end,)if evaluation_type == "hog":@@ -555,6 +687,8 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):start_time=eval_start,target=inputs.target,ai_session_id=inputs.ai_session_id,+ backfill_id=inputs.backfill_id,+ event_timestamp=inputs.anchor_timestamp,),schedule_to_close_timeout=timedelta(seconds=30),retry_policy=RetryPolicy(maximum_attempts=3),diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.pyindex ce7bba85f823..0c5b62a003ff 100644--- a/posthog/temporal/ai_observability/run_evaluation.py+++ b/posthog/temporal/ai_observability/run_evaluation.py@@ -250,6 +250,7 @@ class RunEvaluationWorkflow(PostHogWorkflow):return RunEvaluationInputs(evaluation_id=inputs[0],event_data=json.loads(inputs[1]),+ backfill_id=inputs[2] if len(inputs) > 2 else None,)@temporalio.workflow.run@@ -260,6 +261,11 @@ class RunEvaluationWorkflow(PostHogWorkflow):start_time = temporalio.workflow.now()+ # A backfill dispatcher ships only a reference, because capture accepts an AI event up to+ # 8 MiB while a Temporal payload is capped near 2 MiB, so a large generation cannot cross+ # this boundary at all. Each activity that needs the body now reads it itself.+ event_data = inputs.event_data+# One activity fetches the evaluation and, for hog and sentiment, also executes it and# emits its event, so three Temporal Cloud actions become one for these local evaluation# types, which are the large majority of volume.@@ -272,8 +278,9 @@ class RunEvaluationWorkflow(PostHogWorkflow):run_local_evaluation_activity,RunLocalEvaluationInputs(evaluation_id=inputs.evaluation_id,- event_data=inputs.event_data,+ event_data=event_data,start_time=start_time,+ backfill_id=inputs.backfill_id,),start_to_close_timeout=timedelta(seconds=120),# Total deadline including queue wait: without it a task stuck in the queue@@ -305,14 +312,14 @@ class RunEvaluationWorkflow(PostHogWorkflow):if evaluation_type == "hog":result = await temporalio.workflow.execute_activity(execute_hog_eval_activity,- args=[evaluation, inputs.event_data],+ args=[evaluation, event_data],schedule_to_close_timeout=timedelta(seconds=30),retry_policy=RetryPolicy(maximum_attempts=1),)elif evaluation_type == "sentiment":result = await temporalio.workflow.execute_activity(execute_sentiment_eval_activity,- args=[evaluation, inputs.event_data],+ args=[evaluation, event_data],schedule_to_close_timeout=timedelta(seconds=120),retry_policy=RetryPolicy(maximum_attempts=1),)@@ -320,7 +327,7 @@ class RunEvaluationWorkflow(PostHogWorkflow):try:result = await temporalio.workflow.execute_activity(execute_llm_judge_activity,- ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=inputs.event_data),+ ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data),schedule_to_close_timeout=timedelta(minutes=6),retry_policy=LLM_JUDGE_RETRY_POLICY,)@@ -356,11 +363,16 @@ class RunEvaluationWorkflow(PostHogWorkflow):emit_evaluation_event_activity,EmitEvaluationEventInputs(evaluation=evaluation,- event_data=inputs.event_data,+ event_data=event_data,result=result,start_time=start_time,+ backfill_id=inputs.backfill_id,),- schedule_to_close_timeout=timedelta(seconds=30),+ # The activity reads the generation itself when it was handed a reference, and+ # that event can run to several MiB, so it gets the same budget as the local+ # evaluation activity rather than the 30s a capture call alone would need.+ start_to_close_timeout=timedelta(seconds=120),+ schedule_to_close_timeout=timedelta(minutes=8),retry_policy=RetryPolicy(maximum_attempts=3),)except Exception:@@ -395,8 +407,8 @@ class RunEvaluationWorkflow(PostHogWorkflow):and result.get("verdict") is Trueand result.get("reasoning")):- event_uuid = inputs.event_data.get("uuid", "")- properties = inputs.event_data.get("properties", {})+ event_uuid = event_data.get("uuid", "")+ properties = event_data.get("properties", {})if isinstance(properties, str):properties = json.loads(properties)@@ -406,7 +418,7 @@ class RunEvaluationWorkflow(PostHogWorkflow):evaluation_name=evaluation.get("name", "Unknown evaluation"),evaluation_prompt=(evaluation.get("evaluation_config") or {}).get("prompt", ""),event_uuid=event_uuid,- event_type=inputs.event_data.get("event", ""),+ event_type=event_data.get("event", ""),trace_id=properties.get("$ai_trace_id", ""),reasoning=result.get("reasoning", ""),model=result.get("model", ""),diff --git a/posthog/temporal/ai_observability/run_session_evaluation.py b/posthog/temporal/ai_observability/run_session_evaluation.pyindex dd09261f1185..feb56b57cb10 100644--- a/posthog/temporal/ai_observability/run_session_evaluation.py+++ b/posthog/temporal/ai_observability/run_session_evaluation.py@@ -22,6 +22,7 @@ from posthog.hogql.parser import parse_selectfrom posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Product, tags_context+from posthog.dataclasses import frozenfrom posthog.hogql_queries.ai.ai_table_resolver import query_ai_eventsfrom posthog.hogql_queries.ai.session_query_runner import SessionQueryRunnerfrom posthog.models.team import Team@@ -217,7 +218,9 @@ def _count_session_events(team: Team, session_id: str, date_from: datetime, datereturn _SessionEventCount(event_count=int(event_count), first_seen=first_seen)-def fetch_session_for_evaluation(team_id: int, session_id: str, window_start: datetime) -> SessionFetchOutcome:+def fetch_session_for_evaluation(+ team_id: int, session_id: str, window_start: datetime, window_end: datetime | None = None+) -> SessionFetchOutcome:"""Fetch every trace of a session for an online evaluation, bounded by retention.Deliberately not bounded by `max_age_seconds`: that's a forward budget (how long the workflow@@ -231,7 +234,7 @@ def fetch_session_for_evaluation(team_id: int, session_id: str, window_start: da"""team = Team.objects.get(id=team_id)retention_floor = window_start - timedelta(days=AI_EVENTS_RETENTION_DAYS)- date_to = datetime.now(UTC)+ date_to = window_end or datetime.now(UTC)preflight = _count_session_events(team, session_id, retention_floor, date_to)if preflight.event_count == 0:@@ -383,12 +386,19 @@ def build_session_skip_result(allows_na: bool, skip_reason: str) -> EvaluationAcreturn result-@dataclass+@frozenclass ExecuteSessionEvaluationInputs:evaluation: dict[str, Any]team_id: intsession_id: strwindow_start: str+ # Upper bound of the fetch, ISO. Unset on a live run, which reads up to now; a backfilled run+ # sets it so an old unit is graded over the same span the live path would have covered.+ window_end: str | None = None++ @property+ def window_end_datetime(self) -> datetime | None:+ return datetime.fromisoformat(self.window_end) if self.window_end else None@propertydef properties_to_log(self) -> dict[str, Any]:@@ -432,6 +442,7 @@ def execute_session_llm_judge_activity(inputs: ExecuteSessionEvaluationInputs) -inputs.team_id,inputs.session_id,datetime.fromisoformat(inputs.window_start),+ inputs.window_end_datetime,)if outcome.skip_reason or outcome.traces is None:return build_session_skip_result(allows_na, outcome.skip_reason or "session_not_found")@@ -470,6 +481,7 @@ async def execute_session_hog_eval_activity(inputs: ExecuteSessionEvaluationInpuinputs.team_id,inputs.session_id,datetime.fromisoformat(inputs.window_start),+ inputs.window_end_datetime,)if outcome.skip_reason or outcome.traces is None:return None, outcome.skip_reason or "session_not_found"diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex 7cdf585ef29a..e5ddf21395d9 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -30,12 +30,13 @@ from posthog.hogql import astfrom posthog.hogql.parser import parse_selectfrom posthog.api.capture import CaptureInternalError+from posthog.dataclasses import frozenfrom posthog.hogql_queries.ai.ai_table_resolver import query_ai_eventsfrom posthog.hogql_queries.ai.trace_query_runner import TraceQueryRunnerfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_errors import is_terminal_user_error_result-from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io+from posthog.temporal.ai_observability.evaluation_event_io import as_utc_datetime, extract_event_iofrom posthog.temporal.ai_observability.evaluation_hog import (build_hog_event_global,execute_hog_eval_bytecode,@@ -56,6 +57,7 @@ from posthog.temporal.ai_observability.evaluation_types import EvaluationActivitfrom posthog.temporal.ai_observability.evaluation_workflow_activities import (EmitInternalTelemetryInputs,RunEvaluationInputs,+ backfill_verdict_timestamp,build_evaluation_event_properties,emit_internal_telemetry_activity,fetch_evaluation_activity,@@ -138,12 +140,19 @@ class RunTraceEvaluationInputs:}-@dataclass+@frozenclass ExecuteTraceEvaluationInputs:evaluation: dict[str, Any]team_id: inttrace_id: strwindow_start: str+ # Upper bound of the fetch, ISO. Unset on a live run, which reads up to now; a backfilled run+ # sets it so an old unit is graded over the same span the live path would have covered.+ window_end: str | None = None++ @property+ def window_end_datetime(self) -> datetime | None:+ return datetime.fromisoformat(self.window_end) if self.window_end else None@propertydef properties_to_log(self) -> dict[str, Any]:@@ -205,9 +214,14 @@ def _sum_trace_payload_bytes(team: Team, trace_id: str, date_from: datetime, datreturn int(result.results[0][0] or 0)-def _fetch_trace(team: Team, trace_id: str, date_from: datetime, date_to: datetime) -> TraceFetchOutcome:+def _fetch_trace(+ team: Team, trace_id: str, date_from: datetime, date_to: datetime, *, bound_to_date_to: bool = False+) -> TraceFetchOutcome:"""Fetch a single full trace from ClickHouse over an explicit window, with a cheap count- preflight so degenerate traces are skipped before pulling their payload."""+ preflight so degenerate traces are skipped before pulling their payload.++ `bound_to_date_to` grades the trace as of `date_to`. A live run leaves it off and reads the+ whole trace, which is what it graded before backfills existed."""event_count = _count_trace_events(team, trace_id, date_from, date_to)if event_count == 0:return TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=0)@@ -231,19 +245,32 @@ def _fetch_trace(team: Team, trace_id: str, date_from: datetime, date_to: datetidateRange=DateRange(date_from=date_from.isoformat(), date_to=date_to.isoformat()),tags=QueryLogTags(productKey="AIObservability"),),+ # Without this the runner returns the whole trace whatever `dateRange` says, so a backfilled+ # run would grade events that the live run never saw, and its totals would report cost and+ # latency from them. The runner applies the upper bound only. A lower bound would cut off the+ # early events of the trace, which live runs do grade.+ bound_events_to_date_range=bound_to_date_to,)response = runner.calculate()if not response.results:return TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=event_count)- return TraceFetchOutcome(trace=response.results[0], skip_reason=None, event_count=event_count)+ trace = response.results[0]+ if bound_to_date_to and not trace.events:+ # The count preflight includes the `$ai_trace` root row, which never reaches `events`, so a+ # non-zero count does not promise a transcript. Once the bound applies, an empty one must+ # skip rather than let the judge grade nothing. A live run keeps its own handling of this.+ return TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=event_count)+ return TraceFetchOutcome(trace=trace, skip_reason=None, event_count=event_count)-def fetch_trace_for_evaluation(team_id: int, trace_id: str, window_start: datetime) -> TraceFetchOutcome:+def fetch_trace_for_evaluation(+ team_id: int, trace_id: str, window_start: datetime, window_end: datetime | None = None+) -> TraceFetchOutcome:"""Fetch the full trace for an online evaluation run, looking back from the workflow start."""team = Team.objects.get(id=team_id)date_from = window_start - TRACE_EVENTS_LOOKBACK- date_to = datetime.now(UTC)- return _fetch_trace(team, trace_id, date_from, date_to)+ date_to = window_end or datetime.now(UTC)+ return _fetch_trace(team, trace_id, date_from, date_to, bound_to_date_to=window_end is not None)@dataclass@@ -543,7 +570,9 @@ def execute_trace_llm_judge_activity(inputs: ExecuteTraceEvaluationInputs) -> Evallows_na = evaluation.get("output_config", {}).get("allows_na", False)- outcome = fetch_trace_for_evaluation(inputs.team_id, inputs.trace_id, datetime.fromisoformat(inputs.window_start))+ outcome = fetch_trace_for_evaluation(+ inputs.team_id, inputs.trace_id, datetime.fromisoformat(inputs.window_start), inputs.window_end_datetime+ )if outcome.skip_reason or outcome.trace is None:return _build_trace_skip_result(allows_na, outcome.skip_reason or "trace_not_found")@@ -574,7 +603,7 @@ async def execute_trace_hog_eval_activity(inputs: ExecuteTraceEvaluationInputs)def _execute() -> tuple[dict[str, Any] | None, str | None]:outcome = fetch_trace_for_evaluation(- inputs.team_id, inputs.trace_id, datetime.fromisoformat(inputs.window_start)+ inputs.team_id, inputs.trace_id, datetime.fromisoformat(inputs.window_start), inputs.window_end_datetime)if outcome.skip_reason or outcome.trace is None:return None, outcome.skip_reason or "trace_not_found"@@ -589,7 +618,7 @@ async def execute_trace_hog_eval_activity(inputs: ExecuteTraceEvaluationInputs)return finalize_hog_eval_result(result, evaluation=evaluation, allows_na=allows_na, unit_label="trace")-@dataclass+@frozenclass EmitTraceEvaluationEventInputs:evaluation: dict[str, Any]team_id: int@@ -600,6 +629,8 @@ class EmitTraceEvaluationEventInputs:start_time: datetimetarget: str = "trace"ai_session_id: str | None = None+ backfill_id: str | None = None+ event_timestamp: str | None = None@propertydef properties_to_log(self) -> dict[str, Any]:@@ -618,7 +649,9 @@ async def emit_trace_evaluation_event_activity(inputs: EmitTraceEvaluationEventIdef _emit():# No single source event to inherit from, so SOURCE_AI_PROPERTIES_TO_COPY (span/parent# linkage copied in the generation path) intentionally does not apply here.- properties = build_evaluation_event_properties(inputs.evaluation, inputs.result, inputs.start_time)+ properties = build_evaluation_event_properties(+ inputs.evaluation, inputs.result, inputs.start_time, inputs.backfill_id+ )if inputs.target == "session" and inputs.ai_session_id:properties.update({@@ -642,12 +675,25 @@ async def emit_trace_evaluation_event_activity(inputs: EmitTraceEvaluationEventI})+ # A backfilled verdict sits at its unit's own time so time-bucketed views line it up with+ # the trace it grades instead of with the day the backfill ran. The dispatcher always+ # sends the anchor and the backfill id together, so there is no third case.+ if inputs.event_timestamp and inputs.backfill_id:+ timestamp = backfill_verdict_timestamp(+ as_utc_datetime(inputs.event_timestamp),+ str(inputs.evaluation["id"]),+ inputs.backfill_id,+ str(properties["$ai_target_id"]),+ )+ else:+ timestamp = datetime.now(UTC)+capture_internal_for_team(team_id=inputs.team_id,event_name="$ai_evaluation",event_source="llm_analytics_evaluation",distinct_id=inputs.distinct_id,- timestamp=datetime.now(UTC),+ timestamp=timestamp,properties=properties,)diff --git a/posthog/temporal/ai_observability/test_evaluation_backfill.py b/posthog/temporal/ai_observability/test_evaluation_backfill.pynew file mode 100644index 000000000000..9f93569e1c95--- /dev/null+++ b/posthog/temporal/ai_observability/test_evaluation_backfill.py@@ -0,0 +1,566 @@+import uuid+from datetime import UTC, datetime, timedelta+from typing import Any, cast++import pytest+from unittest.mock import AsyncMock, patch++from django.conf import settings+from django.test import override_settings++from asgiref.sync import async_to_sync+from temporalio.common import WorkflowIDReusePolicy+from temporalio.exceptions import ActivityError, CancelledError, WorkflowAlreadyStartedError+from temporalio.workflow import ParentClosePolicy++from posthog.models import Organization, Team+from posthog.temporal.ai_observability.evaluation_backfill import (+ BACKFILL_MAX_CONSECUTIVE_FAILURES,+ MAX_BACKFILL_BATCH_SIZE,+ AdvanceCursorInputs,+ AdvanceCursorOutput,+ CandidatePayload,+ EvaluationBackfillInputs,+ EvaluationBackfillWorkflow,+ FindCandidatesInputs,+ FindCandidatesOutput,+ PrepareTickOutput,+ TickAction,+ advance_evaluation_backfill_cursor_activity,+ child_workflow_name_and_id,+ fail_evaluation_backfill_activity,+ find_evaluation_backfill_candidates_activity,+ prepare_evaluation_backfill_tick_activity,+)+from posthog.temporal.ai_observability.evaluation_workflow_activities import (+ RunEvaluationInputs,+ backfill_verdict_timestamp,+)+from posthog.temporal.ai_observability.run_aggregate_evaluation import RunAggregateEvaluationInputs++from products.ai_observability.backend.backfill_candidates import BackfillCandidate, CandidatePage+from products.ai_observability.backend.models.evaluation_backfill import EvaluationBackfill, EvaluationBackfillStatus+from products.ai_observability.backend.models.evaluations import Evaluation++WINDOW_START = datetime(2026, 1, 1, tzinfo=UTC)+WINDOW_END = datetime(2026, 2, 1, tzinfo=UTC)+UNIT_TIMESTAMP = datetime(2026, 1, 15, 12, 0, tzinfo=UTC)+++class _BackfillMocks:+ def __init__(+ self,+ *,+ activity_results: dict | None = None,+ child_errors_for_ids: dict[str, Exception] | None = None,+ ) -> None:+ self.activity_results = activity_results or {}+ self.child_errors_for_ids = child_errors_for_ids or {}+ self.activity_calls: list[tuple] = []+ self.child_calls: list[dict] = []++ async def execute_activity(self, activity_fn, activity_input, **_) -> object:+ self.activity_calls.append((activity_fn, activity_input))+ result = self.activity_results.get(activity_fn)+ if isinstance(result, Exception):+ raise result+ if activity_fn is advance_evaluation_backfill_cursor_activity and activity_fn not in self.activity_results:+ return AdvanceCursorOutput(finished=False)+ return result++ async def start_child_workflow(self, *args, **kwargs) -> object:+ wid = kwargs.get("id")+ self.child_calls.append(+ {"name": args[0], "id": wid, "inputs": args[1] if len(args) > 1 else None, "kwargs": kwargs}+ )+ if wid is not None and wid in self.child_errors_for_ids:+ raise self.child_errors_for_ids[wid]+ return object()+++def _inputs() -> EvaluationBackfillInputs:+ return EvaluationBackfillInputs(backfill_id="B", team_id=42)+++def _candidate(unit_id: str) -> CandidatePayload:+ return CandidatePayload(+ unit_id=unit_id,+ unit_timestamp=UNIT_TIMESTAMP.isoformat(),+ distinct_id=f"distinct-{unit_id}",+ session_id=f"web-{unit_id}",+ trace_id=f"trace-{unit_id}",+ )+++def _tick(**overrides: Any) -> PrepareTickOutput:+ return PrepareTickOutput(action=TickAction.DISPATCH, evaluation_id="E", batch_size=100, **overrides)+++def _found(candidates: list[CandidatePayload], *, exhausted: bool = False) -> FindCandidatesOutput:+ return FindCandidatesOutput(+ candidates=candidates,+ next_cursor_timestamp=UNIT_TIMESTAMP.isoformat(),+ next_cursor_unit_id=candidates[-1].unit_id if candidates else "",+ exhausted=exhausted,+ started_from_cursor_timestamp=None,+ started_from_cursor_unit_id="",+ )+++async def _run(mocks: _BackfillMocks, inputs: EvaluationBackfillInputs | None = None):+ # `workflow.logger` reaches into the workflow runtime, which isn't set up here.+ fake_logger = type("Logger", (), {"exception": staticmethod(lambda *_a, **_kw: None)})()+ with (+ patch("temporalio.workflow.logger", fake_logger),+ patch("temporalio.workflow.execute_activity", side_effect=mocks.execute_activity),+ patch("temporalio.workflow.start_child_workflow", side_effect=mocks.start_child_workflow),+ patch("temporalio.workflow.continue_as_new") as continue_as_new,+ patch("temporalio.workflow.sleep", new=AsyncMock()),+ ):+ await EvaluationBackfillWorkflow().run(inputs or _inputs())+ return continue_as_new+++def _called(mocks: _BackfillMocks) -> list:+ return [fn for fn, _ in mocks.activity_calls]+++def _advance_input(mocks: _BackfillMocks) -> AdvanceCursorInputs:+ return next(call for fn, call in mocks.activity_calls if fn is advance_evaluation_backfill_cursor_activity)+++class TestEvaluationBackfillWorkflow:+ @pytest.mark.asyncio+ async def test_finished_tick_returns_without_dispatch(self) -> None:+ mocks = _BackfillMocks(+ activity_results={prepare_evaluation_backfill_tick_activity: PrepareTickOutput(action=TickAction.FINISHED)}+ )++ continue_as_new = await _run(mocks)++ assert _called(mocks) == [prepare_evaluation_backfill_tick_activity]+ assert mocks.child_calls == []+ continue_as_new.assert_not_called()++ @pytest.mark.asyncio+ async def test_dispatch_starts_one_child_per_candidate_and_advances_cursor(self) -> None:+ candidates = [_candidate("u1"), _candidate("u2"), _candidate("u3")]+ mocks = _BackfillMocks(+ activity_results={+ prepare_evaluation_backfill_tick_activity: _tick(),+ find_evaluation_backfill_candidates_activity: _found(candidates),+ }+ )++ continue_as_new = await _run(mocks)++ assert [call["id"] for call in mocks.child_calls] == [+ "llma-hog-eval-E-u1-ingestion",+ "llma-hog-eval-E-u2-ingestion",+ "llma-hog-eval-E-u3-ingestion",+ ]+ # ABANDON is load-bearing: the default policy terminates every child at continue_as_new.+ kwargs = mocks.child_calls[0]["kwargs"]+ assert kwargs["parent_close_policy"] == ParentClosePolicy.ABANDON+ assert kwargs["id_reuse_policy"] == WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY+ assert kwargs["task_queue"] == settings.LLMA_EVALS_TASK_QUEUE+ advance = _advance_input(mocks)+ assert (advance.dispatched_delta, advance.skipped_delta) == (3, 0)+ assert (advance.expected_cursor_timestamp, advance.expected_cursor_unit_id) == (None, "")+ assert (advance.new_cursor_timestamp, advance.new_cursor_unit_id) == (UNIT_TIMESTAMP.isoformat(), "u3")+ assert not advance.exhausted+ continue_as_new.assert_called_once()++ @pytest.mark.asyncio+ async def test_existing_child_counts_as_skipped(self) -> None:+ mocks = _BackfillMocks(+ activity_results={+ prepare_evaluation_backfill_tick_activity: _tick(),+ find_evaluation_backfill_candidates_activity: _found(+ [_candidate("u1"), _candidate("u2"), _candidate("u3")]+ ),+ },+ child_errors_for_ids={+ "llma-hog-eval-E-u2-ingestion": WorkflowAlreadyStartedError("llma-hog-eval-E-u2-ingestion", "x")+ },+ )++ await _run(mocks)++ advance = _advance_input(mocks)+ assert (advance.dispatched_delta, advance.skipped_delta) == (2, 1)++ @pytest.mark.asyncio+ async def test_exhausted_page_finishes_without_continue_as_new(self) -> None:+ mocks = _BackfillMocks(+ activity_results={+ prepare_evaluation_backfill_tick_activity: _tick(),+ find_evaluation_backfill_candidates_activity: _found([_candidate("u1")], exhausted=True),+ advance_evaluation_backfill_cursor_activity: AdvanceCursorOutput(finished=True),+ }+ )++ continue_as_new = await _run(mocks)++ assert _advance_input(mocks).exhausted+ continue_as_new.assert_not_called()++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "failing_activity",+ [prepare_evaluation_backfill_tick_activity, find_evaluation_backfill_candidates_activity],+ )+ async def test_failing_tick_continues_as_new_with_an_incremented_failure_count(self, failing_activity) -> None:+ mocks = _BackfillMocks(+ activity_results={+ prepare_evaluation_backfill_tick_activity: _tick(),+ find_evaluation_backfill_candidates_activity: _found([_candidate("u1")]),+ failing_activity: RuntimeError("postgres is down"),+ }+ )++ continue_as_new = await _run(mocks, EvaluationBackfillInputs(backfill_id="B", team_id=42))++ assert fail_evaluation_backfill_activity not in _called(mocks)+ continue_as_new.assert_called_once_with(+ EvaluationBackfillInputs(backfill_id="B", team_id=42, consecutive_failures=1)+ )++ @pytest.mark.asyncio+ async def test_a_cancelled_activity_ends_the_run_instead_of_counting_as_a_failure(self) -> None:+ # Cancelling a backfill cancels its in-flight activity, which must not read as a tick+ # that failed: the run would log an error and spend one of its five failures.+ mocks = _BackfillMocks(+ activity_results={+ prepare_evaluation_backfill_tick_activity: _tick(),+ find_evaluation_backfill_candidates_activity: ActivityError(+ "activity cancelled",+ scheduled_event_id=1,+ started_event_id=2,+ identity="test",+ activity_type="find",+ activity_id="1",+ retry_state=None,+ ),+ }+ )+ cause = CancelledError("cancelled")+ cast(ActivityError, mocks.activity_results[find_evaluation_backfill_candidates_activity]).__cause__ = cause++ with pytest.raises(ActivityError):+ await _run(mocks)++ assert fail_evaluation_backfill_activity not in _called(mocks)++ @pytest.mark.asyncio+ async def test_repeated_failures_cancel_the_backfill_instead_of_looping_forever(self) -> None:+ mocks = _BackfillMocks(+ activity_results={+ prepare_evaluation_backfill_tick_activity: _tick(),+ find_evaluation_backfill_candidates_activity: RuntimeError("clickhouse is down"),+ }+ )+ inputs = EvaluationBackfillInputs(+ backfill_id="B", team_id=42, consecutive_failures=BACKFILL_MAX_CONSECUTIVE_FAILURES - 1+ )++ continue_as_new = await _run(mocks, inputs)++ assert _called(mocks)[-1] is fail_evaluation_backfill_activity+ continue_as_new.assert_not_called()++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "target,expected",+ [+ (+ "generation",+ RunEvaluationInputs(+ evaluation_id="E",+ event_data={+ "uuid": "u1",+ "team_id": 42,+ "timestamp": UNIT_TIMESTAMP.isoformat(),+ "trace_id": "trace-u1",+ },+ backfill_id="B",+ ),+ ),+ (+ "trace",+ RunAggregateEvaluationInputs(+ evaluation_id="E",+ team_id=42,+ trace_id="u1",+ distinct_id="distinct-u1",+ session_id="web-u1",+ ai_session_id=None,+ target="trace",+ settle={"window_seconds": 30},+ anchor_timestamp=UNIT_TIMESTAMP.isoformat(),+ backfill_id="B",+ ),+ ),+ (+ "session",+ RunAggregateEvaluationInputs(+ evaluation_id="E",+ team_id=42,+ trace_id="",+ distinct_id="distinct-u1",+ session_id="web-u1",+ ai_session_id="u1",+ target="session",+ settle={"window_seconds": 30},+ anchor_timestamp=UNIT_TIMESTAMP.isoformat(),+ backfill_id="B",+ ),+ ),+ ],+ )+ async def test_child_inputs_carry_the_unit_in_the_field_its_target_reads(self, target, expected) -> None:+ mocks = _BackfillMocks(+ activity_results={+ prepare_evaluation_backfill_tick_activity: _tick(target=target, settle={"window_seconds": 30}),+ find_evaluation_backfill_candidates_activity: _found([_candidate("u1")]),+ }+ )++ await _run(mocks)++ assert mocks.child_calls[0]["inputs"] == expected+++ "target,evaluation_type,rerun_existing,unit_id,expected_name,expected_id",+ [+ ("generation", "hog", False, "U", "run-evaluation", "llma-hog-eval-E-U-ingestion"),+ ("generation", "llm_judge", True, "U", "run-evaluation", "llma-llm-eval-E-U-backfill-B"),+ ("trace", "hog", False, "U", "run-aggregate-evaluation", "llma-trace-eval-E-U"),+ ("session", "hog", False, "U", "run-aggregate-evaluation", "llma-session-eval-E-U"),+ ("trace", "hog", True, "U", "run-aggregate-evaluation", "llma-trace-eval-E-U-backfill-B"),+ # 32 hex characters is the md5 the Node scheduler falls back to past 128 characters;+ # without the same fallback a backfill child would not collide with the live path's id.+ (+ "trace",+ "hog",+ False,+ "t" * 129,+ "run-aggregate-evaluation",+ "llma-trace-eval-E-4670e99bfd94a7cdfa2de20b9a018676",+ ),+ ],+)+def test_child_workflow_ids_match_live_scheduler_unless_rerun(+ target, evaluation_type, rerun_existing, unit_id, expected_name, expected_id+) -> None:+ child = child_workflow_name_and_id(+ evaluation_id="E",+ evaluation_type=evaluation_type,+ target=target,+ unit_id=unit_id,+ backfill_id="B",+ rerun_existing=rerun_existing,+ )++ assert (child.name, child.workflow_id) == (expected_name, expected_id)+++def test_backfill_verdict_timestamps_are_stable_and_stay_inside_the_unit_second() -> None:+ first = backfill_verdict_timestamp(UNIT_TIMESTAMP, "E", "bf-1", "u1")++ assert first == backfill_verdict_timestamp(UNIT_TIMESTAMP, "E", "bf-1", "u1")+ # Each of the three ids has to move the offset, or verdicts that differ only in that id keep+ # sharing an ingestion dedup key and all but one are dropped.+ assert first != backfill_verdict_timestamp(UNIT_TIMESTAMP, "E", "bf-2", "u1")+ assert first != backfill_verdict_timestamp(UNIT_TIMESTAMP, "E2", "bf-1", "u1")+ assert first != backfill_verdict_timestamp(UNIT_TIMESTAMP, "E", "bf-1", "u2")+ # Ingestion keeps millisecond precision, so the spread is about 1000 usable buckets.+ for unit_id in ("u1", "u2", "u3"):+ offset = backfill_verdict_timestamp(UNIT_TIMESTAMP, "E", "bf-1", unit_id) - UNIT_TIMESTAMP+ assert timedelta(0) <= offset < timedelta(seconds=1)+++def backfill_data():+ organization = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=organization, name="Team")+ evaluation = Evaluation.objects.create(+ team=team,+ name="e",+ evaluation_type="hog",+ evaluation_config={"source": "return true"},+ output_type="boolean",+ output_config={},+ conditions=[],+ target="generation",+ enabled=True,+ )+ backfill = EvaluationBackfill.objects.for_team(team.id).create(+ team=team,+ evaluation=evaluation,+ window_start=WINDOW_START,+ window_end=WINDOW_END,+ target="generation",+ conditions=[],+ total_count=10,+ )+ return {"team": team, "evaluation": evaluation, "backfill": backfill}+++def _update_backfill(backfill_data, **fields) -> None:+ EvaluationBackfill.objects.for_team(backfill_data["team"].id).filter(pk=backfill_data["backfill"].id).update(+ **fields+ )+++def _activity_inputs(backfill_data) -> EvaluationBackfillInputs:+ return EvaluationBackfillInputs(backfill_id=str(backfill_data["backfill"].id), team_id=backfill_data["team"].id)+++def _advance(+ backfill_data, *, dispatched_delta: int = 1, skipped_delta: int = 0, exhausted: bool = False+) -> AdvanceCursorInputs:+ return AdvanceCursorInputs(+ backfill_id=str(backfill_data["backfill"].id),+ team_id=backfill_data["team"].id,+ expected_cursor_timestamp=None,+ expected_cursor_unit_id="",+ new_cursor_timestamp=UNIT_TIMESTAMP.isoformat(),+ new_cursor_unit_id="u3",+ dispatched_delta=dispatched_delta,+ skipped_delta=skipped_delta,+ exhausted=exhausted,+ )++[email protected]_db(transaction=True)+class TestEvaluationBackfillActivities:+ @pytest.mark.parametrize("status", [EvaluationBackfillStatus.COMPLETED, EvaluationBackfillStatus.CANCELLED, None])+ def test_prepare_returns_finished_for_missing_or_terminal_row(self, backfill_data, status) -> None:+ inputs = _activity_inputs(backfill_data)+ if status is None:+ inputs = EvaluationBackfillInputs(backfill_id=str(uuid.uuid4()), team_id=backfill_data["team"].id)+ else:+ _update_backfill(backfill_data, status=status)++ result = async_to_sync(prepare_evaluation_backfill_tick_activity)(inputs)++ assert result.action == TickAction.FINISHED++ @pytest.mark.parametrize(+ "update",+ [+ {"deleted": True},+ # No workflow id prefix exists for this type, so no child could ever be started.+ {"evaluation_type": "not_a_real_type"},+ # Nothing tells the loop a paused evaluation came back, so holding the cursor would+ # leave the row RUNNING and the workflow ticking forever.+ {"enabled": False},+ ],+ )+ def test_prepare_cancels_the_row_when_the_evaluation_cannot_run(self, backfill_data, update) -> None:+ Evaluation.objects.filter(pk=backfill_data["evaluation"].id).update(**update)++ result = async_to_sync(prepare_evaluation_backfill_tick_activity)(_activity_inputs(backfill_data))++ assert result.action == TickAction.FINISHED+ backfill_data["backfill"].refresh_from_db()+ assert backfill_data["backfill"].status == EvaluationBackfillStatus.CANCELLED+ assert backfill_data["backfill"].finished_at is not None++ @pytest.mark.parametrize(+ "configured,expected",+ [(7, 7), (0, 1), (-5, 1), (MAX_BACKFILL_BATCH_SIZE * 10, MAX_BACKFILL_BATCH_SIZE)],+ )+ def test_prepare_dispatches_with_a_clamped_batch_size(self, backfill_data, configured, expected) -> None:+ with override_settings(LLMA_EVAL_BACKFILL_BATCH_SIZE=configured):+ result = async_to_sync(prepare_evaluation_backfill_tick_activity)(_activity_inputs(backfill_data))++ assert result == PrepareTickOutput(+ action=TickAction.DISPATCH,+ evaluation_id=str(backfill_data["evaluation"].id),+ target="generation",+ evaluation_type="hog",+ # A generation evaluation carries no settle config; the model normalizes the bag to {}.+ settle={},+ rerun_existing=False,+ batch_size=expected,+ )++ def test_find_serializes_candidates_and_cursor(self, backfill_data) -> None:+ _update_backfill(backfill_data, cursor_timestamp=UNIT_TIMESTAMP + timedelta(hours=1), cursor_unit_id="u0")+ page = CandidatePage(+ candidates=[+ BackfillCandidate(+ unit_id="u1",+ unit_timestamp=UNIT_TIMESTAMP,+ distinct_id="d1",+ session_id="web-1",+ trace_id="t1",+ )+ ],+ next_cursor_timestamp=UNIT_TIMESTAMP,+ next_cursor_unit_id="u1",+ exhausted=True,+ )++ with patch(+ "posthog.temporal.ai_observability.evaluation_backfill.fetch_backfill_candidates", return_value=page+ ) as fetch:+ result = async_to_sync(find_evaluation_backfill_candidates_activity)(+ FindCandidatesInputs(+ backfill_id=str(backfill_data["backfill"].id), team_id=backfill_data["team"].id, limit=5+ )+ )++ assert fetch.call_args.kwargs["cursor_timestamp"] == UNIT_TIMESTAMP + timedelta(hours=1)+ assert fetch.call_args.kwargs["cursor_unit_id"] == "u0"+ assert fetch.call_args.kwargs["limit"] == 5+ assert result.candidates == [+ CandidatePayload(+ unit_id="u1",+ unit_timestamp=UNIT_TIMESTAMP.isoformat(),+ distinct_id="d1",+ session_id="web-1",+ trace_id="t1",+ )+ ]+ assert (result.next_cursor_timestamp, result.next_cursor_unit_id) == (UNIT_TIMESTAMP.isoformat(), "u1")+ assert (result.started_from_cursor_timestamp, result.started_from_cursor_unit_id) == (+ (UNIT_TIMESTAMP + timedelta(hours=1)).isoformat(),+ "u0",+ )+ assert result.exhausted++ def test_advance_is_idempotent_on_retry(self, backfill_data) -> None:+ advance = _advance(backfill_data, dispatched_delta=3, skipped_delta=1)++ first = async_to_sync(advance_evaluation_backfill_cursor_activity)(advance)+ second = async_to_sync(advance_evaluation_backfill_cursor_activity)(advance)++ backfill_data["backfill"].refresh_from_db()+ assert (backfill_data["backfill"].dispatched_count, backfill_data["backfill"].skipped_count) == (3, 1)+ assert backfill_data["backfill"].cursor_unit_id == "u3"+ assert not first.finished+ # The second call matched nothing because the first already moved the cursor. Reading that+ # as finished would end the loop with the row still RUNNING and the window half walked.+ assert not second.finished++ def test_advance_marks_completed_when_exhausted(self, backfill_data) -> None:+ result = async_to_sync(advance_evaluation_backfill_cursor_activity)(_advance(backfill_data, exhausted=True))++ assert result.finished+ backfill_data["backfill"].refresh_from_db()+ assert backfill_data["backfill"].status == EvaluationBackfillStatus.COMPLETED+ assert backfill_data["backfill"].finished_at is not None++ def test_advance_loses_to_concurrent_cancel(self, backfill_data) -> None:+ _update_backfill(backfill_data, status=EvaluationBackfillStatus.CANCELLED)++ result = async_to_sync(advance_evaluation_backfill_cursor_activity)(_advance(backfill_data))++ assert result.finished+ backfill_data["backfill"].refresh_from_db()+ assert backfill_data["backfill"].status == EvaluationBackfillStatus.CANCELLED+ assert backfill_data["backfill"].dispatched_count == 0diff --git a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.pyindex d2721344e0a5..0754daaf99b0 100644--- a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py@@ -15,12 +15,15 @@ from posthog.models import Organization, Teamfrom posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResultfrom posthog.temporal.ai_observability.evaluation_workflow_activities import RunEvaluationInputsfrom posthog.temporal.ai_observability.run_aggregate_evaluation import (+ INGESTION_LAG_MARGIN_SECONDS,MAX_SETTLE_POLLS_PER_RUN,CheckSessionSettledInputs,CheckTraceSettledInputs,+ FindQuietPointInputs,RunAggregateEvaluationInputs,RunAggregateEvaluationWorkflow,SettlePlan,+ _quiet_point,check_session_settled_activity,check_trace_settled_activity,resolve_poll_interval,@@ -248,7 +251,13 @@ def _mock_activities(calls: list[str], exclude: set[str] | None = None) -> list[calls.append("execute_session")return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}+ @activity.defn(name="find_evaluation_quiet_point_activity")+ async def mock_find_quiet_point(inputs: FindQuietPointInputs) -> str:+ calls.append("quiet_point")+ return QUIET_POINT+all_activities = {+ "find_evaluation_quiet_point_activity": mock_find_quiet_point,"fetch_evaluation_activity": mock_fetch_evaluation,"execute_trace_hog_eval_activity": mock_execute_trace_hog,"emit_trace_evaluation_event_activity": mock_emit,@@ -273,6 +282,35 @@ def _workflow_inputs(settle: dict[str, Any], **overrides: Any) -> RunAggregateEvreturn RunAggregateEvaluationInputs(**defaults)+QUIET_POINT = "2026-08-01T12:20:00+00:00"+++class TestQuietPoint:+ @pytest.mark.parametrize(+ "case,offsets,expected_offset",+ [+ # A gap of at least the quiet period ends the read one quiet period after the last+ # event before it, which is where the live poll would have settled.+ ("a gap in the middle", [0, 60, 3600], 60 + 1800 + INGESTION_LAG_MARGIN_SECONDS),+ # Silence after the last event, so the read ends one quiet period after it.+ ("no gap at all", [0, 60, 120], 120 + 1800 + INGESTION_LAG_MARGIN_SECONDS),+ # Every gap is shorter than the quiet period until the ceiling.+ ("activity all the way to the ceiling", [0, 1200, 2400, 3600, 4800, 6000, 7200], 7200),+ ("no events", [], 7200),+ ],+ )+ def test_reads_stop_where_an_inactivity_poll_would_have_settled(+ self, case: str, offsets: list[int], expected_offset: int+ ) -> None:+ window_start = datetime(2026, 8, 1, 12, 0, tzinfo=UTC)+ quiet = timedelta(seconds=1800 + INGESTION_LAG_MARGIN_SECONDS)+ cap = window_start + timedelta(seconds=7200)++ point = _quiet_point([window_start + timedelta(seconds=offset) for offset in offsets], window_start, quiet, cap)++ assert point == window_start + timedelta(seconds=expected_offset)++class TestRunAggregateEvaluationWorkflow:@pytest.mark.asyncioasync def test_fixed_window_sleeps_then_evaluates(self):@@ -299,6 +337,98 @@ class TestRunAggregateEvaluationWorkflow:assert elapsed >= timedelta(seconds=600)assert elapsed < timedelta(seconds=900)+ @pytest.mark.asyncio+ async def test_anchor_timestamp_skips_the_settle_window(self):+ calls: list[str] = []+ anchor = "2026-08-01T12:00:00+00:00"+ window_starts: list[str] = []+ window_ends: list[str | None] = []++ @activity.defn(name="execute_trace_hog_eval_activity")+ async def mock_execute_trace_hog(inputs: ExecuteTraceEvaluationInputs) -> EvaluationActivityResult:+ calls.append("execute")+ window_starts.append(inputs.window_start)+ window_ends.append(inputs.window_end)+ return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[RunAggregateEvaluationWorkflow],+ activities=[+ *_mock_activities(calls, exclude={"execute_trace_hog_eval_activity"}),+ mock_execute_trace_hog,+ ],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ start = await env.get_current_time()+ result = await env.client.execute_workflow(+ RunAggregateEvaluationWorkflow.run,+ _workflow_inputs(+ {"strategy": "fixed_window", "window_seconds": 1800},+ anchor_timestamp=anchor,+ backfill_id="bf-1",+ ),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )+ elapsed = (await env.get_current_time()) - start++ assert calls == ["fetch", "execute", "emit", "telemetry"]+ assert result["verdict"] is True+ assert window_starts == [datetime.fromisoformat(anchor).isoformat()]+ # Bounded to the span the live path would have covered from the anchor, so the grade does+ # not sweep in everything that arrived between the anchor and now.+ assert window_ends == [+ (datetime.fromisoformat(anchor) + timedelta(seconds=1800 + INGESTION_LAG_MARGIN_SECONDS)).isoformat()+ ]+ # Far below the 1800s window, so the settle sleep cannot have run. The slack absorbs the+ # test environment skipping an idle activity timeout.+ assert elapsed < timedelta(seconds=900)++ @pytest.mark.asyncio+ async def test_a_backfilled_inactivity_unit_reads_to_its_quiet_point(self):+ calls: list[str] = []+ anchor = "2026-08-01T12:00:00+00:00"+ window_ends: list[str | None] = []++ @activity.defn(name="execute_trace_hog_eval_activity")+ async def mock_execute_trace_hog(inputs: ExecuteTraceEvaluationInputs) -> EvaluationActivityResult:+ calls.append("execute")+ window_ends.append(inputs.window_end)+ return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[RunAggregateEvaluationWorkflow],+ activities=[+ *_mock_activities(calls, exclude={"execute_trace_hog_eval_activity"}),+ mock_execute_trace_hog,+ ],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ await env.client.execute_workflow(+ RunAggregateEvaluationWorkflow.run,+ _workflow_inputs(+ {"strategy": "inactivity", "quiet_period_seconds": 1800, "max_age_seconds": 7200},+ anchor_timestamp=anchor,+ backfill_id="bf-1",+ ),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ # The quiet point, not the maximum age: reading to the ceiling would grade a transcript+ # the live path never saw.+ assert window_ends == [QUIET_POINT]+ assert "check_trace_settled" not in calls+ assert calls[0] == "quiet_point"+@pytest.mark.asyncioasync def test_inactivity_settles_after_one_quiet_period_when_silent(self):calls: list[str] = []diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex a65952436ab2..23328ffd94e3 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -4,7 +4,7 @@ from datetime import UTC, datetimefrom typing import Anyimport pytest-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patchfrom asgiref.sync import sync_to_asyncfrom parameterized import parameterized@@ -40,8 +40,8 @@ from .evaluation_errors import (status_reason_detail_for_terminal_user_error,terminal_user_error_result_from_application_error,)-from .evaluation_llm_judge import JUDGE_EVENT_MAX_CHARS-from .evaluation_workflow_activities import LocalEvaluationOutcome+from .evaluation_llm_judge import JUDGE_EVENT_MAX_CHARS, _execute_llm_judge_activity+from .evaluation_workflow_activities import LocalEvaluationOutcome, backfill_verdict_timestampfrom .run_evaluation import (BooleanEvalResult,BooleanWithNAEvalResult,@@ -109,6 +109,23 @@ def test_terminal_user_error_result_from_application_error_uses_key_details_for_assert result["model"] == "missing-model"+HYDRATE_FETCH = "posthog.temporal.ai_observability.evaluation_event_io.fetch_generation_event"+THIN_REFERENCE = {"uuid": "g1", "team_id": 1, "timestamp": "2024-01-01T10:00:00+00:00"}+++def _local_evaluation(**overrides: Any) -> dict[str, Any]:+ return {+ "id": "eval-1",+ "name": "Local eval",+ "evaluation_type": "hog",+ "evaluation_config": {"source": "return true"},+ "output_type": "boolean",+ "output_config": {},+ "team_id": 1,+ **overrides,+ }++def create_mock_event_data(team_id: int, **overrides: Any) -> dict[str, Any]:"""Helper to create mock event data for tests"""defaults = {@@ -490,6 +507,59 @@ class TestRunEvaluationWorkflow:assert props["$ai_output_tokens"] == 18assert props["$ai_evaluation_type"] == "online"+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize(+ "expected_trigger,backfill_id",+ [+ pytest.param("live", None, id="live"),+ pytest.param("backfill", "bf-1", id="backfill"),+ ],+ )+ async def test_emit_evaluation_event_activity_stamps_trigger_and_timestamp(+ self, setup_data, expected_trigger: str, backfill_id: str | None+ ):+ team = setup_data["team"]+ event_data = create_mock_event_data(team.id, timestamp="2026-08-01T12:00:00+00:00")+ start_time = datetime(2026, 9, 1, 12, 0, 0, tzinfo=UTC)+ result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": True,+ "reasoning": "Test passed",+ "allows_na": False,+ }++ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token):+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())++ await emit_evaluation_event_activity(+ EmitEvaluationEventInputs(+ evaluation={"id": str(setup_data["evaluation"].id), "name": "Test Evaluation"},+ event_data=event_data,+ result=result,+ start_time=start_time,+ backfill_id=backfill_id,+ )+ )++ call_kwargs = mock_capture.call_args[1]+ props = call_kwargs["properties"]+ assert props["$ai_evaluation_trigger"] == expected_trigger+ if backfill_id:+ assert props["$ai_evaluation_backfill_id"] == backfill_id+ # Offset inside the unit's second, so verdicts that would share an ingestion dedup+ # key no longer do.+ assert call_kwargs["timestamp"] == backfill_verdict_timestamp(+ datetime.fromisoformat(event_data["timestamp"]),+ str(setup_data["evaluation"].id),+ backfill_id,+ str(event_data["uuid"]),+ )+ else:+ assert "$ai_evaluation_backfill_id" not in props+ assert call_kwargs["timestamp"] == start_time+@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)@pytest.mark.parametrize(@@ -695,6 +765,125 @@ class TestRunEvaluationWorkflow:assert "$ai_evaluation_result" not in propsassert "$ai_evaluation_allows_na" not in props+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "event_data,expects_thin_reference",+ [+ pytest.param({"uuid": "g1", "team_id": 1}, True, id="thin_reference_reaches_the_activity"),+ pytest.param(create_mock_event_data(team_id=1, uuid="g1"), False, id="full_event_is_used_as_is"),+ ],+ )+ async def test_the_event_never_travels_through_the_workflow(+ self, event_data: dict[str, Any], expects_thin_reference: bool+ ):+ seen_inputs: list[RunLocalEvaluationInputs] = []++ @activity.defn(name="run_local_evaluation_activity")+ async def mock_run_local_evaluation(inputs: RunLocalEvaluationInputs) -> LocalEvaluationOutcome:+ seen_inputs.append(inputs)+ return LocalEvaluationOutcome(+ evaluation=_local_evaluation(id=inputs.evaluation_id, evaluation_config={}),+ result={"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False},+ emitted=True,+ )++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[RunEvaluationWorkflow],+ activities=[mock_run_local_evaluation],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ await env.client.execute_workflow(+ RunEvaluationWorkflow.run,+ RunEvaluationInputs(evaluation_id="eval-1", event_data=event_data, backfill_id="bf-1"),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert [inputs.backfill_id for inputs in seen_inputs] == ["bf-1"]+ assert [("properties" not in inputs.event_data) for inputs in seen_inputs] == [expects_thin_reference]++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "evaluation_type",+ [pytest.param("hog", id="hog"), pytest.param("sentiment", id="sentiment")],+ )+ async def test_run_local_evaluation_activity_hydrates_a_thin_reference(self, evaluation_type: str):+ full_event = create_mock_event_data(team_id=1, uuid="g1")+ evaluation = _local_evaluation(evaluation_type=evaluation_type)+ graded: list[dict[str, Any]] = []++ async def fake_run(_evaluation: dict[str, Any], event_data: dict[str, Any]) -> EvaluationActivityResult:+ graded.append(event_data)+ return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}++ module = "posthog.temporal.ai_observability.evaluation_workflow_activities"+ with (+ patch(f"{module}.fetch_evaluation", return_value=evaluation),+ patch(HYDRATE_FETCH, return_value=full_event) as mock_fetch,+ patch(f"{module}.run_hog_eval_for_event", side_effect=fake_run),+ patch(f"{module}.run_sentiment_eval", side_effect=fake_run),+ patch(f"{module}.emit_generation_evaluation_event", new_callable=AsyncMock) as mock_emit,+ ):+ outcome = await run_local_evaluation_activity(+ RunLocalEvaluationInputs(+ evaluation_id="eval-1",+ event_data=dict(THIN_REFERENCE),+ start_time=datetime(2024, 1, 1, 12, 0, tzinfo=UTC),+ )+ )++ assert mock_fetch.call_count == 1+ assert graded == [full_event]+ assert outcome.emitted is True+ mock_emit.assert_awaited_once()+ assert mock_emit.await_args_list[0].args[0].event_data == full_event++ @pytest.mark.asyncio+ async def test_the_generation_emit_activity_hydrates_a_thin_reference(self):+ full_event = create_mock_event_data(team_id=1, uuid="g1")+ with (+ patch(HYDRATE_FETCH, return_value=full_event) as mock_fetch,+ patch(+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ ) as mock_capture,+ ):+ await emit_evaluation_event_activity(+ EmitEvaluationEventInputs(+ evaluation=_local_evaluation(evaluation_type="llm_judge"),+ event_data=dict(THIN_REFERENCE),+ result={"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False},+ start_time=datetime(2024, 1, 1, 12, 0, tzinfo=UTC),+ )+ )++ assert mock_fetch.call_count == 1+ assert mock_capture.call_args.kwargs["properties"]["$ai_target_event_id"] == full_event["uuid"]++ def test_the_llm_judge_activity_hydrates_a_thin_reference(self):+ full_event = create_mock_event_data(team_id=1, uuid="g1")+ with (+ patch(HYDRATE_FETCH, return_value=full_event) as mock_fetch,+ patch(+ "posthog.temporal.ai_observability.evaluation_llm_judge.extract_event_io",+ side_effect=AssertionError("stop after hydration"),+ ),+ ):+ with pytest.raises(AssertionError, match="stop after hydration"):+ _execute_llm_judge_activity(+ ExecuteLLMJudgeInputs(+ evaluation=_local_evaluation(+ evaluation_type="llm_judge", evaluation_config={"prompt": "grade it"}+ ),+ event_data=dict(THIN_REFERENCE),+ )+ )++ assert mock_fetch.call_count == 1+def test_parse_inputs(self):"""Test that parse_inputs correctly parses workflow inputs"""event_data = create_mock_event_data(team_id=1)@@ -2570,12 +2759,42 @@ class TestRunLocalEvaluationActivity:enabled=True,)- def _inputs(self, evaluation, team, start_time: datetime) -> RunLocalEvaluationInputs:+ def _inputs(self, evaluation, team, start_time: datetime, **overrides: Any) -> RunLocalEvaluationInputs:return RunLocalEvaluationInputs(evaluation_id=str(evaluation.id),event_data=create_mock_event_data(team.id),start_time=start_time,+ **overrides,+ )++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_backfilled_hog_eval_is_stamped_at_the_source_event(self, setup_data):+ team = setup_data["team"]+ evaluation = await sync_to_async(self._create_hog_evaluation)(team, "return true")+ inputs = RunLocalEvaluationInputs(+ evaluation_id=str(evaluation.id),+ event_data=create_mock_event_data(team.id, timestamp="2026-08-01T12:00:00+00:00"),+ start_time=self.START_TIME,+ backfill_id="bf-1",+ )++ with patch(+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ ) as mock_capture:+ await run_local_evaluation_activity(inputs)++ capture_kwargs = mock_capture.call_args.kwargs+ # Offset inside the unit's second, so verdicts that would share an ingestion dedup key+ # no longer do.+ assert capture_kwargs["timestamp"] == backfill_verdict_timestamp(+ datetime(2026, 8, 1, 12, 0, 0, tzinfo=UTC),+ str(evaluation.id),+ "bf-1",+ str(inputs.event_data["uuid"]),)+ assert capture_kwargs["properties"]["$ai_evaluation_trigger"] == "backfill"+ assert capture_kwargs["properties"]["$ai_evaluation_backfill_id"] == "bf-1"@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)diff --git a/posthog/temporal/ai_observability/test_run_session_evaluation.py b/posthog/temporal/ai_observability/test_run_session_evaluation.pyindex 9db3d4f733e1..2ef71116e560 100644--- a/posthog/temporal/ai_observability/test_run_session_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_session_evaluation.py@@ -209,6 +209,33 @@ class TestFetchSessionForEvaluation:# tail of any session past 100 traces, so the fetch must ask for the export ceiling instead.assert kwargs["query"].limit == MAX_SELECT_TRACES_LIMIT_EXPORT+ @pytest.mark.parametrize("window_end", [None, datetime(2026, 7, 20, 6, tzinfo=UTC)])+ def test_upper_bound_is_the_given_window_end_or_now(self, window_end):+ window_start = datetime(2026, 7, 20, tzinfo=UTC)+ now = datetime(2026, 7, 21, tzinfo=UTC)+ with (+ freeze_time(now),+ patch("posthog.temporal.ai_observability.run_session_evaluation.Team"),+ patch(+ "posthog.temporal.ai_observability.run_session_evaluation._sum_session_payload_bytes",+ return_value=0,+ ),+ patch(+ "posthog.temporal.ai_observability.run_session_evaluation._count_session_events",+ return_value=_SessionEventCount(event_count=3, first_seen=datetime(2026, 7, 19, tzinfo=UTC)),+ ),+ patch(+ "posthog.temporal.ai_observability.run_session_evaluation.SessionQueryRunner"+ ) as mock_session_query_runner,+ ):+ mock_session_query_runner.return_value.calculate.return_value = Mock(+ results=[_trace("t1", cost=0, latency=0)], hasMore=False+ )+ fetch_session_for_evaluation(1, "s-1", window_start, window_end)++ date_range = mock_session_query_runner.call_args.kwargs["query"].dateRange+ assert date_range.date_to == (window_end or now).isoformat()+def test_skips_a_small_session_whose_payload_is_enormous(self):"""The event count cannot see this: a handful of events carrying megabytes each sits farunder the row cap while being exactly the payload the cap exists to keep out of the worker.diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pyindex 3da5c616eb96..816186a0ebd7 100644--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -1,7 +1,7 @@import jsonimport uuidfrom datetime import UTC, datetime, timedelta-from typing import Any+from typing import Any, castimport pytestfrom freezegun import freeze_time@@ -24,6 +24,7 @@ from products.ai_observability.backend.models.provider_keys import LLMProviderKefrom .evaluation_hog import execute_hog_eval_bytecodefrom .evaluation_llm_judge import BooleanEvalResultfrom .evaluation_types import EvaluationActivityResult+from .evaluation_workflow_activities import backfill_verdict_timestampfrom .run_trace_evaluation import (JUDGE_TRACE_MAX_CHARS,MAX_TRACE_EVAL_EVENTS,@@ -284,6 +285,26 @@ class TestFetchTraceForEvaluation:assert outcome.event_count == MAX_TRACE_EVAL_EVENTS + 1mock_runner.assert_not_called()+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize("window_end", [None, FROZEN_NOW + timedelta(minutes=30)])+ def test_upper_bound_is_the_given_window_end_or_now(self, setup_data, window_end):+ team = setup_data["team"]+ trace = create_trace([create_trace_event("$ai_generation", **{"$ai_input": "q", "$ai_output": "a"})])++ with (+ freeze_time(FROZEN_NOW),+ patch("posthog.temporal.ai_observability.run_trace_evaluation._count_trace_events", return_value=1),+ patch("posthog.temporal.ai_observability.run_trace_evaluation.TraceQueryRunner") as mock_runner,+ ):+ mock_runner.return_value.calculate.return_value = MagicMock(results=[trace])+ fetch_trace_for_evaluation(team.id, "trace-123", FROZEN_NOW, window_end)++ date_range = mock_runner.call_args.kwargs["query"].dateRange+ assert date_range.date_to == (window_end or FROZEN_NOW).isoformat()+ # The runner ignores dateRange on the ai_events path unless it is asked to honor it, and+ # only a backfilled run asks: a live run grades the whole trace, as it always has.+ assert mock_runner.call_args.kwargs["bound_events_to_date_range"] is (window_end is not None)+@pytest.mark.django_db(transaction=True)def test_returns_trace_when_found(self, setup_data):team = setup_data["team"]@@ -297,6 +318,29 @@ class TestFetchTraceForEvaluation:assert outcome.skip_reason is Noneassert outcome.trace is trace+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize(+ "window_end,expected_skip",+ [(FROZEN_NOW + timedelta(minutes=30), "trace_not_found"), (None, None)],+ )+ def test_a_backfilled_trace_left_with_no_events_is_skipped(self, setup_data, window_end, expected_skip):+ team = setup_data["team"]+ empty_trace = create_trace([])++ # The count preflight sees the `$ai_trace` root row, which never reaches `events`, so the+ # bounded runner can return a trace row with no transcript to grade. A live run keeps+ # whatever it did with that row before, so only the backfilled run skips.+ with (+ freeze_time(FROZEN_NOW),+ patch("posthog.temporal.ai_observability.run_trace_evaluation._count_trace_events", return_value=2),+ patch("posthog.temporal.ai_observability.run_trace_evaluation.TraceQueryRunner") as mock_runner,+ ):+ mock_runner.return_value.calculate.return_value = MagicMock(results=[empty_trace])+ outcome = fetch_trace_for_evaluation(team.id, "trace-123", FROZEN_NOW, window_end)++ assert outcome.skip_reason == expected_skip+ assert outcome.trace is (None if expected_skip else empty_trace)+class TestRunHogEvalOverRecentTraces:@patch("posthog.temporal.ai_observability.run_trace_evaluation.query_ai_events")@@ -591,6 +635,71 @@ class TestEmitTraceEvaluationEventActivity:assert "$ai_target_event_id" not in propsassert "$ai_target_event_type" not in props+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize(+ "expected_trigger,backfill_id,event_timestamp",+ [+ pytest.param("live", None, None, id="live"),+ pytest.param("backfill", "bf-1", "2026-08-01T12:00:00+00:00", id="backfill"),+ ],+ )+ async def test_stamps_trigger_and_timestamp(+ self,+ setup_data,+ expected_trigger: str,+ backfill_id: str | None,+ event_timestamp: str | None,+ ):+ team = setup_data["team"]+ result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": True,+ "reasoning": "Looks good",+ "allows_na": False,+ }++ with (+ freeze_time(FROZEN_NOW),+ patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token),+ patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture,+ ):+ mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())++ await emit_trace_evaluation_event_activity(+ EmitTraceEvaluationEventInputs(+ evaluation=evaluation_dict(setup_data),+ team_id=team.id,+ trace_id="trace-123",+ distinct_id="test-user",+ session_id=None,+ result=result,+ start_time=datetime(2024, 1, 1, 12, 0, 0),+ backfill_id=backfill_id,+ event_timestamp=event_timestamp,+ )+ )++ call_kwargs = mock_capture.call_args[1]+ props = call_kwargs["properties"]+ assert props["$ai_evaluation_trigger"] == expected_trigger+ if backfill_id:+ assert props["$ai_evaluation_backfill_id"] == backfill_id+ else:+ assert "$ai_evaluation_backfill_id" not in props+ if event_timestamp:+ # Offset inside the unit's second, so verdicts that would share an ingestion dedup+ # key no longer do.+ assert call_kwargs["timestamp"] == backfill_verdict_timestamp(+ datetime.fromisoformat(event_timestamp),+ str(evaluation_dict(setup_data)["id"]),+ cast(str, backfill_id),+ "trace-123",+ )+ else:+ # A live verdict is stamped when it is emitted.+ assert call_kwargs["timestamp"] == FROZEN_NOW+@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)@pytest.mark.parametrize(diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex f15ba92b1de5..3f2982def728 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -202,6 +202,7 @@ class TestAIObservabilityModuleIntegrity:"AIObservabilityEvaluationClusteringCoordinatorWorkflow","AIObservabilityEvaluationClusteringWorkflow","RunEvaluationWorkflow",+ "EvaluationBackfillWorkflow",]actual_workflow_names = [w.__name__ for w in LLM_ANALYTICS_WORKFLOWS]assert len(actual_workflow_names) == len(expected_workflows), (@@ -251,6 +252,10 @@ class TestAIObservabilityModuleIntegrity:"emit_evaluation_event_activity","emit_internal_telemetry_activity","emit_eval_signal_activity",+ "prepare_evaluation_backfill_tick_activity",+ "find_evaluation_backfill_candidates_activity",+ "advance_evaluation_backfill_cursor_activity",+ "fail_evaluation_backfill_activity",]actual_activity_names = [a.__name__ for a in LLM_ANALYTICS_ACTIVITIES]assert len(actual_activity_names) == len(expected_activities), (diff --git a/products/ai_observability/backend/ai_event_lookup.py b/products/ai_observability/backend/ai_event_lookup.pynew file mode 100644index 000000000000..5e5021d9e7e1--- /dev/null+++ b/products/ai_observability/backend/ai_event_lookup.py@@ -0,0 +1,109 @@+from datetime import datetime+from typing import Any++from posthog.clickhouse.client import query_with_columns+from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.clickhouse.workload import Workload+from posthog.hogql_queries.ai.ai_table_resolver import AIEventsExpiredError, AIEventsNotFoundError+from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, HEAVY_COLUMN_TO_PROPERTY, merge_heavy_properties+from posthog.utils import ensure_utc+++def _query_ai_event(+ team_id: int, where_clauses: list[str], params: dict[str, object], workload: Workload = Workload.DEFAULT+) -> dict[str, Any] | None:+ """Read one event with its heavy AI columns, or None. An evaluation grades the heavy+ $ai_input / $ai_output, which live only on the dedicated ai_events table."""+ heavy_cols = ",\n ".join(HEAVY_COLUMN_NAMES)+ # Tag these direct ClickHouse reads so the manual-eval-trigger lookup is attributed+ # to AI observability in query-usage analysis alongside the rest of the product.+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):+ rows = query_with_columns(+ f"""+ SELECT+ uuid,+ event,+ properties,+ timestamp,+ team_id,+ distinct_id,+ person_id,+ {heavy_cols}+ FROM ai_events+ WHERE {" AND ".join(where_clauses)}+ LIMIT 1+ """,+ params,+ team_id=team_id,+ workload=workload,+ )+ if not rows:+ return None++ event_data = rows[0]+ # Merge heavy columns back into properties for the evaluation workflow.+ heavy_columns = {col: event_data.pop(col, "") for col in HEAVY_COLUMN_TO_PROPERTY}+ event_data["properties"] = merge_heavy_properties(event_data["properties"], heavy_columns)+ # ClickHouse hands back native UUID and datetime values, which no JSON payload can hold. Only+ # a caller that starts a workflow gets them stringified by Temporal's converter, so normalizing+ # here gives an activity that reads the event itself the same shape the live path receives.+ event_data["uuid"] = str(event_data["uuid"])+ if event_data.get("person_id") is not None:+ event_data["person_id"] = str(event_data["person_id"])+ if isinstance(event_data["timestamp"], datetime):+ event_data["timestamp"] = ensure_utc(event_data["timestamp"]).isoformat()+ return event_data+++def fetch_ai_event(team_id: int, where_clauses: list[str], params: dict[str, object]) -> dict[str, Any]:+ """Fetch the target event, and tell the two ways it can be absent apart.++ ai_events has a retention TTL, so when the event is missing we probe the long-lived events+ table purely to classify the miss. A stripped events row can't be evaluated either way.+ Raises AIEventsExpiredError when it aged past the TTL, AIEventsNotFoundError when it is in+ neither table.+ """+ event_data = _query_ai_event(team_id, where_clauses, params)+ if event_data is not None:+ return event_data++ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):+ exists_in_events = query_with_columns(+ f"""+ SELECT 1+ FROM events+ WHERE {" AND ".join(where_clauses)}+ LIMIT 1+ """,+ params,+ team_id=team_id,+ )+ if exists_in_events:+ raise AIEventsExpiredError("target event has aged past the ai_events retention window")+ raise AIEventsNotFoundError("target event not found")+++def fetch_generation_event(+ team_id: int, event_uuid: str, timestamp: datetime | None = None, trace_id: str | None = None+) -> dict[str, Any] | None:+ """Look a generation up by identity, returning None on a miss.++ No classification probe, unlike `fetch_ai_event`: a caller with only a uuid can do nothing+ different about an expired event than about a missing one.+ """+ where_clauses = ["team_id = %(team_id)s", "uuid = %(event_id)s"]+ params: dict[str, object] = {"team_id": team_id, "event_id": event_uuid.replace("-", "")}+ if trace_id is not None:+ # ai_events sorts on (team_id, trace_id, timestamp), so this is what turns the read into a+ # point lookup instead of a scan of every row the team has.+ where_clauses.append("trace_id = %(trace_id)s")+ params["trace_id"] = trace_id+ if timestamp is not None:+ # A day of slack each side covers the backdating a client SDK can apply between the+ # timestamp the caller recorded and the one the row carries.+ where_clauses.append("timestamp >= %(ts)s - INTERVAL 1 DAY")+ where_clauses.append("timestamp <= %(ts)s + INTERVAL 1 DAY")+ params["ts"] = timestamp+ # An evaluation activity reads this, and a backfill tick can start hundreds of them at once,+ # so it belongs off the cluster serving interactive requests.+ return _query_ai_event(team_id, where_clauses, params, workload=Workload.OFFLINE)diff --git a/products/ai_observability/backend/api/evaluation_runs.py b/products/ai_observability/backend/api/evaluation_runs.pyindex 95605275241c..3cd148945356 100644--- a/products/ai_observability/backend/api/evaluation_runs.py+++ b/products/ai_observability/backend/api/evaluation_runs.py@@ -16,27 +16,20 @@ from temporalio.common import RetryPolicy, WorkflowIDReusePolicyfrom posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.clickhouse.client import query_with_columns-from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.event_usage import report_user_actionfrom posthog.hogql_queries.ai.ai_table_resolver import AIEventsExpiredError, AIEventsNotFoundError-from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, HEAVY_COLUMN_TO_PROPERTY, merge_heavy_propertiesfrom posthog.permissions import AccessControlPermission+from posthog.temporal.ai_observability.evaluation_types import EVALUATION_WORKFLOW_PREFIXESfrom posthog.temporal.ai_observability.run_evaluation import RunEvaluationInputsfrom posthog.temporal.common.client import sync_connect+from products.ai_observability.backend.ai_event_lookup import fetch_ai_eventfrom products.ai_observability.backend.api.metrics import llma_track_latencyfrom ..models.evaluations import Evaluation, EvaluationTargetlogger = structlog.get_logger(__name__)-EVALUATION_WORKFLOW_PREFIXES = {- "hog": "llma-hog-eval",- "llm_judge": "llma-llm-eval",- "sentiment": "llma-sentiment-eval",-}-def _evaluation_workflow_prefix(evaluation_type: str) -> str:try:@@ -120,7 +113,7 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):params["distinct_id"] = distinct_idtry:- event_data = self._fetch_event_for_evaluation(where_clauses, params)+ event_data = fetch_ai_event(self.team_id, where_clauses, params)except AIEventsExpiredError:raise NotFound(f"Event {target_event_id} is past the ai_events retention window and can no longer be evaluated"@@ -200,57 +193,3 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# The frontend prefixes this with the action name, so "Failed to start evaluation" here# would read back as "Run evaluation failed: Failed to start evaluation".raise APIException("The evaluation service is unavailable. Try again in a moment.") from e-- def _fetch_event_for_evaluation(self, where_clauses: list[str], params: dict[str, object]) -> dict:- """Fetch the target event with its heavy AI columns from ai_events.-- An evaluation grades the heavy $ai_input / $ai_output, which live only on the- dedicated ai_events table. That table has a retention TTL, so when the event is- absent we probe the long-lived events table purely to classify the miss — a- stripped events row can't be evaluated either way.-- Raises AIEventsExpiredError if the event is gone from ai_events but still in- events (aged past the TTL), or AIEventsNotFoundError if it is in neither.- """- heavy_cols = ",\n ".join(HEAVY_COLUMN_NAMES)- # Tag these direct ClickHouse reads so the manual-eval-trigger lookup is attributed- # to AI observability in query-usage analysis alongside the rest of the product.- with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=self.team_id):- rows = query_with_columns(- f"""- SELECT- uuid,- event,- properties,- timestamp,- team_id,- distinct_id,- person_id,- {heavy_cols}- FROM ai_events- WHERE {" AND ".join(where_clauses)}- LIMIT 1- """,- params,- team_id=self.team_id,- )- if not rows:- exists_in_events = query_with_columns(- f"""- SELECT 1- FROM events- WHERE {" AND ".join(where_clauses)}- LIMIT 1- """,- params,- team_id=self.team_id,- )- if exists_in_events:- raise AIEventsExpiredError("target event has aged past the ai_events retention window")- raise AIEventsNotFoundError("target event not found")-- event_data = rows[0]- # Merge heavy columns back into properties for the evaluation workflow.- heavy_columns = {col: event_data.pop(col, "") for col in HEAVY_COLUMN_TO_PROPERTY}- event_data["properties"] = merge_heavy_properties(event_data["properties"], heavy_columns)- return event_datadiff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex 65bc445879d6..dcbf33887400 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -17,7 +17,6 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.hogql import ast-from posthog.hogql.property import property_to_exprfrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.monitoring import monitor@@ -41,6 +40,7 @@ from products.access_control.backend.presentation.access_control import (UserAccessControlSerializerMixin,)+from ..evaluation_conditions import build_condition_filterfrom ..hog import compile_ai_observability_hogfrom ..llm import DEFAULT_MODEL_BY_PROVIDERfrom ..models.evaluation_config import EvaluationConfig@@ -1224,18 +1224,8 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbiteam = Team.objects.get(id=self.team_id)- # Build the trigger-condition filter once (OR between condition sets, AND within each).- # Both targets reuse it — for traces it filters which triggering generation qualifies.- condition_exprs: list[ast.Expr] = []- for condition in conditions:- props = condition.get("properties", [])- if props:- condition_exprs.append(property_to_expr(props, team))- condition_filter: ast.Expr | None = None- if len(condition_exprs) == 1:- condition_filter = condition_exprs[0]- elif condition_exprs:- condition_filter = ast.Or(exprs=condition_exprs)+ # Both targets reuse it; for traces it filters which triggering generation qualifies.+ condition_filter = build_condition_filter(conditions, team)if target == EvaluationTarget.SESSION.value:return _test_hog_over_sessions(diff --git a/products/ai_observability/backend/api/test/test_evaluation_runs.py b/products/ai_observability/backend/api/test/test_evaluation_runs.pyindex 7d0ff3752f62..d89c01698560 100644--- a/products/ai_observability/backend/api/test/test_evaluation_runs.py+++ b/products/ai_observability/backend/api/test/test_evaluation_runs.py@@ -82,7 +82,7 @@ class TestEvaluationRunViewSet(APIBaseTest):assert response.status_code == status.HTTP_403_FORBIDDEN- @patch("products.ai_observability.backend.api.evaluation_runs.query_with_columns")+ @patch("products.ai_observability.backend.ai_event_lookup.query_with_columns")@patch("products.ai_observability.backend.api.evaluation_runs.sync_connect")def test_create_evaluation_run_success(self, mock_connect, mock_query):"""Test successfully creating an evaluation run"""@@ -141,7 +141,7 @@ class TestEvaluationRunViewSet(APIBaseTest):assert workflow_inputs.event_data is not Noneassert workflow_inputs.event_data["uuid"] == target_event_id.replace("-", "")- @patch("products.ai_observability.backend.api.evaluation_runs.query_with_columns")+ @patch("products.ai_observability.backend.ai_event_lookup.query_with_columns")@patch("products.ai_observability.backend.api.evaluation_runs.sync_connect")def test_create_evaluation_run_tags_clickhouse_query(self, mock_connect, mock_query):"""The manual eval-trigger ClickHouse lookup must run inside an LLM analytics tag context.diff --git a/products/ai_observability/backend/backfill_candidates.py b/products/ai_observability/backend/backfill_candidates.pynew file mode 100644index 000000000000..a03d768481c7--- /dev/null+++ b/products/ai_observability/backend/backfill_candidates.py@@ -0,0 +1,547 @@+"""One HogQL query shape serves both the pre-start estimate and the paged dispatch, so the number+a user approves and the units the workflow evaluates come from the same predicate.++Units are discovered on `events` rather than on `ai_events`. Both tables hold every AI event, but+their sort keys decide what a time range costs: `events` is ordered by `(team_id, toDate(timestamp),+event, ...)` and partitioned by month, so a team's `$ai_generation` rows over a range of days prune+to almost exactly the rows asked for, while `ai_events` is ordered by `(team_id, trace_id,+timestamp)`, where a range with no trace id prunes nothing and reads the team's whole history.++`ai_events` is still the only table carrying the heavy properties an evaluation can filter on, so a+condition set that reads one of those is settled by a second query against the trace ids the first+one found, which is a sort-key lookup rather than a scan.+"""++from datetime import datetime, timedelta+from typing import Any++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.clickhouse.workload import Workload+from posthog.dataclasses import frozen+from posthog.hogql_queries.ai.ai_table_resolver import AIEventsExpiredError, AIEventsNotFoundError, query_ai_events+from posthog.hogql_queries.ai.utils import HEAVY_PROPERTY_NAMES+from posthog.models.team import Team++from products.ai_observability.backend.evaluation_conditions import build_condition_filter+from products.ai_observability.backend.models.evaluations import EvaluationTarget++# The count runs inside an API request and the walk inside one activity attempt, so a filter that+# is too expensive for ClickHouse must fail the caller quickly rather than hold it for the 60s default.+MAX_EXECUTION_TIME_SECONDS = 30++# Room for the verdict event's own trip through ingestion, on top of the evaluation's settle+# horizon. A verdict that lands later than this is one the dedupe cannot see.+VERDICT_LAG_MARGIN = timedelta(days=1)++# How far below its cursor a page reads. A unit is ordered by its first event, so the query has to+# see that event to place it, but a unit's events sit in one burst: a generation is a single row and+# a trace or session closes within its settle horizon. Reading only that far below the cursor keeps+# every page the same width instead of growing back to the start of the window. A unit whose events+# outlast the lookback surfaces twice, once truncated and once at its true position, which costs+# nothing: both dispatches share a workflow id, so the second is a no-op counted as skipped.+MIN_SCAN_LOOKBACK = timedelta(days=1)++# A trace or session id is a plain event property, so capture takes one as large as the event it+# rides on, while a Temporal activity payload stops near 2 MiB. Bounding every id a candidate+# carries keeps a full batch far under that, and the bound sits in the query because the cursor is+# itself a unit id: a row skipped after the query would never be passed, stalling the walk on it.+MAX_CANDIDATE_ID_BYTES = 256++CANDIDATE_QUERY_TYPE = "EvaluationBackfillCandidates"+COUNT_QUERY_TYPE = "EvaluationBackfillCount"+HEAVY_MATCH_QUERY_TYPE = "EvaluationBackfillHeavyConditions"++_TARGET_TYPES: dict[str, str] = {+ EvaluationTarget.GENERATION.value: "generation_uuid",+ EvaluationTarget.TRACE.value: "trace_id",+ EvaluationTarget.SESSION.value: "session_id",+}++_UNITS_SQL = """+SELECT+ {unit_key} AS unit_id,+ min(timestamp) AS unit_timestamp,+ argMin(distinct_id, timestamp) AS distinct_id,+ argMin(properties.$session_id, timestamp) AS web_session_id,+ argMin(properties.$ai_trace_id, timestamp) AS unit_trace_id+FROM events+WHERE event = '$ai_generation'+ AND isNotNull({unit_key})+ AND {unit_key} != ''+ AND length({unit_key}) <= {max_id_bytes}+ AND timestamp >= {scan_start}+ AND timestamp < {window_end}+ AND {condition_filter}+ AND {not_already_evaluated}+GROUP BY unit_id+"""++# Settles the condition sets that read a heavy property, over the traces the units query already+# found. `trace_id` leads the ai_events sort key after the team, so this reads those traces rather+# than the window.+_HEAVY_MATCH_SQL = """+SELECT DISTINCT {unit_key} AS unit_id+FROM posthog.ai_events AS ai_events+WHERE event = '$ai_generation'+ AND {unit_scope}+ AND timestamp >= {scan_start}+ AND timestamp < {window_end}+ AND {condition_filter}+"""++# Counting a heavy filter means asking ai_events directly, because the traces to ask about are+# exactly what is being counted. It stays one aggregate: listing the window's units in Python to+# refine them afterwards would let one estimate request hold a whole window in memory.+_AI_UNITS_SQL = """+SELECT {unit_key} AS unit_id+FROM posthog.ai_events AS ai_events+WHERE event = '$ai_generation'+ AND isNotNull({unit_key})+ AND {unit_key} != ''+ AND length({unit_key}) <= {max_id_bytes}+ AND timestamp >= {window_start}+ AND timestamp < {window_end}+ AND {condition_filter}+ AND {not_already_evaluated}+GROUP BY unit_id+"""++# Reads the shared events table rather than ai_events: the verdict rows must stay visible past the+# ai_events retention window, so a re-run of an old backfill still sees what it already covered.+_ALREADY_EVALUATED_SQL = """+SELECT properties.$ai_target_id+FROM events+WHERE event = '$ai_evaluation'+ AND properties.$ai_evaluation_id = {evaluation_id}+ AND {target_type_filter}+ AND timestamp >= {window_start}+ AND timestamp < {verdict_end}+"""+++@frozen+class BackfillCandidate:+ unit_id: str+ unit_timestamp: datetime+ distinct_id: str+ session_id: str | None+ trace_id: str | None+++@frozen+class CandidatePage:+ candidates: list[BackfillCandidate]+ next_cursor_timestamp: datetime | None+ next_cursor_unit_id: str+ exhausted: bool+++def _unit_key(target: str) -> ast.Expr:+ """The unit id as `events` carries it. Only the generation uuid is a column there."""+ if target == EvaluationTarget.TRACE.value:+ return ast.Field(chain=["properties", "$ai_trace_id"])+ if target == EvaluationTarget.SESSION.value:+ return ast.Field(chain=["properties", "$ai_session_id"])+ if target == EvaluationTarget.GENERATION.value:+ # A ClickHouse UUID needs a String cast to compare against the cursor and against the+ # dedupe subquery's target ids.+ return ast.Call(name="toString", args=[ast.Field(chain=["uuid"])])+ raise ValueError(f"Unsupported evaluation target: {target}")+++def _ai_events_unit_key(target: str) -> ast.Expr:+ """The same unit id as `ai_events` carries it, where trace and session are native columns."""+ if target == EvaluationTarget.TRACE.value:+ return ast.Field(chain=["trace_id"])+ if target == EvaluationTarget.SESSION.value:+ return ast.Field(chain=["session_id"])+ if target == EvaluationTarget.GENERATION.value:+ return ast.Call(name="toString", args=[ast.Field(chain=["uuid"])])+ raise ValueError(f"Unsupported evaluation target: {target}")+++def _target_type_filter(target: str) -> ast.Expr:+ target_type = ast.Field(chain=["properties", "$ai_target_type"])+ try:+ expected = _TARGET_TYPES[target]+ except KeyError:+ raise ValueError(f"Unsupported evaluation target: {target}") from None+ matches = ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=target_type, right=ast.Constant(value=expected))+ if target != EvaluationTarget.GENERATION.value:+ return matches+ # Verdicts emitted before $ai_target_type existed are generation verdicts, so a null value+ # belongs to the generation id space. Same rule as eval_reports/targets.py:target_event_predicate.+ return ast.Or(exprs=[matches, ast.Call(name="isNull", args=[target_type])])+++def reads_heavy_properties(conditions: list[dict[str, Any]]) -> bool:+ """Whether any condition set filters on a property `events` does not carry."""+ return any(+ str(prop.get("key")) in HEAVY_PROPERTY_NAMES+ for condition in conditions+ for prop in (condition.get("properties") or [])+ )+++def _without_heavy_properties(conditions: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """The same condition sets with the heavy filters dropped, so they match a superset.++ What survives runs on `events` to find the units worth asking about; the full sets then settle+ which of those actually match.+ """+ return [+ {+ **condition,+ "properties": [+ prop for prop in (condition.get("properties") or []) if str(prop.get("key")) not in HEAVY_PROPERTY_NAMES+ ],+ }+ for condition in conditions+ ]+++def _not_already_evaluated(+ *,+ unit_key: ast.Expr,+ evaluation_id: str,+ target: str,+ window_start: datetime,+ window_end: datetime,+ settle_horizon: timedelta,+) -> ast.Expr:+ # The upper bound keeps the subquery off the whole events history after the window. A live+ # verdict is stamped when its unit finishes settling, so it can trail the unit by the whole+ # settle horizon the evaluation is configured with, up to 7 days for a session. Reading that+ # number from the evaluation rather than assuming one keeps the scan tight where the wait is+ # short, which is every generation and every trace.+ already_evaluated = parse_select(+ _ALREADY_EVALUATED_SQL,+ placeholders={+ "evaluation_id": ast.Constant(value=evaluation_id),+ "target_type_filter": _target_type_filter(target),+ "window_start": ast.Constant(value=window_start),+ "verdict_end": ast.Constant(value=window_end + settle_horizon + VERDICT_LAG_MARGIN),+ },+ )+ return ast.CompareOperation(op=ast.CompareOperationOp.NotIn, left=unit_key, right=already_evaluated)+++def _units_query(+ *,+ team: Team,+ evaluation_id: str,+ target: str,+ settle_horizon: timedelta,+ conditions: list[dict[str, Any]],+ scan_start: datetime,+ window_start: datetime,+ window_end: datetime,+ rerun_existing: bool,+) -> ast.SelectQuery:+ """Units in `[scan_start, window_end)` that the evaluation has not judged yet."""+ unit_key = _unit_key(target)+ condition_filter = build_condition_filter(_without_heavy_properties(conditions), team, unit_key)+ query = parse_select(+ _UNITS_SQL,+ placeholders={+ "unit_key": unit_key,+ "max_id_bytes": ast.Constant(value=MAX_CANDIDATE_ID_BYTES),+ "scan_start": ast.Constant(value=scan_start),+ "window_end": ast.Constant(value=window_end),+ "condition_filter": condition_filter if condition_filter is not None else ast.Constant(value=True),+ "not_already_evaluated": ast.Constant(value=True)+ if rerun_existing+ else _not_already_evaluated(+ unit_key=unit_key,+ evaluation_id=evaluation_id,+ target=target,+ window_start=window_start,+ window_end=window_end,+ settle_horizon=settle_horizon,+ ),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return query+++def _cursor_predicate(cursor_timestamp: datetime, cursor_unit_id: str) -> ast.Expr:+ timestamp_field = ast.Field(chain=["unit_timestamp"])+ cursor = ast.Constant(value=cursor_timestamp)+ return ast.Or(+ exprs=[+ ast.CompareOperation(op=ast.CompareOperationOp.Lt, left=timestamp_field, right=cursor),+ ast.And(+ exprs=[+ ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=timestamp_field, right=cursor),+ ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=ast.Field(chain=["unit_id"]),+ right=ast.Constant(value=cursor_unit_id),+ ),+ ]+ ),+ ]+ )+++def _bounded_id(value: Any) -> str | None:+ """An id a candidate carries alongside its unit, dropped when it is too large to ship.++ Both are optional to the run that receives them: one narrows the child's ClickHouse scan and+ the other becomes a property on the verdict, so losing an absurd one beats failing the tick.+ """+ if not value:+ return None+ text = str(value)+ return text if len(text.encode()) <= MAX_CANDIDATE_ID_BYTES else None+++def _scan_start(*, window_start: datetime, cursor_timestamp: datetime | None, settle_horizon: timedelta) -> datetime:+ if cursor_timestamp is None:+ return window_start+ return max(window_start, cursor_timestamp - max(settle_horizon, MIN_SCAN_LOOKBACK))+++def _run(query: ast.SelectQuery, *, team: Team, query_type: str) -> list[tuple[Any, ...]]:+ # Tagged here so both callers (the API estimate and the Temporal walk) attribute the same way.+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.BACKFILL, team_id=team.pk):+ response = execute_hogql_query(+ query=query,+ team=team,+ query_type=query_type,+ workload=Workload.OFFLINE,+ settings=HogQLGlobalSettings(max_execution_time=MAX_EXECUTION_TIME_SECONDS),+ )+ return list(response.results or [])+++def _run_on_ai_events(+ query: ast.SelectQuery, placeholders: dict[str, ast.Expr], *, team: Team, query_type: str+) -> list[tuple[Any, ...]]:+ """Runs through the ai_events resolver, which rewrites a heavy property read onto its column.++ Only what arrives in `placeholders` is rewritten, so a condition filter baked into the parsed+ query would read a `properties.$ai_input` that ai_events does not carry, and match nothing.+ """+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.BACKFILL, team_id=team.pk):+ try:+ response = query_ai_events(+ query=query,+ placeholders=placeholders,+ team=team,+ query_type=query_type,+ fall_back_to_events=False,+ workload=Workload.OFFLINE,+ settings=HogQLGlobalSettings(max_execution_time=MAX_EXECUTION_TIME_SECONDS),+ )+ except (AIEventsNotFoundError, AIEventsExpiredError):+ return []+ return list(response.results or [])+++def _heavy_matches(+ *,+ team: Team,+ target: str,+ conditions: list[dict[str, Any]],+ candidates: list[BackfillCandidate],+ scan_start: datetime,+ window_end: datetime,+) -> set[str]:+ """Which of these candidates match the condition sets in full, heavy filters included."""+ if not candidates:+ return set()+ unit_key = _ai_events_unit_key(target)+ trace_ids = sorted({candidate.trace_id for candidate in candidates if candidate.trace_id})+ scope: ast.Expr = ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["trace_id"]),+ right=ast.Constant(value=trace_ids),+ )+ # A generation can carry a heavy property and no trace id at all, and for a generation or+ # session unit that is still a candidate. Reaching it by its own id keeps it judged rather+ # than dropped, and the clause is only added when such a candidate is on the page, so the+ # ordinary lookup keeps reading by the sort key alone.+ untraced = sorted({candidate.unit_id for candidate in candidates if not candidate.trace_id})+ if untraced:+ scope = ast.Or(+ exprs=[+ scope,+ ast.CompareOperation(op=ast.CompareOperationOp.In, left=unit_key, right=ast.Constant(value=untraced)),+ ]+ )+ condition_filter = build_condition_filter(conditions, team, unit_key)+ query = parse_select(_HEAVY_MATCH_SQL)+ assert isinstance(query, ast.SelectQuery)+ rows = _run_on_ai_events(+ query,+ {+ "unit_key": unit_key,+ "unit_scope": scope,+ "scan_start": ast.Constant(value=scan_start),+ "window_end": ast.Constant(value=window_end),+ "condition_filter": condition_filter if condition_filter is not None else ast.Constant(value=True),+ },+ team=team,+ query_type=HEAVY_MATCH_QUERY_TYPE,+ )+ return {str(row[0]) for row in rows}+++def count_backfill_candidates(+ *,+ team: Team,+ evaluation_id: str,+ target: str,+ settle_horizon: timedelta,+ conditions: list[dict[str, Any]],+ window_start: datetime,+ window_end: datetime,+ rerun_existing: bool,+) -> int:+ units = _units_query(+ team=team,+ evaluation_id=evaluation_id,+ target=target,+ settle_horizon=settle_horizon,+ conditions=conditions,+ scan_start=window_start,+ window_start=window_start,+ window_end=window_end,+ rerun_existing=rerun_existing,+ )+ if not reads_heavy_properties(conditions):+ query = ast.SelectQuery(select=[ast.Call(name="count", args=[])], select_from=ast.JoinExpr(table=units))+ rows = _run(query, team=team, query_type=COUNT_QUERY_TYPE)+ return int(rows[0][0]) if rows else 0++ # `events` cannot judge a heavy filter, and the traces to ask ai_events about are exactly what+ # is being counted, so the count asks ai_events for all of it and comes back with one number.+ # The scan is the wide one this module otherwise avoids, which is the price of counting a+ # filter on a property only that table holds, and the execution cap bounds it.+ ai_unit_key = _ai_events_unit_key(target)+ ai_units = parse_select(_AI_UNITS_SQL)+ assert isinstance(ai_units, ast.SelectQuery)+ rows = _run_on_ai_events(+ ast.SelectQuery(select=[ast.Call(name="count", args=[])], select_from=ast.JoinExpr(table=ai_units)),+ {+ "unit_key": ai_unit_key,+ "max_id_bytes": ast.Constant(value=MAX_CANDIDATE_ID_BYTES),+ "window_start": ast.Constant(value=window_start),+ "window_end": ast.Constant(value=window_end),+ "condition_filter": build_condition_filter(conditions, team, ai_unit_key) or ast.Constant(value=True),+ "not_already_evaluated": ast.Constant(value=True)+ if rerun_existing+ else _not_already_evaluated(+ unit_key=ai_unit_key,+ evaluation_id=evaluation_id,+ target=target,+ window_start=window_start,+ window_end=window_end,+ settle_horizon=settle_horizon,+ ),+ },+ team=team,+ query_type=COUNT_QUERY_TYPE,+ )+ return int(rows[0][0]) if rows else 0+++def fetch_backfill_candidates(+ *,+ team: Team,+ evaluation_id: str,+ target: str,+ settle_horizon: timedelta,+ conditions: list[dict[str, Any]],+ window_start: datetime,+ window_end: datetime,+ rerun_existing: bool,+ cursor_timestamp: datetime | None,+ cursor_unit_id: str,+ limit: int,+) -> CandidatePage:+ scan_start = _scan_start(+ window_start=window_start, cursor_timestamp=cursor_timestamp, settle_horizon=settle_horizon+ )+ query = _units_query(+ team=team,+ evaluation_id=evaluation_id,+ target=target,+ settle_horizon=settle_horizon,+ conditions=conditions,+ scan_start=scan_start,+ window_start=window_start,+ window_end=window_end,+ rerun_existing=rerun_existing,+ )+ if cursor_timestamp is not None:+ query.having = _cursor_predicate(cursor_timestamp, cursor_unit_id)+ # A unit whose first generation is after the cursor is already excluded by HAVING, and+ # every remaining unit keeps the same min(timestamp) once later rows are dropped. So this+ # bound changes no result, it only stops ClickHouse from reading rows the walk has passed.+ cursor_bound = ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=cursor_timestamp),+ )+ query.where = ast.And(exprs=[query.where, cursor_bound]) if query.where is not None else cursor_bound+ query.order_by = [+ ast.OrderExpr(expr=ast.Field(chain=["unit_timestamp"]), order="DESC"),+ ast.OrderExpr(expr=ast.Field(chain=["unit_id"]), order="DESC"),+ ]+ query.limit = ast.Constant(value=limit)++ rows = _run(query, team=team, query_type=CANDIDATE_QUERY_TYPE)+ candidates = [+ BackfillCandidate(+ unit_id=str(row[0]),+ unit_timestamp=row[1],+ distinct_id=str(row[2]),+ session_id=_bounded_id(row[3]),+ trace_id=_bounded_id(row[4]),+ )+ for row in rows+ ]+ # The cursor tracks what the page examined, not what survived, so a unit the heavy filter+ # rejects is passed over once rather than met again on the next tick.+ examined = candidates[-1] if candidates else None+ if reads_heavy_properties(conditions):+ matched = _heavy_matches(+ team=team,+ target=target,+ conditions=conditions,+ candidates=candidates,+ scan_start=scan_start,+ window_end=window_end,+ )+ candidates = [candidate for candidate in candidates if candidate.unit_id in matched]++ if len(rows) == limit and examined is not None:+ return CandidatePage(+ candidates=candidates,+ next_cursor_timestamp=examined.unit_timestamp,+ next_cursor_unit_id=examined.unit_id,+ exhausted=False,+ )+ # A short page means this slice is spent, not the window: the walk drops to the slice's own+ # floor and carries on until that floor is the start of the window.+ if scan_start > window_start:+ return CandidatePage(+ candidates=candidates,+ next_cursor_timestamp=scan_start,+ next_cursor_unit_id="",+ exhausted=False,+ )+ return CandidatePage(+ candidates=candidates,+ next_cursor_timestamp=examined.unit_timestamp if examined else None,+ next_cursor_unit_id=examined.unit_id if examined else "",+ exhausted=True,+ )diff --git a/products/ai_observability/backend/evaluation_conditions.py b/products/ai_observability/backend/evaluation_conditions.pynew file mode 100644index 000000000000..a3f9c1b957ba--- /dev/null+++ b/products/ai_observability/backend/evaluation_conditions.py@@ -0,0 +1,74 @@+"""HogQL filter for an evaluation's condition sets, shared by the test-Hog preview and backfills."""++from typing import Any++from posthog.hogql import ast+from posthog.hogql.property import property_to_expr++from posthog.models.team import Team++# Buckets of 0.01%, matching the rollout slider.+_SAMPLING_BUCKETS = 10000+++def _rollout_bucket(unit_key: ast.Expr) -> ast.Expr:+ """The bucket the live scheduler puts this unit in, rebuilt in SQL.++ `checkRolloutPercentage` in the evaluation scheduler reads the first four bytes of the key's+ md5 as a big-endian integer, then takes it modulo the bucket count. Any other hash would put+ the same unit in a different bucket, so a backfill would sample a disjoint share of the+ population and grade far more units than the rollout asks for.+ """+ first_four_bytes = ast.Call(+ name="unhex",+ args=[+ ast.Call(+ name="substring",+ args=[+ ast.Call(name="hex", args=[ast.Call(name="MD5", args=[unit_key])]),+ ast.Constant(value=1),+ ast.Constant(value=8),+ ],+ )+ ],+ )+ return ast.ArithmeticOperation(+ op=ast.ArithmeticOperationOp.Mod,+ # reinterpretAsUInt32 reads little-endian, so the bytes are reversed to read them the way+ # the scheduler's parseInt does.+ left=ast.Call(name="reinterpretAsUInt32", args=[ast.Call(name="reverse", args=[first_four_bytes])]),+ right=ast.Constant(value=_SAMPLING_BUCKETS),+ )+++def _sampling_predicate(unit_key: ast.Expr, rollout_percentage: float) -> ast.Expr | None:+ if rollout_percentage >= 100:+ return None+ return ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=_rollout_bucket(unit_key),+ right=ast.Constant(value=int(round(rollout_percentage * 100))),+ )+++def build_condition_filter(+ conditions: list[dict[str, Any]], team: Team, unit_key: ast.Expr | None = None+) -> ast.Expr | None:+ """OR across condition sets, AND within a set (properties, and sampling when a unit key is given)."""+ sets: list[ast.Expr] = []+ for condition in conditions:+ parts: list[ast.Expr] = []+ props = condition.get("properties") or []+ if props:+ parts.append(property_to_expr(props, team))+ if unit_key is not None:+ sampling = _sampling_predicate(unit_key, float(condition.get("rollout_percentage", 100)))+ if sampling is not None:+ parts.append(sampling)+ if len(parts) > 1:+ sets.append(ast.And(exprs=parts))+ else:+ sets.append(parts[0] if parts else ast.Constant(value=True))+ if not sets:+ return None+ return sets[0] if len(sets) == 1 else ast.Or(exprs=sets)diff --git a/products/ai_observability/backend/migrations/0048_evaluationbackfill.py b/products/ai_observability/backend/migrations/0048_evaluationbackfill.pynew file mode 100644index 000000000000..a89aa4c87968--- /dev/null+++ b/products/ai_observability/backend/migrations/0048_evaluationbackfill.py@@ -0,0 +1,136 @@+# Generated by Django 5.2.17 on 2026-09-03 09:39++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("ai_observability", "0047_alter_evaluationconfig_team"),+ ("posthog", "1339_validate_taggeditem_project_fk"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="EvaluationBackfill",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "window_start",+ models.DateTimeField(help_text="Inclusive lower bound of the window, by unit timestamp."),+ ),+ (+ "window_end",+ models.DateTimeField(help_text="Exclusive upper bound of the window; clamped to now at creation."),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("running", "Running"),+ ("completed", "Completed"),+ ("cancelled", "Cancelled"),+ ],+ default="running",+ max_length=16,+ ),+ ),+ (+ "target",+ models.CharField(help_text="Evaluation target frozen at creation.", max_length=20),+ ),+ (+ "conditions",+ models.JSONField(+ default=list,+ help_text="Condition sets used for this backfill: [{properties: [...], rollout_percentage: float}].",+ ),+ ),+ (+ "rerun_existing",+ models.BooleanField(+ default=False,+ help_text="When true, units that already have a result from this evaluation are evaluated again.",+ ),+ ),+ ("cursor_timestamp", models.DateTimeField(blank=True, null=True)),+ ("cursor_unit_id", models.TextField(blank=True, default="")),+ (+ "total_count",+ models.PositiveIntegerField(+ help_text="Units matched at creation; the ceiling on dispatched_count."+ ),+ ),+ ("dispatched_count", models.PositiveIntegerField(default=0)),+ (+ "skipped_count",+ models.PositiveIntegerField(+ default=0,+ help_text="Units whose child workflow already existed, so the live path had them.",+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("finished_at", models.DateTimeField(blank=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "evaluation",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="backfills",+ to="ai_observability.evaluation",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "indexes": [+ models.Index(+ fields=["team", "created_at"],+ name="aio_eval_backfill_team_created",+ )+ ],+ "constraints": [+ models.UniqueConstraint(+ condition=models.Q(("status", "running")),+ fields=("evaluation",),+ name="aio_eval_backfill_one_active_per_evaluation",+ ),+ models.CheckConstraint(+ condition=models.Q(("window_start__lt", models.F("window_end"))),+ name="aio_eval_backfill_window_start_before_end",+ ),+ ],+ },+ ),+ ]diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txtindex 1fb81148bb6a..81173f149890 100644--- a/products/ai_observability/backend/migrations/max_migration.txt+++ b/products/ai_observability/backend/migrations/max_migration.txt@@ -1 +1 @@-0047_alter_evaluationconfig_team+0048_evaluationbackfilldiff --git a/products/ai_observability/backend/models/__init__.py b/products/ai_observability/backend/models/__init__.pyindex fab45082d5ce..743c35f83e1d 100644--- a/products/ai_observability/backend/models/__init__.py+++ b/products/ai_observability/backend/models/__init__.py@@ -1,6 +1,7 @@from .clustering_config import ClusteringConfigfrom .clustering_job import ClusteringJobfrom .datasets import Dataset, DatasetItem, DatasetItemVersion, DatasetRevision+from .evaluation_backfill import EvaluationBackfillfrom .evaluation_config import EvaluationConfigfrom .evaluation_directories import EvaluationDirectoryfrom .evaluation_reports import EvaluationReport, EvaluationReportRun@@ -21,6 +22,7 @@ __all__ = ["ClusteringConfig","ClusteringJob","Evaluation",+ "EvaluationBackfill","EvaluationConfig","EvaluationDirectory","EvaluationReport",diff --git a/products/ai_observability/backend/models/evaluation_backfill.py b/products/ai_observability/backend/models/evaluation_backfill.pynew file mode 100644index 000000000000..844450267397--- /dev/null+++ b/products/ai_observability/backend/models/evaluation_backfill.py@@ -0,0 +1,80 @@+from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel+++class EvaluationBackfillStatus(models.TextChoices):+ RUNNING = "running", "Running"+ COMPLETED = "completed", "Completed"+ CANCELLED = "cancelled", "Cancelled"+++ACTIVE_BACKFILL_STATUSES = (EvaluationBackfillStatus.RUNNING,)+++class EvaluationBackfill(TeamScopedRootMixin, UUIDModel):+ """One historical run of an evaluation over a date window.++ The row is the source of truth for progress: the Temporal workflow reads the cursor at every+ tick and writes it back, so a worker restart resumes where it stopped.+ """++ evaluation = models.ForeignKey("ai_observability.Evaluation", on_delete=models.CASCADE, related_name="backfills")+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)++ window_start = models.DateTimeField(help_text="Inclusive lower bound of the window, by unit timestamp.")+ window_end = models.DateTimeField(help_text="Exclusive upper bound of the window; clamped to now at creation.")++ status = models.CharField(+ max_length=16, choices=EvaluationBackfillStatus.choices, default=EvaluationBackfillStatus.RUNNING+ )++ # Frozen at creation so an edit to the evaluation mid-run does not change what the walk matches.+ target = models.CharField(max_length=20, help_text="Evaluation target frozen at creation.")+ conditions = models.JSONField(+ default=list,+ help_text="Condition sets used for this backfill: [{properties: [...], rollout_percentage: float}].",+ )+ rerun_existing = models.BooleanField(+ default=False, help_text="When true, units that already have a result from this evaluation are evaluated again."+ )++ # Keyset cursor over (unit timestamp DESC, unit id DESC). Null until the first batch is dispatched.+ cursor_timestamp = models.DateTimeField(null=True, blank=True)+ cursor_unit_id = models.TextField(blank=True, default="")++ total_count = models.PositiveIntegerField(help_text="Units matched at creation; the ceiling on dispatched_count.")+ dispatched_count = models.PositiveIntegerField(default=0)+ skipped_count = models.PositiveIntegerField(+ default=0, help_text="Units whose child workflow already existed, so the live path had them."+ )++ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)+ finished_at = models.DateTimeField(null=True, blank=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["evaluation"],+ condition=models.Q(status="running"),+ name="aio_eval_backfill_one_active_per_evaluation",+ ),+ models.CheckConstraint(+ condition=models.Q(window_start__lt=models.F("window_end")),+ name="aio_eval_backfill_window_start_before_end",+ ),+ ]+ indexes = [models.Index(fields=["team", "created_at"], name="aio_eval_backfill_team_created")]++ def save(self, *args, **kwargs) -> None:+ if self._state.adding:+ evaluation_team_id = self.evaluation.team_id+ if self.team_id and self.team_id != evaluation_team_id:+ raise ValueError("EvaluationBackfill.team_id must match evaluation.team_id")+ self.team_id = evaluation_team_id+ super().save(*args, **kwargs)diff --git a/products/ai_observability/backend/test/test_backfill_candidates.py b/products/ai_observability/backend/test/test_backfill_candidates.pynew file mode 100644index 000000000000..ae838e92d709--- /dev/null+++ b/products/ai_observability/backend/test/test_backfill_candidates.py@@ -0,0 +1,452 @@+import uuid+import hashlib+from datetime import UTC, datetime, timedelta+from typing import Any++from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from unittest.mock import patch++from parameterized import parameterized++from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events+from posthog.models.ai_events.test_util import bulk_create_ai_events++from products.ai_observability.backend.backfill_candidates import (+ MAX_CANDIDATE_ID_BYTES,+ count_backfill_candidates,+ fetch_backfill_candidates,+)+from products.ai_observability.backend.models.evaluations import Evaluation++CANDIDATES_MODULE = "products.ai_observability.backend.backfill_candidates"++BASE = datetime(2026, 8, 1, 12, tzinfo=UTC)+WINDOW_START = BASE - timedelta(hours=1)+WINDOW_END = BASE + timedelta(days=1)+++def _generation_uuid(index: int) -> str:+ return str(uuid.UUID(int=index))+++def _write_generations(payloads: list[dict[str, Any]]) -> None:+ """Write generations the way ingestion does, to `events` and to `ai_events` alike.++ Units are discovered on `events` and heavy properties are read from `ai_events`, so a fixture+ that lands in only one table exercises neither path as production runs it.+ """+ bulk_create_ai_events(payloads)+ for payload in payloads:+ _create_event(+ team=payload["team"],+ event=payload["event"],+ distinct_id=payload["distinct_id"],+ timestamp=payload["timestamp"],+ event_uuid=payload["event_uuid"],+ properties=payload["properties"],+ )+ flush_persons_and_events()+++class TestBackfillCandidates(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.evaluation = Evaluation.objects.create(+ team=self.team,+ name="e",+ evaluation_type="hog",+ evaluation_config={"source": "return true"},+ output_type="boolean",+ output_config={},+ conditions=[],+ )+ # (label, trace, offset, model). One trace carries two generations, so trace and session+ # grouping collapses where the generation target does not.+ self.fixture = [+ ("g1", "t1", timedelta(0), "gpt-4o"),+ ("g2", "t1", timedelta(minutes=1), "gpt-4o"),+ ("g3", "t2", timedelta(hours=1), "gpt-4o-mini"),+ ("g4", "t3", timedelta(hours=2), "gpt-4o"),+ ]+ self.uuids = {label: _generation_uuid(index + 1) for index, (label, _, _, _) in enumerate(self.fixture)}+ _write_generations(+ [+ {+ "event": "$ai_generation",+ "distinct_id": f"d-{trace_id}",+ "team": self.team,+ "timestamp": BASE + offset,+ "event_uuid": self.uuids[label],+ "properties": {+ "$ai_trace_id": trace_id,+ "$ai_session_id": f"s-{trace_id}",+ "$ai_model": model,+ "$ai_input": "hello there",+ "$session_id": f"web-{trace_id}",+ },+ }+ for label, trace_id, offset, model in self.fixture+ ]+ )++ def _create_generations(self, *specs: tuple[int, str, timedelta]) -> None:+ _write_generations(+ [+ {+ "event": "$ai_generation",+ "distinct_id": f"d-{trace_id}",+ "team": self.team,+ "timestamp": BASE + offset,+ "event_uuid": _generation_uuid(index),+ "properties": {"$ai_trace_id": trace_id, "$ai_session_id": f"s-{trace_id}"},+ }+ for index, trace_id, offset in specs+ ]+ )++ def _walk(self, *, limit: int, **overrides: Any) -> list[Any]:+ walked: list[Any] = []+ cursor_timestamp: datetime | None = None+ cursor_unit_id = ""+ while True:+ page = self._fetch(+ cursor_timestamp=cursor_timestamp, cursor_unit_id=cursor_unit_id, limit=limit, **overrides+ )+ walked.extend(page.candidates)+ if page.exhausted:+ break+ cursor_timestamp, cursor_unit_id = page.next_cursor_timestamp, page.next_cursor_unit_id+ return walked++ def _count(self, **overrides: Any) -> int:+ kwargs: dict[str, Any] = {+ "team": self.team,+ "evaluation_id": str(self.evaluation.id),+ "target": "trace",+ "settle_horizon": timedelta(0),+ "conditions": [],+ "window_start": WINDOW_START,+ "window_end": WINDOW_END,+ "rerun_existing": True,+ }+ kwargs.update(overrides)+ return count_backfill_candidates(**kwargs)++ def _fetch(self, **overrides: Any) -> Any:+ kwargs: dict[str, Any] = {+ "team": self.team,+ "evaluation_id": str(self.evaluation.id),+ "target": "generation",+ "settle_horizon": timedelta(0),+ "conditions": [],+ "window_start": WINDOW_START,+ "window_end": WINDOW_END,+ "rerun_existing": True,+ "cursor_timestamp": None,+ "cursor_unit_id": "",+ "limit": 3,+ }+ kwargs.update(overrides)+ return fetch_backfill_candidates(**kwargs)++ @parameterized.expand([("generation", 4), ("trace", 3), ("session", 3)])+ def test_counts_every_unit_in_window_without_conditions(self, target: str, expected: int) -> None:+ assert self._count(target=target) == expected++ def test_window_bounds_exclude_units_outside_the_range(self) -> None:+ assert self._count(target="generation", window_end=BASE + timedelta(minutes=1)) == 1+ assert self._count(target="generation", window_start=BASE + timedelta(hours=1)) == 2++ def test_property_condition_filters_units_and_full_rollout_keeps_them_all(self) -> None:+ conditions = [+ {+ "properties": [{"key": "$ai_model", "value": "gpt-4o", "operator": "exact", "type": "event"}],+ "rollout_percentage": 100,+ }+ ]+ assert self._count(target="trace", conditions=conditions) == 2++ @parameterized.expand([("a tenth", 10), ("two fifths", 40), ("just under the first bucket", 8)])+ def test_sampling_picks_the_units_the_live_scheduler_would_pick(self, _case: str, rollout: int) -> None:+ # `checkRolloutPercentage` in the evaluation scheduler reads the first four bytes of the+ # key's md5 as a big-endian integer, modulo 10000. Sampling on any other hash would take a+ # share of the population disjoint from the live one, so a backfill over a window the live+ # path already covered would grade about twice the rollout the user set.+ def live_bucket(unit_id: str) -> int:+ return int(hashlib.md5(unit_id.encode()).hexdigest()[:8], 16) % 10000++ expected = sorted(trace for trace in ("t1", "t2", "t3") if live_bucket(trace) < rollout * 100)++ page = self._fetch(+ target="trace",+ conditions=[{"properties": [], "rollout_percentage": rollout}],+ limit=10,+ )++ assert sorted(candidate.unit_id for candidate in page.candidates) == expected++ def test_zero_rollout_matches_nothing_and_condition_sets_are_ored(self) -> None:+ conditions = [+ {+ "properties": [{"key": "$ai_model", "value": "gpt-4o", "operator": "exact", "type": "event"}],+ "rollout_percentage": 0,+ },+ {+ "properties": [{"key": "$ai_model", "value": "gpt-4o-mini", "operator": "exact", "type": "event"}],+ "rollout_percentage": 100,+ },+ ]+ assert self._count(target="trace", conditions=conditions) == 1++ @parameterized.expand(+ [+ ("trace", "trace", "trace_id", "t1", 2),+ ("generation", "generation", "generation_uuid", _generation_uuid(1), 3),+ ("session", "session", "session_id", "s-t1", 2),+ # Verdicts emitted before $ai_target_type existed are generation verdicts.+ ("generation_without_target_type", "generation", None, _generation_uuid(1), 3),+ ]+ )+ def test_already_evaluated_units_are_excluded_unless_rerun(+ self, _case: str, target: str, target_type: str | None, target_id: str, expected: int+ ) -> None:+ properties: dict[str, Any] = {"$ai_evaluation_id": str(self.evaluation.id), "$ai_target_id": target_id}+ if target_type is not None:+ properties["$ai_target_type"] = target_type+ _create_event(+ team=self.team,+ event="$ai_evaluation",+ distinct_id="d",+ timestamp=BASE + timedelta(minutes=5),+ properties=properties,+ )+ flush_persons_and_events()+ assert self._count(target=target, rerun_existing=False) == expected+ assert self._count(target=target, rerun_existing=True) == expected + 1++ @parameterized.expand(+ [+ # A generation is graded when it lands, so a verdict three days later belongs to+ # something else and the unit is still a candidate.+ ("a settle horizon this evaluation does not have", timedelta(0), 3),+ # A session evaluation can wait a week before it grades, so the same verdict is the+ # one this backfill would otherwise duplicate.+ ("the horizon a long session evaluation waits", timedelta(days=7), 2),+ ]+ )+ def test_a_verdict_is_deduped_when_the_evaluation_could_still_have_been_settling(+ self, _case: str, horizon: timedelta, expected: int+ ) -> None:+ _create_event(+ team=self.team,+ event="$ai_evaluation",+ distinct_id="d",+ timestamp=WINDOW_END + timedelta(days=3),+ properties={+ "$ai_evaluation_id": str(self.evaluation.id),+ "$ai_target_id": "t1",+ "$ai_target_type": "trace_id",+ },+ )+ flush_persons_and_events()++ assert self._count(target="trace", settle_horizon=horizon, rerun_existing=False) == expected++ def test_pages_descend_by_timestamp_then_id_and_report_exhaustion(self) -> None:+ page1 = self._fetch(limit=3)+ assert [c.unit_id for c in page1.candidates] == [self.uuids["g4"], self.uuids["g3"], self.uuids["g2"]]+ assert page1.exhausted is False++ page2 = self._fetch(+ cursor_timestamp=page1.next_cursor_timestamp,+ cursor_unit_id=page1.next_cursor_unit_id,+ limit=3,+ )+ assert [c.unit_id for c in page2.candidates] == [self.uuids["g1"]]+ assert page2.exhausted is True++ def test_a_page_break_on_tied_timestamps_neither_drops_nor_repeats_a_unit(self) -> None:+ self._create_generations((6, "t5", timedelta(hours=1)))++ # limit=2 puts the break inside the pair sharing BASE + 1h, so paging depends on the+ # unit_id tiebreak rather than on the timestamp alone.+ walked = [candidate.unit_id for candidate in self._walk(limit=2)]++ tied = _generation_uuid(6)+ assert walked == [+ self.uuids["g4"],+ tied,+ self.uuids["g3"],+ self.uuids["g2"],+ self.uuids["g1"],+ ]+ assert len(set(walked)) == len(walked)++ def test_candidate_carries_the_fields_the_dispatcher_needs(self) -> None:+ page = self._fetch(target="trace", limit=1)+ candidate = page.candidates[0]+ assert candidate.unit_id == "t3"+ assert candidate.unit_timestamp == BASE + timedelta(hours=2)+ assert candidate.distinct_id == "d-t3"+ assert candidate.session_id == "web-t3"+ assert candidate.trace_id == "t3"++ generation = self._fetch(target="generation", limit=1).candidates[0]+ assert generation.unit_id == self.uuids["g4"]+ assert generation.trace_id == "t3"++ def test_candidate_without_a_web_session_reports_none(self) -> None:+ self._create_generations((5, "t4", timedelta(hours=3)))+ page = self._fetch(target="trace", limit=1)+ assert page.candidates[0].unit_id == "t4"+ assert page.candidates[0].session_id is None++ def test_an_oversized_unit_id_is_left_out_of_the_walk(self) -> None:+ # Capture takes a trace id as large as the event carrying it, and a Temporal payload stops+ # near 2 MiB, so a unit this wide can never be dispatched.+ oversized = "t" * (MAX_CANDIDATE_ID_BYTES + 1)+ _write_generations(+ [+ {+ "event": "$ai_generation",+ "distinct_id": "d-wide",+ "team": self.team,+ "timestamp": BASE + timedelta(hours=3),+ "event_uuid": _generation_uuid(90),+ "properties": {"$ai_trace_id": oversized, "$ai_session_id": "s-wide"},+ }+ ]+ )++ page = self._fetch(target="trace", limit=10)++ assert oversized not in [candidate.unit_id for candidate in page.candidates]+ assert self._count(target="trace") == len(page.candidates)++ def test_an_oversized_id_beside_the_unit_is_dropped_rather_than_shipped(self) -> None:+ # The trace id only narrows the child's scan and the session id only tags the verdict, so+ # a candidate keeps its place without them.+ oversized = "s" * (MAX_CANDIDATE_ID_BYTES + 1)+ _write_generations(+ [+ {+ "event": "$ai_generation",+ "distinct_id": "d-t5",+ "team": self.team,+ "timestamp": BASE + timedelta(hours=4),+ "event_uuid": _generation_uuid(91),+ "properties": {+ "$ai_trace_id": "t5",+ "$ai_session_id": "s-t5",+ "$session_id": oversized,+ },+ }+ ]+ )++ candidate = self._fetch(target="trace", limit=1).candidates[0]++ assert candidate.unit_id == "t5"+ assert candidate.session_id is None++ def test_a_condition_on_a_heavy_property_reads_the_native_ai_events_column(self) -> None:+ # `properties.$ai_input` is stripped from ai_events, so a filter that survives into the+ # SQL as a property read matches nothing on the real table.+ conditions = [+ {+ "properties": [{"key": "$ai_input", "value": "hello", "operator": "icontains", "type": "event"}],+ "rollout_percentage": 100,+ }+ ]+ executed: list[Any] = []++ def _capture(**kwargs: Any) -> Any:+ response = query_ai_events(**kwargs)+ executed.append(response)+ return response++ with patch(f"{CANDIDATES_MODULE}.query_ai_events", side_effect=_capture):+ self._count(target="generation", conditions=conditions)++ assert executed, "the count never reached ClickHouse"+ # The native column, not a JSONExtract on `properties`, which holds no heavy property.+ assert "ai_events.input" in (executed[0].clickhouse or "")++ def test_a_unit_spanning_the_cursor_is_returned_once_at_its_first_generation(self) -> None:+ self._create_generations((7, "t6", timedelta(minutes=30)), (8, "t6", timedelta(hours=3)))++ walked = [(candidate.unit_id, candidate.unit_timestamp) for candidate in self._walk(target="trace", limit=1)]++ # t6 spans the cursor: its later generation sits above every cursor the walk passes, and+ # the unit must still surface once, at the timestamp of its first generation.+ assert walked == [+ ("t3", BASE + timedelta(hours=2)),+ ("t2", BASE + timedelta(hours=1)),+ ("t6", BASE + timedelta(minutes=30)),+ ("t1", BASE),+ ]++ def test_a_unit_with_no_trace_id_is_still_judged_by_a_heavy_filter(self) -> None:+ # The heavy lookup reaches ai_events by trace id, which a generation is not obliged to+ # carry. Reaching that unit by its own id keeps it judged rather than silently dropped.+ untraced = _generation_uuid(30)+ _write_generations(+ [+ {+ "event": "$ai_generation",+ "distinct_id": "d-untraced",+ "team": self.team,+ "timestamp": BASE + timedelta(hours=5),+ "event_uuid": untraced,+ "properties": {"$ai_input": "hello there"},+ }+ ]+ )+ conditions = [+ {+ "properties": [{"key": "$ai_input", "value": "hello", "operator": "icontains", "type": "event"}],+ "rollout_percentage": 100,+ }+ ]++ page = self._fetch(target="generation", conditions=conditions, limit=10)++ assert untraced in [candidate.unit_id for candidate in page.candidates]++ def test_the_walk_crosses_a_quiet_stretch_wider_than_its_lookback(self) -> None:+ # Each page reads only as far below its cursor as a unit's events can reach, so a gap+ # wider than that returns nothing. The walk has to step down to the slice floor and carry+ # on, or a backfill would report itself complete at the first quiet day.+ far_start = BASE - timedelta(days=5)+ self._create_generations((20, "t-old", far_start - BASE))++ walked = [candidate.unit_id for candidate in self._walk(target="trace", limit=2, window_start=far_start)]++ assert "t-old" in walked+ assert walked[-1] == "t-old"++ def test_a_heavy_filter_settles_on_ai_events_and_drops_what_does_not_match(self) -> None:+ # `events` carries no $ai_input, so the units query cannot judge this filter. It finds the+ # traces and the second query decides, which must not leave the whole page in.+ conditions = [+ {+ "properties": [{"key": "$ai_input", "value": "hello", "operator": "icontains", "type": "event"}],+ "rollout_percentage": 100,+ }+ ]+ self._create_generations((21, "t-silent", timedelta(hours=4)))++ page = self._fetch(target="trace", conditions=conditions, limit=10)++ unit_ids = [candidate.unit_id for candidate in page.candidates]+ # Every fixture generation carries "hello there"; the one added here carries no input.+ assert "t-silent" not in unit_ids+ assert "t1" in unit_ids++ def test_empty_window_returns_no_candidates_and_a_zero_count(self) -> None:+ far_start = BASE + timedelta(days=30)+ far_end = far_start + timedelta(days=1)+ assert self._count(target="trace", window_start=far_start, window_end=far_end) == 0+ page = self._fetch(target="trace", window_start=far_start, window_end=far_end)+ assert page.candidates == []+ assert page.exhausted is Truediff --git a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambrindex 9657b80c53b1..e60646b8e2ee 100644--- a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr+++ b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr@@ -64,7 +64,7 @@HogQL defines what functions are available with most (but not all) having a 1:1 mapping to ClickHouse functions.These are the non-aggregated HogQL functions:```- ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', 'toIntOrDefault', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'dynamicType', 'toTypeName', 'defaultValueOfTypeName', 'cityHash64', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', '_caseWithExpression', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', '_finalizeAggregation', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']+ ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', 'toIntOrDefault', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'dynamicType', 'toTypeName', 'defaultValueOfTypeName', 'cityHash64', 'MD5', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', '_caseWithExpression', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', '_finalizeAggregation', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']```These are the aggregated HogQL functions: