: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): hold generation backfills 30s and retry a missing generation twice (#108631)
Bernat Torres286f80851518
diff --git a/posthog/temporal/ai_observability/evaluation_event_io.py b/posthog/temporal/ai_observability/evaluation_event_io.pyindex c91b2bfaec06..89004fdc854b 100644--- a/posthog/temporal/ai_observability/evaluation_event_io.py+++ b/posthog/temporal/ai_observability/evaluation_event_io.py@@ -1,13 +1,19 @@from datetime import datetimefrom typing import Any+import temporalio.activityfrom temporalio.exceptions import ApplicationErrorfrom posthog.dataclasses import frozen+from posthog.temporal.common.errors import NonReportableApplicationErrorfrom posthog.utils import ensure_utcfrom products.ai_observability.backend.ai_event_lookup import fetch_generation_event+# A generation can reach `events`, where a backfill finds it, before it reaches `ai_events`, where+# it is read, so a miss gets two retries before it fails the run.+GENERATION_NOT_FOUND_MAX_ATTEMPTS = 3+def as_utc_datetime(value: str | datetime) -> datetime:"""Read a ClickHouse event timestamp, which reaches us as a naive datetime on a direct call@@ -81,5 +87,8 @@ def hydrate_event_reference(event_data: dict[str, Any]) -> dict[str, Any]:event_data.get("trace_id"),)if event is None:+ if temporalio.activity.in_activity() and temporalio.activity.info().attempt < GENERATION_NOT_FOUND_MAX_ATTEMPTS:+ # Only the last miss reaches error tracking: an earlier one is usually the lag above.+ raise NonReportableApplicationError("Generation not found", type="generation_not_found")raise ApplicationError("Generation not found", type="generation_not_found", non_retryable=True)return eventdiff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex f9d117ff2981..9e38f134c90f 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -1,5 +1,6 @@import jsonimport uuid+import dataclassesfrom datetime import UTC, datetime, timedeltafrom ipaddress import ip_addressfrom typing import Any, cast@@ -17,7 +18,7 @@ from pydantic import ValidationError as PydanticValidationErrorfrom temporalio import activityfrom temporalio.api.enums.v1 import EventTypefrom temporalio.exceptions import ApplicationError, CancelledError-from temporalio.testing import WorkflowEnvironment+from temporalio.testing import ActivityEnvironment, WorkflowEnvironmentfrom temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Workerfrom posthog.api.capture import CaptureInternalError@@ -25,6 +26,7 @@ from posthog.constants import AvailableFeaturefrom posthog.models import Organization, OrganizationMembership, Team, Userfrom posthog.temporal.ai_observability.sentiment.extraction import truncate_to_head_tailfrom posthog.temporal.ai_observability.sentiment.schema import SentimentResult+from posthog.temporal.common.errors import NonReportableErrorfrom products.access_control.backend.models.access_control import AccessControlfrom products.ai_observability.backend.llm.errors import (@@ -51,6 +53,7 @@ from .evaluation_errors import (status_reason_detail_for_terminal_user_error,terminal_user_error_result_from_application_error,)+from .evaluation_event_io import hydrate_event_referencefrom .evaluation_llm_judge import (JUDGE_EVENT_MAX_CHARS,NumericWithNAEvalResult,@@ -1214,6 +1217,25 @@ class TestRunEvaluationWorkflow:assert mock_fetch.call_count == 1+ @pytest.mark.parametrize(+ "attempt,retryable",+ [+ pytest.param(1, True, id="first attempt"),+ pytest.param(2, True, id="second attempt"),+ pytest.param(3, False, id="last attempt"),+ ],+ )+ def test_a_missing_generation_gets_two_retries_before_it_fails_the_run(self, attempt: int, retryable: bool):+ env = ActivityEnvironment()+ env.info = dataclasses.replace(env.info, attempt=attempt)+ with patch(HYDRATE_FETCH, return_value=None):+ with pytest.raises(ApplicationError) as raised:+ env.run(hydrate_event_reference, dict(THIN_REFERENCE))++ assert raised.value.type == "generation_not_found"+ assert raised.value.non_retryable is not retryable+ assert isinstance(raised.value, NonReportableError) is retryable+def test_parse_inputs(self):"""Test that parse_inputs correctly parses workflow inputs"""event_data = create_mock_event_data(team_id=1)diff --git a/products/ai_observability/backend/api/evaluation_backfills.py b/products/ai_observability/backend/api/evaluation_backfills.pyindex 3f719de68f4d..8d13aed9469b 100644--- a/products/ai_observability/backend/api/evaluation_backfills.py+++ b/products/ai_observability/backend/api/evaluation_backfills.py@@ -84,6 +84,11 @@ BACKFILL_START_GRACE = timedelta(minutes=2)# no timeout, and the list still answers 200, so nothing upstream slows the polling down.BACKFILL_ALIVE_CACHE_SECONDS = 60+# Candidates come from `events`, but each generation is read back from `ai_events`, which a+# separate pipeline fills later, and a small share of generations take longer than the shared+# ingestion margin to land there.+BACKFILL_AI_EVENTS_LAG = timedelta(seconds=30)+@frozenclass BackfillWindow:@@ -332,10 +337,9 @@ class EvaluationBackfillViewSet(def _clamped_window(self, evaluation: Evaluation, data: dict[str, Any]) -> BackfillWindow:"""The requested window, bounded to the span whose verdicts can be read back."""now = timezone.now()- # Candidates come from `events`, but each generation is read back from `ai_events`, which a- # separate pipeline fills later. A generation that has not reached `ai_events` yet fails its- # run for good, so the window stops short of the newest events.- window_end: datetime = min(data["window_end"], now - timedelta(seconds=INGESTION_LAG_MARGIN_SECONDS))+ # A generation that has not reached `ai_events` yet fails its run, so the window stops short+ # of the newest events.+ window_end: datetime = min(data["window_end"], now - BACKFILL_AI_EVENTS_LAG)settle_hold = settle_horizon(evaluation.target, evaluation.target_config)if settle_hold:# A trace or session is graded over `settle_hold` from its first event, so a unit anydiff --git a/products/ai_observability/backend/api/test/test_evaluation_backfills.py b/products/ai_observability/backend/api/test/test_evaluation_backfills.pyindex cafd5987a1a9..04044d5b3893 100644--- a/products/ai_observability/backend/api/test/test_evaluation_backfills.py+++ b/products/ai_observability/backend/api/test/test_evaluation_backfills.py@@ -26,11 +26,14 @@ from posthog.rate_limit import (AIObservabilityBackfillEstimateSustainedThrottle,AIObservabilityBackfillEstimateThrottle,)-from posthog.temporal.ai_observability.run_aggregate_evaluation import INGESTION_LAG_MARGIN_SECONDSfrom posthog.temporal.ai_observability.run_session_evaluation import AI_EVENTS_RETENTION_DAYSfrom products.access_control.backend.models.access_control import AccessControl-from products.ai_observability.backend.api.evaluation_backfills import BACKFILL_RETENTION_MARGIN, BACKFILL_START_GRACE+from products.ai_observability.backend.api.evaluation_backfills import (+ BACKFILL_AI_EVENTS_LAG,+ BACKFILL_RETENTION_MARGIN,+ BACKFILL_START_GRACE,+)from products.ai_observability.backend.backfill_candidates import BackfillScopefrom products.ai_observability.backend.models.evaluation_backfill import EvaluationBackfill, EvaluationBackfillStatusfrom products.ai_observability.backend.models.evaluations import Evaluation@@ -421,7 +424,7 @@ class TestEvaluationBackfillsApi(APIBaseTest):estimate = self.client.post(f"{self.url}/estimate/", body, format="json")assert estimate.status_code == status.HTTP_200_OK, estimate.json()- expected_end = now - timedelta(seconds=INGESTION_LAG_MARGIN_SECONDS)+ expected_end = now - BACKFILL_AI_EVENTS_LAGassert abs(datetime.fromisoformat(estimate.json()["window_end"]) - expected_end) < timedelta(seconds=5)expected_start = now - timedelta(days=AI_EVENTS_RETENTION_DAYS)assert abs(datetime.fromisoformat(estimate.json()["window_start"]) - expected_start) < timedelta(seconds=5)@@ -469,7 +472,7 @@ class TestEvaluationBackfillsApi(APIBaseTest):@patch(f"{API_MODULE}.sync_connect")def test_a_generation_backfill_stops_short_of_the_ai_events_lag(self, connect, _count):connect.return_value = _temporal_client()- margin = timedelta(seconds=INGESTION_LAG_MARGIN_SECONDS)+ margin = BACKFILL_AI_EVENTS_LAGbefore = timezone.now()estimate = self.client.post(f"{self.url}/estimate/", _body(), format="json")