: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
fix(aio): give backfill evaluation runs a longer retry budget (#117546)
Bernat Torresccfe2114d0a0
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.mdindex ad7bf86edbf4..e8ceee308d75 100644--- a/docs/internal/ai-observability-judge-inputs.md+++ b/docs/internal/ai-observability-judge-inputs.md@@ -184,6 +184,12 @@ The playground keeps the provider's explanation so users can correct the settingA backfill that stops on its own shows as **Interrupted**, with a stop reason.A backfill a user stops shows as **Cancelled**.+Backfill activities retry temporary database, DNS, connection, and rate-limit failures up to 5 times within 10 minutes, or within the live time limit when that is longer, with backoff from 10 seconds to one minute.+A backfill run that still hits a DNS failure on its last attempt fails instead of recording a skip, so **Retry remaining** can run it again.+Live evaluation retry budgets remain unchanged.+Authentication, quota, blocked-endpoint, and permanent request errors retain their existing handling.+Result emission has a separate retry budget, so retrying emission does not repeat a completed judge call.+An interrupted backfill preserves completed results.**Retry remaining** creates a new backfill with the original date range and filters, using the current evaluation settings.It preserves usable existing results and retries units without usable results.diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex 57e1bf35c176..617c13f12afc 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -44,6 +44,7 @@ from posthog.temporal.ai_observability.metrics import (increment_user_errors,)from posthog.temporal.ai_observability.model_resolution import model_spec+from posthog.temporal.ai_observability.retries import is_last_attemptfrom posthog.temporal.common.errors import NonReportableApplicationError, NonReportableErrorfrom posthog.temporal.common.utils import close_db_connections@@ -94,14 +95,34 @@ LLM_JUDGE_RETRY_POLICY = RetryPolicy(backoff_coefficient=2.0,)+BACKFILL_ACTIVITY_TIMEOUT = timedelta(minutes=10)+BACKFILL_ACTIVITY_RETRY_POLICY = RetryPolicy(+ maximum_attempts=5,+ initial_interval=timedelta(seconds=10),+ maximum_interval=timedelta(seconds=60),+ backoff_coefficient=2.0,+)+++def backfill_timeout(recover_backfill: bool, live: timedelta | None) -> timedelta | None:+ if not recover_backfill:+ return live+ return max(live, BACKFILL_ACTIVITY_TIMEOUT) if live else BACKFILL_ACTIVITY_TIMEOUT+++def backfill_retry_policy(recover_backfill: bool, live: RetryPolicy) -> RetryPolicy:+ return BACKFILL_ACTIVITY_RETRY_POLICY if recover_backfill else live+# A retry can fix these client errors, so they stay on the retry policy like a 5xx.# 499 is a cancellation, which Gemini already maps to the transport lane._RETRYABLE_CLIENT_ERROR_STATUSES = frozenset({408, 409, 429, 499})-def _is_last_judge_attempt() -> bool:- if not temporalio.activity.in_activity():+def _is_last_judge_attempt(backfill: bool = False) -> bool:+ # A backfill run never treats an attempt as its last: running out of retries fails the run, and+ # the backfill decides whether to pause or stop. Only a live run gives up for good.+ if backfill or not temporalio.activity.in_activity():return Falsereturn temporalio.activity.info().attempt >= (LLM_JUDGE_RETRY_POLICY.maximum_attempts or 0)@@ -270,10 +291,11 @@ def build_system_prompt({config.instructions}"""-@dataclass+@dataclass(frozen=False)class ExecuteLLMJudgeInputs:evaluation: dict[str, Any]event_data: dict[str, Any]+ backfill_id: str | None = None@propertydef properties_to_log(self) -> dict[str, Any]:@@ -526,6 +548,7 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActisystem_prompt=system_prompt,user_prompt=user_prompt,allows_na=allows_na,+ backfill=inputs.backfill_id is not None,)@@ -549,6 +572,7 @@ def call_llm_judge(system_prompt: str,user_prompt: str,allows_na: bool,+ backfill: bool = False,) -> EvaluationActivityResult:"""Resolve the judge model/key for `evaluation` and run a single judge completion.@@ -797,12 +821,14 @@ def call_llm_judge()except RetryableRateLimitError as e:increment_errors("rate_limit", provider=provider)+ retry_delay = timedelta(seconds=e.retry_after) if e.retry_after is not None else None# A retry usually gets through, so only an outage that outlasts every attempt reaches error tracking.- error_class = ApplicationError if _is_last_judge_attempt() else NonReportableApplicationError+ last = is_last_attempt(retry_delay) if backfill else _is_last_judge_attempt()+ error_class = ApplicationError if last else NonReportableApplicationErrorraise error_class(str(e),{"error_type": "provider_unavailable", "provider": provider},- next_retry_delay=timedelta(seconds=e.retry_after) if e.retry_after is not None else None,+ next_retry_delay=retry_delay,) from eexcept AuthenticationError:if is_byok:@@ -964,7 +990,7 @@ def call_llm_judge()except ProviderHostUnresolvedError as e:- if not _is_last_judge_attempt():+ if not _is_last_judge_attempt(backfill):increment_errors("connection_error", provider=provider)raise TransientJudgeError(str(e)) from e# The host did not resolve on any attempt, so the base URL is probably wrong. A faileddiff --git a/posthog/temporal/ai_observability/run_aggregate_evaluation.py b/posthog/temporal/ai_observability/run_aggregate_evaluation.pyindex 8b2dfc1c380c..62d593eb72ad 100644--- a/posthog/temporal/ai_observability/run_aggregate_evaluation.py+++ b/posthog/temporal/ai_observability/run_aggregate_evaluation.py@@ -34,7 +34,11 @@ from 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_resultfrom posthog.temporal.ai_observability.evaluation_event_io import as_utc_datetime-from posthog.temporal.ai_observability.evaluation_llm_judge import LLM_JUDGE_RETRY_POLICY+from posthog.temporal.ai_observability.evaluation_llm_judge import (+ LLM_JUDGE_RETRY_POLICY,+ backfill_retry_policy,+ backfill_timeout,+)from posthog.temporal.ai_observability.evaluation_workflow_activities import (EmitInternalTelemetryInputs,RunEvaluationInputs,@@ -482,6 +486,9 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):# 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+ recover_backfill = inputs.backfill_id is not None and temporalio.workflow.patched(+ "evaluation-backfill-extended-retries"+ )window_start = (as_utc_datetime(inputs.anchor_timestamp)if inputs.anchor_timestamp is not None@@ -526,7 +533,8 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):max_age_seconds=plan.max_age_seconds,),start_to_close_timeout=timedelta(seconds=60),- retry_policy=RetryPolicy(maximum_attempts=3),+ schedule_to_close_timeout=backfill_timeout(recover_backfill, None),+ retry_policy=backfill_retry_policy(recover_backfill, RetryPolicy(maximum_attempts=3)),)window_end = quiet_point@@ -591,8 +599,8 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):evaluation = await temporalio.workflow.execute_activity(fetch_evaluation_activity,RunEvaluationInputs(evaluation_id=inputs.evaluation_id, event_data={"team_id": inputs.team_id}),- schedule_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=3),+ schedule_to_close_timeout=backfill_timeout(recover_backfill, timedelta(seconds=30)),+ retry_policy=backfill_retry_policy(recover_backfill, RetryPolicy(maximum_attempts=3)),)evaluation_type = evaluation.get("evaluation_type", "llm_judge")@@ -616,22 +624,23 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):session_id=inputs.ai_session_id,window_start=window_start.isoformat(),window_end=window_end,+ backfill_id=inputs.backfill_id if recover_backfill else None,)if evaluation_type == "hog":result = await temporalio.workflow.execute_activity(execute_session_hog_eval_activity,session_inputs,# Longer than the trace equivalent: the fetch spans every trace of the session.- schedule_to_close_timeout=timedelta(minutes=5),- retry_policy=RetryPolicy(maximum_attempts=2),+ schedule_to_close_timeout=backfill_timeout(recover_backfill, timedelta(minutes=5)),+ retry_policy=backfill_retry_policy(recover_backfill, RetryPolicy(maximum_attempts=2)),)else:try:result = await temporalio.workflow.execute_activity(execute_session_llm_judge_activity,session_inputs,- schedule_to_close_timeout=timedelta(minutes=15),- retry_policy=LLM_JUDGE_RETRY_POLICY,+ schedule_to_close_timeout=backfill_timeout(recover_backfill, timedelta(minutes=15)),+ retry_policy=backfill_retry_policy(recover_backfill, LLM_JUDGE_RETRY_POLICY),)except temporalio.exceptions.ActivityError as e:handled = await handle_llm_judge_activity_error(e, evaluation, evaluation_type)@@ -645,6 +654,7 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):trace_id=inputs.trace_id,window_start=window_start.isoformat(),window_end=window_end,+ backfill_id=inputs.backfill_id if recover_backfill else None,)if evaluation_type == "hog":@@ -653,8 +663,8 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):result = await temporalio.workflow.execute_activity(execute_trace_hog_eval_activity,execute_inputs,- schedule_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=2),+ schedule_to_close_timeout=backfill_timeout(recover_backfill, timedelta(minutes=2)),+ retry_policy=backfill_retry_policy(recover_backfill, RetryPolicy(maximum_attempts=2)),)else:try:@@ -662,8 +672,8 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):execute_trace_llm_judge_activity,execute_inputs,# > single-event judge timeout: the activity also fetches the trace from ClickHouse- schedule_to_close_timeout=timedelta(minutes=8),- retry_policy=LLM_JUDGE_RETRY_POLICY,+ schedule_to_close_timeout=backfill_timeout(recover_backfill, timedelta(minutes=8)),+ retry_policy=backfill_retry_policy(recover_backfill, LLM_JUDGE_RETRY_POLICY),)except temporalio.exceptions.ActivityError as e:handled = await handle_llm_judge_activity_error(e, evaluation, evaluation_type)diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.pyindex 792e6957cbd7..bdc9e456c375 100644--- a/posthog/temporal/ai_observability/run_evaluation.py+++ b/posthog/temporal/ai_observability/run_evaluation.py@@ -24,6 +24,8 @@ from posthog.temporal.ai_observability.evaluation_llm_judge import (BooleanEvalResult,BooleanWithNAEvalResult,ExecuteLLMJudgeInputs,+ backfill_retry_policy,+ backfill_timeout,build_system_prompt,execute_llm_judge_activity,get_output_type_config,@@ -265,6 +267,9 @@ class RunEvaluationWorkflow(PostHogWorkflow):temporalio.workflow.deprecate_patch("remove-trial-evals")start_time = temporalio.workflow.now()+ recover_backfill = inputs.backfill_id is not None and temporalio.workflow.patched(+ "evaluation-backfill-extended-retries"+ )# 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@@ -291,8 +296,8 @@ class RunEvaluationWorkflow(PostHogWorkflow):# Total deadline including queue wait: without it a task stuck in the queue# keeps the workflow RUNNING forever, and USE_EXISTING then blocks every later# trigger for this (evaluation, event) pair.- schedule_to_close_timeout=timedelta(minutes=8),- retry_policy=RetryPolicy(maximum_attempts=3),+ schedule_to_close_timeout=backfill_timeout(recover_backfill, timedelta(minutes=8)),+ retry_policy=backfill_retry_policy(recover_backfill, RetryPolicy(maximum_attempts=3)),)except temporalio.exceptions.ActivityError as e:if isinstance(e.cause, ApplicationError) and e.cause.type == EMIT_EVALUATION_EVENT_FAILED_ERROR_TYPE:@@ -332,9 +337,13 @@ class RunEvaluationWorkflow(PostHogWorkflow):try:result = await temporalio.workflow.execute_activity(execute_llm_judge_activity,- ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data),- schedule_to_close_timeout=timedelta(minutes=6),- retry_policy=LLM_JUDGE_RETRY_POLICY,+ ExecuteLLMJudgeInputs(+ evaluation=evaluation,+ event_data=event_data,+ backfill_id=inputs.backfill_id if recover_backfill else None,+ ),+ schedule_to_close_timeout=backfill_timeout(recover_backfill, timedelta(minutes=6)),+ retry_policy=backfill_retry_policy(recover_backfill, LLM_JUDGE_RETRY_POLICY),)except temporalio.exceptions.ActivityError as e:handled = await handle_llm_judge_activity_error(e, evaluation, evaluation_type)diff --git a/posthog/temporal/ai_observability/run_session_evaluation.py b/posthog/temporal/ai_observability/run_session_evaluation.pyindex 5ba881dc7fdf..eda5baab8559 100644--- a/posthog/temporal/ai_observability/run_session_evaluation.py+++ b/posthog/temporal/ai_observability/run_session_evaluation.py@@ -441,6 +441,7 @@ class ExecuteSessionEvaluationInputs:# 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+ backfill_id: str | None = None@propertydef window_end_datetime(self) -> datetime | None:@@ -508,6 +509,7 @@ def execute_session_llm_judge_activity(inputs: ExecuteSessionEvaluationInputs) -),user_prompt=transcript,allows_na=allows_na,+ backfill=inputs.backfill_id is not None,)diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex 4438662044fb..308a019794c7 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -176,6 +176,7 @@ class ExecuteTraceEvaluationInputs:# 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+ backfill_id: str | None = None@propertydef window_end_datetime(self) -> datetime | None:@@ -703,6 +704,7 @@ def execute_trace_llm_judge_activity(inputs: ExecuteTraceEvaluationInputs) -> Ev),user_prompt=format_trace_for_judge(outcome.trace),allows_na=allows_na,+ backfill=inputs.backfill_id is not None,)diff --git a/posthog/temporal/ai_observability/test_evaluation_backfill.py b/posthog/temporal/ai_observability/test_evaluation_backfill.pyindex 30816f0c5ac4..d4dd0e6ee2bc 100644--- a/posthog/temporal/ai_observability/test_evaluation_backfill.py+++ b/posthog/temporal/ai_observability/test_evaluation_backfill.py@@ -9,10 +9,13 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom django.conf import settingsfrom django.test import override_settings+import temporaliofrom asgiref.sync import async_to_sync+from temporalio.client import WorkflowFailureErrorfrom temporalio.common import WorkflowIDReusePolicy-from temporalio.exceptions import ActivityError, CancelledError, WorkflowAlreadyStartedError-from temporalio.testing import ActivityEnvironment+from temporalio.exceptions import ActivityError, ApplicationError, CancelledError, WorkflowAlreadyStartedError+from temporalio.testing import ActivityEnvironment, WorkflowEnvironment+from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Workerfrom temporalio.workflow import ParentClosePolicyfrom posthog.models import Organization, Team@@ -37,11 +40,19 @@ from posthog.temporal.ai_observability.evaluation_backfill import (measure_evaluation_backfill_remainder_activity,prepare_evaluation_backfill_tick_activity,)+from posthog.temporal.ai_observability.evaluation_llm_judge import _is_last_judge_attempt+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResultfrom posthog.temporal.ai_observability.evaluation_workflow_activities import (+ LocalEvaluationOutcome,RunEvaluationInputs,+ RunLocalEvaluationInputs,backfill_verdict_timestamp,)-from posthog.temporal.ai_observability.run_aggregate_evaluation import RunAggregateEvaluationInputs+from posthog.temporal.ai_observability.run_aggregate_evaluation import (+ RunAggregateEvaluationInputs,+ RunAggregateEvaluationWorkflow,+)+from posthog.temporal.ai_observability.run_evaluation import RunEvaluationWorkflowfrom products.ai_observability.backend.backfill_candidates import BackfillCandidate, BackfillScope, CandidatePagefrom products.ai_observability.backend.models.evaluation_backfill import EvaluationBackfill, EvaluationBackfillStatus@@ -137,6 +148,140 @@ def _advance_input(mocks: _BackfillMocks) -> AdvanceCursorInputs:class TestEvaluationBackfillWorkflow:+ @pytest.mark.asyncio+ @pytest.mark.parametrize("target", ["generation", "trace", "session"])+ @pytest.mark.parametrize(+ "is_backfill,legacy,persistent",+ [(False, False, False), (True, False, False), (True, True, False), (True, False, True)],+ )+ @pytest.mark.parametrize("failure_kind", ["capacity", "dns"])+ async def test_transient_judge_failures_recover_for_backfills(+ self,+ target: str,+ is_backfill: bool,+ legacy: bool,+ persistent: bool,+ failure_kind: str,+ caplog: pytest.LogCaptureFixture,+ ) -> None:+ caplog.set_level("INFO", logger="temporalio.workflow")+ caplog.set_level("INFO", logger="temporalio.activity")+ attempts: list[int] = []+ emitted: list[dict[str, Any]] = []+ recovers = is_backfill and not legacy+ evaluation = {+ "id": "E",+ "team_id": 42,+ "evaluation_type": "llm_judge",+ "output_type": "boolean",+ "enabled": True,+ "deleted": False,+ }++ @temporalio.activity.defn(name="run_local_evaluation_activity")+ async def local(_: RunLocalEvaluationInputs) -> LocalEvaluationOutcome:+ return LocalEvaluationOutcome(evaluation=evaluation, result=None, emitted=False)++ @temporalio.activity.defn(name="fetch_evaluation_activity")+ async def fetch(_: RunEvaluationInputs) -> dict[str, Any]:+ return evaluation++ @temporalio.activity.defn(+ name={+ "generation": "execute_llm_judge_activity",+ "trace": "execute_trace_llm_judge_activity",+ "session": "execute_session_llm_judge_activity",+ }[target]+ )+ async def judge(payload: dict[str, Any]) -> EvaluationActivityResult:+ info = temporalio.activity.info()+ attempt = info.attempt+ if recovers:+ assert info.schedule_to_close_timeout == timedelta(minutes=15 if target == "session" else 10)+ attempts.append(attempt)+ if attempt <= 4 or persistent:+ if failure_kind == "dns" and _is_last_judge_attempt(payload.get("backfill_id") is not None):+ return {+ "result_type": "boolean",+ "skipped": True,+ "skip_reason": "host_unresolved",+ "reasoning": "Example endpoint could not resolve",+ "allows_na": False,+ }+ raise ApplicationError("Query capacity is temporarily unavailable", type="ConcurrencyLimitExceeded")+ return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}++ @temporalio.activity.defn(+ name="emit_evaluation_event_activity" if target == "generation" else "emit_trace_evaluation_event_activity"+ )+ async def emit(payload: dict[str, Any]) -> None:+ emitted.append(payload)++ @temporalio.activity.defn(name="emit_internal_telemetry_activity")+ async def telemetry(_: dict[str, Any]) -> None:+ return++ inputs: RunEvaluationInputs | RunAggregateEvaluationInputs+ backfill_id = "B" if is_backfill else None+ if target == "generation":+ inputs = RunEvaluationInputs(evaluation_id="E", event_data={"team_id": 42}, backfill_id=backfill_id)+ workflow_name = "run-evaluation"+ else:+ inputs = RunAggregateEvaluationInputs(+ evaluation_id="E",+ team_id=42,+ trace_id="example-trace",+ distinct_id="example-user",+ ai_session_id="example-session" if target == "session" else None,+ target=target,+ settle={"strategy": "fixed_window", "window_seconds": 10},+ anchor_timestamp=UNIT_TIMESTAMP.isoformat() if is_backfill else None,+ backfill_id=backfill_id,+ )+ workflow_name = "run-aggregate-evaluation"++ task_queue = str(uuid.uuid4())+ original_patched = temporalio.workflow.patched++ def patched(patch_id: str) -> bool:+ if legacy and patch_id == "evaluation-backfill-extended-retries":+ return False+ return original_patched(patch_id)++ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[RunEvaluationWorkflow, RunAggregateEvaluationWorkflow],+ activities=[local, fetch, judge, emit, telemetry],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ with patch("temporalio.workflow.patched", side_effect=patched):+ handle = await env.client.start_workflow(+ workflow_name,+ inputs,+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ execution_timeout=timedelta(minutes=40),+ )+ if persistent or (not recovers and failure_kind == "capacity"):+ with pytest.raises(WorkflowFailureError):+ await handle.result()+ elif recovers:+ result = await handle.result()+ assert result["verdict"] is True+ else:+ result = await handle.result()+ assert result["skip_reason"] == "host_unresolved"+ history = await handle.fetch_history()++ assert attempts == ([1, 2, 3, 4, 5] if recovers else [1, 2, 3])+ assert len(emitted) == int(not persistent and (recovers or failure_kind == "dns"))+ await Replayer(+ workflows=[RunEvaluationWorkflow, RunAggregateEvaluationWorkflow],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ).replay_workflow(history)+@pytest.mark.asyncioasync def test_finished_tick_returns_without_dispatch(self) -> None:mocks = _BackfillMocks(diff --git a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.pyindex 5b11237373a4..e138e63470e5 100644--- a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py@@ -7,6 +7,7 @@ import time_machinefrom unittest.mock import patchfrom temporalio import activity+from temporalio.api.enums.v1 import EventTypefrom temporalio.exceptions import ApplicationErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker@@ -400,8 +401,7 @@ class TestRunAggregateEvaluationWorkflow:],workflow_runner=UnsandboxedWorkflowRunner(),):- start = await env.get_current_time()- result = await env.client.execute_workflow(+ handle = await env.client.start_workflow(RunAggregateEvaluationWorkflow.run,_workflow_inputs({"strategy": "fixed_window", "window_seconds": 1800},@@ -411,7 +411,8 @@ class TestRunAggregateEvaluationWorkflow:id=str(uuid.uuid4()),task_queue=task_queue,)- elapsed = (await env.get_current_time()) - start+ result = await handle.result()+ history = await handle.fetch_history()assert calls == ["fetch", "execute", "emit", "telemetry"]assert result["verdict"] is True@@ -421,9 +422,7 @@ class TestRunAggregateEvaluationWorkflow: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)+ assert EventType.EVENT_TYPE_TIMER_STARTED not in {event.event_type for event in history.events}@pytest.mark.asyncioasync def test_a_backfilled_inactivity_unit_reads_to_its_quiet_point(self):diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 4675903ee581..d4ff271ba8f6 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -66,6 +66,7 @@ from .evaluation_errors import ()from .evaluation_event_io import GENERATION_NOT_FOUND_RETRY_DELAY, hydrate_event_referencefrom .evaluation_llm_judge import (+ BACKFILL_ACTIVITY_RETRY_POLICY,NumericWithNAEvalResult,TransientJudgeError,_build_errored_trace_result,@@ -1024,7 +1025,9 @@ def test_provider_rejections_distinguish_blocked_endpoints_from_bad_inputs(assert "uncompressed responses no larger than 1 MiB" in result["reasoning"]-def _call_openai_compatible_judge(resolved_ips: set[IPv4Address | IPv6Address]) -> EvaluationActivityResult:+def _call_openai_compatible_judge(+ resolved_ips: set[IPv4Address | IPv6Address], backfill: bool = False+) -> EvaluationActivityResult:key = MagicMock(provider="openai_compatible",encrypted_config={"api_key": "example-token", "base_url": "https://decisions.example.com/v1"},@@ -1041,6 +1044,7 @@ def _call_openai_compatible_judge(resolved_ips: set[IPv4Address | IPv6Address])system_prompt="",user_prompt="Hello!",allows_na=False,+ backfill=backfill,)@@ -1053,13 +1057,13 @@ def test_endpoint_on_a_disallowed_address_is_a_terminal_user_error() -> None:assert "Base URL must be a public https:// URL" in result["reasoning"][email protected]("attempt", [1, 2])-def test_endpoint_host_that_does_not_resolve_is_retried(attempt: int) -> None:[email protected]("attempt,backfill", [(1, False), (2, False), (3, True), (5, True)])+def test_endpoint_host_that_does_not_resolve_is_retried(attempt: int, backfill: bool) -> None:env = ActivityEnvironment()env.info = dataclasses.replace(env.info, attempt=attempt)with pytest.raises(TransientJudgeError):- env.run(_call_openai_compatible_judge, set())+ env.run(_call_openai_compatible_judge, set(), backfill)def test_endpoint_host_that_never_resolves_skips_the_run_with_the_reason() -> None:@@ -1121,17 +1125,27 @@ def test_endpoint_host_that_never_resolves_skips_the_run_with_the_reason() -> No],)@pytest.mark.parametrize(- "attempt,reportable",+ "attempt,backfill,reportable",[- pytest.param(1, False, id="first attempt"),- pytest.param(3, True, id="last attempt"),+ pytest.param(1, False, False, id="first attempt"),+ pytest.param(3, False, True, id="last attempt"),+ pytest.param(3, True, False, id="backfill third attempt"),+ pytest.param(5, True, True, id="backfill last attempt"),],)def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(- provider: str, success_payload: dict[str, Any], status: int, retry_after: int, attempt: int, reportable: bool+ provider: str,+ success_payload: dict[str, Any],+ status: int,+ retry_after: int,+ attempt: int,+ backfill: bool,+ reportable: bool,) -> None:env = ActivityEnvironment()- env.info = dataclasses.replace(env.info, attempt=attempt)+ env.info = dataclasses.replace(+ env.info, attempt=attempt, retry_policy=BACKFILL_ACTIVITY_RETRY_POLICY, schedule_to_close_timeout=None+ )evaluation = {"team_id": 1,"evaluation_config": {"prompt": "Polite?", **({"judge_method": "decision"} if provider == "openai" else {})},@@ -1169,6 +1183,7 @@ def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(system_prompt="",user_prompt="Hello!",allows_na=False,+ backfill=backfill,))assert not error.value.non_retryable