: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): add the evaluation backfills API and Backfills tab (#95052)
Bernat Torres1409f00cb2ca
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex ca57e9b1a4fe..1ba94449be2e 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -361,6 +361,7 @@ export const FEATURE_FLAGS = {LLM_ANALYTICS_CLUSTERING_ADMIN: 'llm-analytics-clustering-admin', // owner: #team-ai-observabilityLLM_ANALYTICS_COMMUNITY_SKILLS: 'llm-analytics-community-skills', // owner: #team-ai-observabilityLLM_ANALYTICS_DATASETS: 'llm-analytics-datasets', // owner: #team-ai-observability #team-posthog-ai+ LLM_ANALYTICS_EVAL_BACKFILLS: 'llm-analytics-eval-backfills', // owner: #team-ai-observabilityLLM_ANALYTICS_EVAL_SETTLING_STRATEGY: 'llm-analytics-eval-settling-strategy', // owner: #team-ai-observabilityLLM_ANALYTICS_EVALUATIONS_START_WITH_AI: 'llm-analytics-evaluations-start-with-ai', // owner: #team-ai-observabilityLLM_ANALYTICS_OFFLINE_EVALS: 'llm-analytics-offline-evals', // owner: #team-ai-observabilitydiff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex a3d8a973cc3a..342d6db9418c 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -970,6 +970,40 @@ class AIObservabilitySummarizationDailyThrottle(PersonalApiKeyOrUserRateThrottlerate = "500/day"+class AIObservabilityBackfillEstimateThrottle(_UserBucketRateThrottle):+ """`estimate` runs a synchronous ClickHouse count, so a caller could otherwise saturate the+ query pool by resubmitting wide windows. Its own bucket keeps the call the UI makes on every+ window change from using up the caller's budget for starting a backfill.++ Per credential so one user changing the window cannot lock the tab for the rest of the team.+ The aggregate is capped by the team-wide companion below."""++ scope = "llma_eval_backfill_estimate"+ rate = "20/minute"+++class AIObservabilityBackfillCreateThrottle(_UserBucketRateThrottle):+ """`create` runs the same ClickHouse count as `estimate`, and also starts a workflow."""++ scope = "llma_eval_backfill_create"+ rate = "10/minute"+++# The buckets above ident a personal-API-key request by key hash, so every key a user mints gets a+# full budget of the counts these two actions run, and each member of the team gets one as well.+# The query pool they spend is shared PostHog infrastructure, so the total needs a bucket of its own,+# the same pairing ReplayVisionSearch uses. An hour at ten times the per-minute burst leaves a team's+# worth of concurrent editors untouched while capping a scripted loop across credentials.+class AIObservabilityBackfillEstimateSustainedThrottle(_TeamBucketRateThrottle):+ scope = "llma_eval_backfill_estimate_sustained"+ rate = "200/hour"+++class AIObservabilityBackfillCreateSustainedThrottle(_TeamBucketRateThrottle):+ scope = "llma_eval_backfill_create_sustained"+ rate = "100/hour"++class _CustomSourceAIBuilderThrottle(PersonalApiKeyOrUserRateThrottle):"""Per-team throttle for the (paid, Opus-backed) custom-source AI manifest builder.diff --git a/posthog/temporal/ai_observability/evaluation_backfill.py b/posthog/temporal/ai_observability/evaluation_backfill.pyindex a1d93e1a9dd1..dbae5f7007b1 100644--- a/posthog/temporal/ai_observability/evaluation_backfill.py+++ b/posthog/temporal/ai_observability/evaluation_backfill.py@@ -371,7 +371,8 @@ class EvaluationBackfillWorkflow(PostHogWorkflow):)# 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.+ # is left to a later backfill, and counted as neither dispatched nor skipped, because+ # skipped means the live path already graded it.results = await asyncio.gather(*(self._start_child(inputs, tick, candidate) for candidate in found.candidates),return_exceptions=True,@@ -383,7 +384,7 @@ class EvaluationBackfillWorkflow(PostHogWorkflow):extra={"backfill_id": inputs.backfill_id, "error": str(error)},)dispatched = sum(1 for result in results if result is True)- skipped = len(results) - dispatched+ skipped = sum(1 for result in results if result is False)advance = await temporalio.workflow.execute_activity(advance_evaluation_backfill_cursor_activity,AdvanceCursorInputs(diff --git a/posthog/temporal/ai_observability/test_evaluation_backfill.py b/posthog/temporal/ai_observability/test_evaluation_backfill.pyindex 9f93569e1c95..548ae5ba5ac2 100644--- a/posthog/temporal/ai_observability/test_evaluation_backfill.py+++ b/posthog/temporal/ai_observability/test_evaluation_backfill.py@@ -109,7 +109,8 @@ def _found(candidates: list[CandidatePayload], *, exhausted: bool = False) -> Fiasync 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)})()+ noop = staticmethod(lambda *_a, **_kw: None)+ fake_logger = type("Logger", (), {"exception": noop, "warning": noop})()with (patch("temporalio.workflow.logger", fake_logger),patch("temporalio.workflow.execute_activity", side_effect=mocks.execute_activity),@@ -190,6 +191,23 @@ class TestEvaluationBackfillWorkflow:advance = _advance_input(mocks)assert (advance.dispatched_delta, advance.skipped_delta) == (2, 1)+ @pytest.mark.asyncio+ async def test_a_start_failure_counts_as_neither_dispatched_nor_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": RuntimeError("temporal refused the start")},+ )++ await _run(mocks)++ advance = _advance_input(mocks)+ assert (advance.dispatched_delta, advance.skipped_delta) == (2, 0)+@pytest.mark.asyncioasync def test_exhausted_page_finishes_without_continue_as_new(self) -> None:mocks = _BackfillMocks(diff --git a/products/ai_observability/backend/api/__init__.py b/products/ai_observability/backend/api/__init__.pyindex 7584c9b457a1..41ba3079e3d5 100644--- a/products/ai_observability/backend/api/__init__.py+++ b/products/ai_observability/backend/api/__init__.py@@ -3,6 +3,7 @@ from .clustering import AIObservabilityClusteringRunViewSetfrom .clustering_config import ClusteringConfigViewSetfrom .clustering_job import ClusteringJobViewSetfrom .datasets import DatasetItemViewSet, DatasetViewSet+from .evaluation_backfills import EvaluationBackfillViewSetfrom .evaluation_config import EvaluationConfigViewSetfrom .evaluation_directories import EvaluationDirectoryViewSetfrom .evaluation_reports import EvaluationReportViewSet@@ -38,6 +39,7 @@ __all__ = ["DatasetViewSet","DatasetItemViewSet","EvaluationViewSet",+ "EvaluationBackfillViewSet","EvaluationDirectoryViewSet","EvaluationReportViewSet","EvaluationRunViewSet",diff --git a/products/ai_observability/backend/api/evaluation_backfills.py b/products/ai_observability/backend/api/evaluation_backfills.pynew file mode 100644index 000000000000..e2f75c8055e2--- /dev/null+++ b/products/ai_observability/backend/api/evaluation_backfills.py@@ -0,0 +1,612 @@+import uuid+import asyncio+from datetime import datetime, timedelta+from typing import Any, Protocol, cast++from django.conf import settings+from django.core.cache import cache+from django.db import IntegrityError+from django.db.models import QuerySet+from django.utils import timezone++import structlog+from drf_spectacular.utils import extend_schema+from rest_framework import mixins, serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.exceptions import APIException, NotFound, ValidationError+from rest_framework.permissions import BasePermission, IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.throttling import BaseThrottle+from rest_framework.views import APIView+from temporalio.client import WorkflowExecutionStatus+from temporalio.common import WorkflowIDReusePolicy+from temporalio.service import RPCError, RPCStatusCode++from posthog.hogql.errors import BaseHogQLError+from posthog.hogql.property import property_to_expr++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.shared import UserBasicSerializer+from posthog.dataclasses import frozen+from posthog.models.user import User+from posthog.permissions import (+ AccessControlPermission,+ APIScopePermission,+ PostHogFeatureFlagPermission,+ TeamMemberAccessPermission,+)+from posthog.rate_limit import (+ AIObservabilityBackfillCreateSustainedThrottle,+ AIObservabilityBackfillCreateThrottle,+ AIObservabilityBackfillEstimateSustainedThrottle,+ AIObservabilityBackfillEstimateThrottle,+)+from posthog.temporal.ai_observability.evaluation_backfill import (+ BACKFILL_WORKFLOW_NAME,+ EvaluationBackfillInputs,+ backfill_workflow_id,+ cancel_backfill,+ settle_horizon,+)+from posthog.temporal.ai_observability.run_aggregate_evaluation import INGESTION_LAG_MARGIN_SECONDS+from posthog.temporal.ai_observability.run_session_evaluation import AI_EVENTS_RETENTION_DAYS+from posthog.temporal.common.client import sync_connect++from products.access_control.backend.property_access_control import get_restricted_properties_for_team+from products.ai_observability.backend.api.evaluations import EvaluationConditionSerializer+from products.ai_observability.backend.backfill_candidates import count_backfill_candidates+from products.ai_observability.backend.models.evaluation_backfill import ACTIVE_BACKFILL_STATUSES, EvaluationBackfill+from products.ai_observability.backend.models.evaluations import Evaluation, EvaluationTarget++logger = structlog.get_logger(__name__)+++WRITE_ACTIONS = ["create", "cancel"]++# The walk pages newest-first, so the oldest units are stamped last, hours or days after the+# window was clamped. Without headroom their verdicts age past the team's drop threshold while+# the backfill is still running, and ingestion throws them away.+BACKFILL_RETENTION_MARGIN = timedelta(days=1)++# A row this young may belong to a create that has not reached `start_workflow` yet, so Temporal+# answers NOT_FOUND for a backfill that is about to be valid. Probing it would let a concurrent+# create cancel a live run and start a second walk over the same units.+BACKFILL_START_GRACE = timedelta(minutes=2)++# The tab polls the list every ten seconds while a backfill runs, and a session-authenticated+# request passes the default throttles, so probing on every request would let one open tab, or one+# caller in a loop, set the rate of a synchronous Temporal call. A live answer stays good for a+# tick, and the release of a dead row waits at most this long. An answer Temporal could not give+# is held for the same tick, because that probe is the expensive one: it opens a connection with+# no timeout, and the list still answers 200, so nothing upstream slows the polling down.+BACKFILL_ALIVE_CACHE_SECONDS = 60+++@frozen+class BackfillWindow:+ """The span a backfill covers once every bound has been applied."""++ start: datetime+ end: datetime+++def _duration_label(duration: timedelta) -> str:+ minutes = duration.total_seconds() / 60+ if minutes < 60:+ value, unit = minutes, "minute"+ elif minutes < 24 * 60:+ value, unit = minutes / 60, "hour"+ else:+ value, unit = minutes / (24 * 60), "day"+ rounded = round(value, 1)+ shown = str(int(rounded)) if rounded == int(rounded) else str(rounded)+ label = f"{shown} {unit}" if shown == "1" else f"{shown} {unit}s"+ # "about" whenever the duration is not a whole number of its unit, so the message never+ # reads as an exact figure the project does not actually use.+ return label if value == int(value) else f"about {label}"+++class _BackfillPermissionView(Protocol):+ action: str+ team_id: int+ kwargs: dict[str, str]+++class EvaluationBackfillAccessControlPermission(AccessControlPermission):+ """Authorize writes against the parent evaluation, not the `evaluation` resource as a whole.++ The generic resource check runs before the viewset can look at the parent, so a user who was+ granted editor on this one evaluation but is a viewer on the resource would be refused before+ the object-level grant is ever read. Same shape as `EvaluationReportAccessControlPermission`.+ """++ def has_permission(self, request: Request, view: APIView) -> bool:+ backfill_view = cast(_BackfillPermissionView, view)+ if backfill_view.action not in WRITE_ACTIONS:+ return super().has_permission(request, view)++ # The parent check runs for every credential, scoped tokens included. `APIScopePermission`+ # already enforced the token's scopes and `TeamMemberAccessPermission` its project+ # membership, so gating this on session auth only refused a personal API key held by a+ # user whom the resource check rejects but the object-level grant allows.+ try:+ evaluation_id = uuid.UUID(str(backfill_view.kwargs.get("parent_lookup_evaluation_id")))+ except (TypeError, ValueError):+ return False+ evaluation = Evaluation.objects.filter(team_id=backfill_view.team_id, id=evaluation_id).first()+ return evaluation is not None and self.has_object_permission(request, view, evaluation)++ def has_object_permission(self, request: Request, view: APIView, obj: object) -> bool:+ if not isinstance(obj, EvaluationBackfill | Evaluation):+ return False+ evaluation = obj.evaluation if isinstance(obj, EvaluationBackfill) else obj+ return super().has_object_permission(request, view, evaluation)+++class EvaluationBackfillRequestSerializer(serializers.Serializer):+ window_start = serializers.DateTimeField(help_text="Inclusive start of the window, by unit timestamp.")+ window_end = serializers.DateTimeField(+ help_text="Exclusive end of the window. Values in the future are clamped to now."+ )+ conditions = EvaluationConditionSerializer(+ many=True,+ required=False,+ help_text="Condition sets to match. Defaults to the evaluation's own condition sets.",+ )+ rerun_existing = serializers.BooleanField(+ default=False,+ help_text="Evaluate units again even when this evaluation already has a result for them.",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ # No span check here: the clamp bounds the window to the retention period, so a caller who+ # asks for a wider range gets it narrowed instead of rejected.+ if attrs["window_start"] >= attrs["window_end"]:+ raise ValidationError("The start of the range must be before the end.")+ return attrs+++class EvaluationBackfillEstimateSerializer(serializers.Serializer):+ total_units = serializers.IntegerField(help_text="Units that would be evaluated.")+ unit = serializers.ChoiceField(+ choices=EvaluationTarget.choices,+ help_text="What one unit is: a generation, a trace, or a session.",+ )+ window_start = serializers.DateTimeField(help_text="Window start after clamping.")+ window_end = serializers.DateTimeField(help_text="Window end after clamping.")+++class EvaluationBackfillConditionSerializer(serializers.Serializer):+ """One condition set as it was frozen onto the backfill: no id, no compiled bytecode."""++ properties = serializers.ListField(+ child=serializers.DictField(),+ required=False,+ default=list,+ help_text="Property filters (event or person) that scope which units match this condition set.",+ )+ rollout_percentage = serializers.FloatField(+ required=False,+ default=100,+ help_text="Percentage (0-100) of matching units sampled for this condition set.",+ )+++class EvaluationBackfillSerializer(serializers.ModelSerializer):+ created_by = UserBasicSerializer(read_only=True, allow_null=True, help_text="User who started the backfill.")+ target = serializers.ChoiceField(+ choices=EvaluationTarget.choices,+ read_only=True,+ help_text="What one unit is, frozen at creation: a generation, a trace, or a session.",+ )+ conditions = EvaluationBackfillConditionSerializer(+ many=True,+ read_only=True,+ help_text="Condition sets frozen at creation, so an edit to the evaluation does not change this run.",+ )++ class Meta:+ model = EvaluationBackfill+ fields = [+ "id",+ "status",+ "target",+ "window_start",+ "window_end",+ "conditions",+ "rerun_existing",+ "total_count",+ "dispatched_count",+ "skipped_count",+ "created_by",+ "created_at",+ "finished_at",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "id": {"help_text": "Backfill identifier."},+ "status": {"help_text": "running while the walk is dispatching, then completed or cancelled."},+ "window_start": {"help_text": "Inclusive start of the window, by unit timestamp."},+ "window_end": {"help_text": "Exclusive end of the window."},+ "rerun_existing": {"help_text": "Whether units with an existing result are evaluated again."},+ "total_count": {"help_text": "Units matched at creation; the ceiling on dispatched_count."},+ "dispatched_count": {"help_text": "Units the backfill has started an evaluation for so far."},+ "skipped_count": {"help_text": "Units the live path had already covered, so nothing was dispatched."},+ "created_at": {"help_text": "When the backfill was created."},+ "finished_at": {"help_text": "When the backfill reached a terminal status; null while it runs."},+ }+++class EvaluationBackfillViewSet(+ TeamAndOrgViewSetMixin,+ mixins.ListModelMixin,+ mixins.RetrieveModelMixin,+ viewsets.GenericViewSet,+):+ """Historical runs of one evaluation over a closed time window (nested under an evaluation)."""++ # The same flag as the tab, so the API and the surface reach a project together.+ posthog_feature_flag = "llm-analytics-eval-backfills"+ scope_object = "evaluation"+ scope_object_read_actions = ["list", "retrieve", "estimate"]+ scope_object_write_actions = WRITE_ACTIONS+ serializer_class = EvaluationBackfillSerializer+ # `objects` is fail-closed; `safely_get_queryset` re-scopes to the request team and evaluation.+ queryset = EvaluationBackfill.objects.unscoped()+ _evaluation_for_url_cache: Evaluation | None = None++ def dangerously_get_permissions(self) -> list[BasePermission]:+ return [+ IsAuthenticated(),+ APIScopePermission(),+ EvaluationBackfillAccessControlPermission(),+ TeamMemberAccessPermission(),+ PostHogFeatureFlagPermission(),+ ]++ def get_throttles(self) -> list[BaseThrottle]:+ # Append, never replace: returning only these throttles would drop the global burst and+ # sustained limits from the two actions that run a ClickHouse count.+ if self.action == "estimate":+ return [+ *super().get_throttles(),+ AIObservabilityBackfillEstimateThrottle(),+ AIObservabilityBackfillEstimateSustainedThrottle(),+ ]+ if self.action == "create":+ return [+ *super().get_throttles(),+ AIObservabilityBackfillCreateThrottle(),+ AIObservabilityBackfillCreateSustainedThrottle(),+ ]+ return super().get_throttles()++ def _evaluation_for_url(self) -> Evaluation:+ if self._evaluation_for_url_cache is not None:+ return self._evaluation_for_url_cache+ try:+ evaluation_id = uuid.UUID(self.kwargs["parent_lookup_evaluation_id"])+ except (KeyError, ValueError):+ raise NotFound()+ evaluation = Evaluation.objects.filter(team_id=self.team_id, pk=evaluation_id, deleted=False).first()+ if evaluation is None:+ raise NotFound()+ self.check_object_permissions(self.request, evaluation)+ self._evaluation_for_url_cache = evaluation+ return evaluation++ def safely_get_queryset(self, queryset: QuerySet[EvaluationBackfill]) -> QuerySet[EvaluationBackfill]:+ return (+ queryset.filter(team_id=self.team_id, evaluation=self._evaluation_for_url())+ .select_related("created_by")+ .order_by("-created_at")+ )++ def _validated_request(self, request: Request) -> dict[str, Any]:+ serializer = EvaluationBackfillRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ return cast(dict[str, Any], serializer.validated_data)++ 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()+ window_end: datetime = min(data["window_end"], now)+ 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 any+ # younger is still filling up. Grading it now would freeze a partial verdict, and the+ # shared workflow id would then keep the live path from ever grading it properly.+ window_end = min(window_end, now - settle_hold)+ if data["window_start"] >= window_end:+ raise ValidationError(+ f"This evaluation grades a {evaluation.target} over "+ f"{_duration_label(settle_hold - timedelta(seconds=INGESTION_LAG_MARGIN_SECONDS))}, so a "+ "backfill has to end before that. Try a range that ends earlier."+ )+ window_start: datetime = max(data["window_start"], now - timedelta(days=AI_EVENTS_RETENTION_DAYS))+ if window_start >= window_end:+ raise ValidationError(+ f"The range must end in the past and start within the last {AI_EVENTS_RETENTION_DAYS} days."+ )+ # A backfilled verdict is stamped at its unit's own timestamp, so ingestion applies the+ # team's drop threshold to it like any other late event. Reaching further back would run+ # the evaluations, pay for them, and have every verdict dropped before it lands.+ drop_events_older_than: timedelta | None = self.team.drop_events_older_than+ if drop_events_older_than:+ # The label rounds to the nearest hour, so anything shorter would render as "0 hours".+ # A reach that short is not worth backfilling either way.+ reach = drop_events_older_than - BACKFILL_RETENTION_MARGIN+ if reach < timedelta(hours=1):+ raise ValidationError(+ "Backfills are not available for this project because it drops events older than "+ f"{_duration_label(drop_events_older_than)}."+ )+ window_start = max(window_start, now - reach)+ if window_start >= window_end:+ raise ValidationError(+ f"Backfills on this project can only reach back {_duration_label(reach)}, "+ "because older events are dropped. Try a more recent range."+ )+ return BackfillWindow(start=window_start, end=window_end)++ def _require_enabled(self, evaluation: Evaluation) -> None:+ # The workflow cancels a backfill whose evaluation is disabled, so starting one here would+ # burn a ClickHouse count and a workflow for a run that stops on its first tick.+ if not evaluation.enabled:+ raise ValidationError("Enable the evaluation before backfilling it.")++ def _conditions(self, evaluation: Evaluation, data: dict[str, Any]) -> list[dict[str, Any]]:+ """The condition sets to freeze, reduced to what the walk reads.++ An empty list is refused rather than passed on: the candidate query treats no conditions+ as no filter and would match every generation in the window, while the live scheduler+ evaluates nothing at all for an evaluation with no condition sets.+ """+ submitted = data.get("conditions")+ source = submitted if submitted is not None else (evaluation.conditions or [])+ if not source:+ raise ValidationError("Add at least one condition set to this backfill.")+ conditions = [+ {+ "properties": condition.get("properties", []),+ "rollout_percentage": condition.get("rollout_percentage", 100),+ }+ for condition in source+ ]+ self._require_applicable_filters(evaluation, conditions)+ self._reject_restricted_properties(conditions)+ return conditions++ def _require_applicable_filters(self, evaluation: Evaluation, conditions: list[dict[str, Any]]) -> None:+ """Refuse a property filter the candidate query would compile away instead of apply.++ `property_to_expr` drops a filter it cannot read, such as a row that carries a key but no+ value yet, and the condition set then matches every unit in the window. On the live path+ that only mistimes some traffic. Here it would run and pay for an evaluation on every unit+ in the range, with the count in the estimate as the only signal. Strict mode raises for+ the filters it would otherwise drop, so the request is rejected instead.+ """+ for condition in conditions:+ try:+ property_to_expr(condition["properties"], self.team, strict=True)+ except (BaseHogQLError, ValueError, TypeError) as error:+ raise self._condition_rejected(evaluation, error)++ def _condition_rejected(self, evaluation: Evaluation, error: Exception) -> ValidationError:+ """A condition the query cannot apply is a bad request, not a server fault."""+ # The message is logged rather than returned, because it names query internals.+ logger.warning(+ "llma.evaluation_backfill_condition_rejected",+ evaluation_id=str(evaluation.id),+ error=str(error),+ )+ return ValidationError("A condition could not be applied. Check the filters and try again.")++ def _reject_restricted_properties(self, conditions: list[dict[str, Any]]) -> None:+ """Refuse a filter on a property this user cannot read.++ The count runs as the team, not as the caller, so a filter on a hidden property would+ answer how many units carry a given value. Names match across property classes, because+ a filter type that resolves to no class must not become a way past the check.+ """+ user = self.request.user if self.request.user.is_authenticated else None+ restricted = {+ name for name, _ in get_restricted_properties_for_team(user=cast(User | None, user), team=self.team)+ }+ if not restricted:+ return+ for condition in conditions:+ for property_filter in condition["properties"]:+ if property_filter.get("key") in restricted:+ raise ValidationError("A condition filters on a property you cannot access.")++ def _count(+ self,+ evaluation: Evaluation,+ conditions: list[dict[str, Any]],+ window_start: datetime,+ window_end: datetime,+ rerun_existing: bool,+ ) -> int:+ try:+ return count_backfill_candidates(+ team=self.team,+ evaluation_id=str(evaluation.id),+ target=evaluation.target,+ settle_horizon=settle_horizon(evaluation.target, evaluation.target_config),+ conditions=conditions,+ window_start=window_start,+ window_end=window_end,+ rerun_existing=rerun_existing,+ )+ except BaseHogQLError as error:+ raise self._condition_rejected(evaluation, error)++ @extend_schema(+ request=EvaluationBackfillRequestSerializer,+ responses={200: EvaluationBackfillEstimateSerializer},+ )+ @action(detail=False, methods=["post"], pagination_class=None)+ def estimate(self, request: Request, **kwargs: Any) -> Response:+ """Count what a backfill over the given window would evaluate, without creating one."""+ evaluation = self._evaluation_for_url()+ self._require_enabled(evaluation)+ data = self._validated_request(request)+ window = self._clamped_window(evaluation, data)+ conditions = self._conditions(evaluation, data)+ total = self._count(evaluation, conditions, window.start, window.end, data["rerun_existing"])+ response = EvaluationBackfillEstimateSerializer(+ {+ "total_units": total,+ "unit": evaluation.target,+ "window_start": window.start,+ "window_end": window.end,+ }+ )+ return Response(response.data)++ def _workflow_is_alive(self, backfill: EvaluationBackfill) -> bool:+ """Whether the row's workflow still runs, releasing the row when it does not.++ A failed workflow (an exhausted retry, a worker that never picked the run up) leaves the+ row at RUNNING, and the one-active-per-evaluation constraint then refuses every later+ backfill for that evaluation. Temporal is the authority on whether the run is really live.+ """+ if timezone.now() - backfill.created_at < BACKFILL_START_GRACE:+ return True+ cache_key = f"llma/evaluation_backfill_alive/{backfill.pk}"+ if cache.get(cache_key):+ return True+ workflow_id = backfill_workflow_id(str(backfill.pk))+ if self._probe_reads_alive(backfill, workflow_id):+ # One write for every alive answer, so an answer Temporal could not give costs the+ # same one probe per tick that a live answer does.+ cache.set(cache_key, True, BACKFILL_ALIVE_CACHE_SECONDS)+ return True++ # Says which read ended someone's backfill, because nothing else records it.+ logger.warning(+ "llma.evaluation_backfill_released",+ backfill_id=str(backfill.pk),+ team_id=self.team_id,+ workflow_id=workflow_id,+ )+ cancel_backfill(self.team_id, backfill.pk)+ return False++ def _probe_reads_alive(self, backfill: EvaluationBackfill, workflow_id: str) -> bool:+ """Ask Temporal whether the workflow runs, and read no answer at all as a yes."""+ try:+ client = sync_connect()+ description = asyncio.run(client.get_workflow_handle(workflow_id).describe())+ return description.status == WorkflowExecutionStatus.RUNNING+ except RPCError as error:+ # Treat an unreachable Temporal as "still running": refusing a second backfill is+ # recoverable, starting one against a live walk doubles every evaluation it runs. A+ # namespace that does not resolve answers NOT_FOUND for every workflow alike, so+ # reading that as "this run is gone" would cancel every backfill at once.+ if error.status != RPCStatusCode.NOT_FOUND or "namespace" in error.message.lower():+ logger.exception("llma.evaluation_backfill_describe_failed", backfill_id=str(backfill.pk))+ return True+ return False+ except Exception:+ logger.exception("llma.evaluation_backfill_describe_failed", backfill_id=str(backfill.pk))+ return True++ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ # The UI blocks Start while a row reads as running, so a dead workflow would hold the+ # evaluation shut until someone created another backfill. At most one row per evaluation+ # is active, so this costs one Temporal probe.+ active = self.get_queryset().filter(status__in=ACTIVE_BACKFILL_STATUSES).first()+ if active is not None:+ self._workflow_is_alive(active)+ return super().list(request, *args, **kwargs)++ @extend_schema(+ request=EvaluationBackfillRequestSerializer,+ responses={201: EvaluationBackfillSerializer},+ )+ def create(self, request: Request, **kwargs: Any) -> Response:+ """Create a backfill: freeze the conditions, count the units, start the walk."""+ evaluation = self._evaluation_for_url()+ self._require_enabled(evaluation)+ data = self._validated_request(request)+ window = self._clamped_window(evaluation, data)+ active = (+ EvaluationBackfill.objects.for_team(self.team_id)+ .filter(evaluation=evaluation, status__in=ACTIVE_BACKFILL_STATUSES)+ .first()+ )+ if active is not None and self._workflow_is_alive(active):+ raise ValidationError("This evaluation already has a running backfill.")++ conditions = self._conditions(evaluation, data)+ rerun_existing = data["rerun_existing"]+ total = self._count(evaluation, conditions, window.start, window.end, rerun_existing)+ if total == 0:+ raise ValidationError(f"No {evaluation.target}s in this range match these conditions. Try a wider range.")++ try:+ backfill = EvaluationBackfill.objects.for_team(self.team_id).create(+ evaluation=evaluation,+ team=self.team,+ window_start=window.start,+ window_end=window.end,+ target=evaluation.target,+ conditions=conditions,+ rerun_existing=rerun_existing,+ total_count=total,+ created_by=cast(User, request.user),+ )+ except IntegrityError:+ # Concurrent create lost the one-active-per-evaluation race.+ raise ValidationError("This evaluation already has a running backfill.")++ try:+ client = sync_connect()+ except Exception:+ # Connecting failed, so no start request reached Temporal and no workflow can exist for+ # this row. Removing it lets the user retry at once.+ EvaluationBackfill.objects.for_team(self.team_id).filter(pk=backfill.pk).delete()+ logger.exception("llma.evaluation_backfill_connect_failed", backfill_id=str(backfill.pk))+ raise APIException("Couldn't start the backfill. Try again.")++ try:+ asyncio.run(+ client.start_workflow(+ BACKFILL_WORKFLOW_NAME,+ EvaluationBackfillInputs(backfill_id=str(backfill.id), team_id=self.team_id),+ id=backfill_workflow_id(str(backfill.id)),+ task_queue=settings.LLMA_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ )+ )+ except Exception:+ # The call can fail after Temporal accepted the start, and the row is what controls the+ # walk: the first tick ends the run when the row is not active, and cancel needs it to+ # exist. Deleting it on an unknown outcome would leave a walk that dispatches judge runs+ # against the team's own provider key with nothing recording them and no way to stop+ # them. The row therefore stays, and `_workflow_is_alive` releases it on the next read+ # once the start grace has passed and Temporal answers NOT_FOUND for the workflow.+ logger.exception("llma.evaluation_backfill_start_failed", backfill_id=str(backfill.pk))+ raise APIException("Couldn't confirm the backfill started. Check the list before starting another one.")++ return Response(self.get_serializer(backfill).data, status=status.HTTP_201_CREATED)++ @extend_schema(request=None, responses={200: EvaluationBackfillSerializer})+ @action(detail=True, methods=["post"], pagination_class=None)+ def cancel(self, request: Request, **kwargs: Any) -> Response:+ """Stop a running backfill. Evaluations already dispatched still finish."""+ backfill = self.get_object()+ if cancel_backfill(self.team_id, backfill.pk):+ try:+ client = sync_connect()+ asyncio.run(client.get_workflow_handle(backfill_workflow_id(str(backfill.pk))).cancel())+ except Exception as error:+ # The workflow reads the row's status at every tick and stops on a terminal one, so+ # a failed handle costs nothing and does not need a stack trace.+ logger.warning("llma.evaluation_backfill_cancel_failed", backfill_id=str(backfill.pk), error=str(error))+ # The status and finished_at were written by the update, not on this instance.+ backfill.refresh_from_db()+ return Response(self.get_serializer(backfill).data)diff --git a/products/ai_observability/backend/api/test/test_evaluation_backfills.py b/products/ai_observability/backend/api/test/test_evaluation_backfills.pynew file mode 100644index 000000000000..2f98d880f2d8--- /dev/null+++ b/products/ai_observability/backend/api/test/test_evaluation_backfills.py@@ -0,0 +1,752 @@+from datetime import datetime, timedelta+from types import SimpleNamespace+from typing import cast++from posthog.test.base import APIBaseTest+from unittest.mock import AsyncMock, MagicMock, patch++from django.conf import settings+from django.core.cache import cache+from django.utils import timezone++from parameterized import parameterized+from rest_framework import status+from rest_framework.request import Request+from rest_framework.test import APIRequestFactory+from temporalio.client import WorkflowExecutionStatus+from temporalio.service import RPCError, RPCStatusCode++from posthog.constants import AvailableFeature+from posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Project, Team, User+from posthog.models.personal_api_key import hash_key_value+from posthog.models.utils import generate_random_token_personal+from posthog.rate_limit import (+ AIObservabilityBackfillCreateSustainedThrottle,+ AIObservabilityBackfillCreateThrottle,+ AIObservabilityBackfillEstimateSustainedThrottle,+ AIObservabilityBackfillEstimateThrottle,+)+from posthog.temporal.ai_observability.run_session_evaluation import AI_EVENTS_RETENTION_DAYS++from 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.models.evaluation_backfill import EvaluationBackfill, EvaluationBackfillStatus+from products.ai_observability.backend.models.evaluations import Evaluation++API_MODULE = "products.ai_observability.backend.api.evaluation_backfills"+++def _other_team() -> Team:+ org = Organization.objects.create(name="other")+ project = Project.objects.create(id=Team.objects.increment_id_sequence(), organization=org)+ return Team.objects.create(id=project.id, project=project, organization=org)+++def _evaluation(+ team: Team,+ conditions: list[dict] | None = None,+ *,+ target: str = "generation",+ target_config: dict | None = None,+) -> Evaluation:+ return Evaluation.objects.create(+ team=team,+ name="e",+ evaluation_type="hog",+ enabled=True,+ evaluation_config={"source": "return true"},+ output_type="boolean",+ output_config={},+ target=target,+ target_config=target_config or {},+ conditions=conditions+ if conditions is not None+ else [{"id": "c1", "properties": [], "rollout_percentage": 100}],+ )+++def _body(**overrides) -> dict:+ now = timezone.now()+ return {+ "window_start": (now - timedelta(days=7)).isoformat(),+ "window_end": now.isoformat(),+ **overrides,+ }+++def _throttle_request(user: User, personal_api_key: str | None = None) -> Request:+ headers = {"HTTP_AUTHORIZATION": f"Bearer {personal_api_key}"} if personal_api_key else {}+ # ty resolves the DRF Request constructor to its wrapped HttpRequest type; the cast restores it.+ request = cast(Request, Request(APIRequestFactory().post("/", **headers)))+ # Resolve the authenticator first. DRF resets `user` to anonymous when it finds none, which+ # would discard a user assigned before that.+ assert request.successful_authenticator is None+ request.user = user+ return request+++def _temporal_client(+ workflow_status: WorkflowExecutionStatus | None = WorkflowExecutionStatus.RUNNING,+ describe_error: Exception | None = None,+) -> MagicMock:+ client = MagicMock()+ client.start_workflow = AsyncMock()+ handle = MagicMock(+ cancel=AsyncMock(),+ describe=AsyncMock(return_value=MagicMock(status=workflow_status), side_effect=describe_error),+ )+ client.get_workflow_handle = MagicMock(return_value=handle)+ return client+++def _workflow_not_found() -> RPCError:+ return RPCError("workflow not found", RPCStatusCode.NOT_FOUND, b"")+++def _enable_backfills_flag(test: APIBaseTest) -> None:+ """Turn the rollout flag on for one test, the way a project that opted in sees the API."""+ flag = patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)+ flag.start()+ test.addCleanup(flag.stop)+++class TestEvaluationBackfillsApi(APIBaseTest):+ def setUp(self):+ super().setUp()+ _enable_backfills_flag(self)+ self.evaluation = _evaluation(self.team, [{"id": "c1", "properties": [], "rollout_percentage": 50}])+ self.url = f"/api/projects/{self.team.id}/evaluations/{self.evaluation.id}/backfills"++ def _running_backfill(+ self, evaluation: Evaluation | None = None, *, age: timedelta | None = None+ ) -> EvaluationBackfill:+ now = timezone.now()+ evaluation = evaluation or self.evaluation+ backfill = EvaluationBackfill.objects.unscoped().create(+ evaluation=evaluation,+ team=evaluation.team,+ window_start=now - timedelta(days=1),+ window_end=now,+ target="generation",+ conditions=[],+ total_count=1,+ )+ if age is not None:+ # created_at is auto_now_add, so ageing the row past BACKFILL_START_GRACE takes an update.+ EvaluationBackfill.objects.unscoped().filter(pk=backfill.pk).update(created_at=now - age)+ backfill.refresh_from_db()+ return backfill++ def _stale_backfill(self, evaluation: Evaluation | None = None) -> EvaluationBackfill:+ return self._running_backfill(evaluation, age=BACKFILL_START_GRACE + timedelta(minutes=1))++ # Guards the wiring and the bucket, not the rate: the team-wide throttle has to reach+ # `get_throttles()`, and a second member of the project has to land in the same bucket, or the+ # count these actions run scales with the number of members and keys again.+ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=5)+ @patch("posthog.rate_limit.AIObservabilityBackfillEstimateSustainedThrottle.rate", new="1/hour")+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_estimate_is_rate_limited_across_the_project(self, _enabled, _count):+ cache.clear()+ assert self.client.post(f"{self.url}/estimate/", _body(), format="json").status_code == status.HTTP_200_OK++ second_member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self.client.force_login(second_member)++ throttled = self.client.post(f"{self.url}/estimate/", _body(), format="json")+ assert throttled.status_code == status.HTTP_429_TOO_MANY_REQUESTS, throttled.json()++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=42)+ def test_estimate_counts_without_creating_a_row(self, _count):+ response = self.client.post(f"{self.url}/estimate/", _body(), format="json")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["total_units"] == 42+ assert response.json()["unit"] == "generation"+ assert EvaluationBackfill.objects.unscoped().count() == 0++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=42)+ @patch(f"{API_MODULE}.sync_connect")+ def test_create_freezes_conditions_and_starts_workflow(self, connect, _count):+ connect.return_value = _temporal_client()++ response = self.client.post(f"{self.url}/", _body(), format="json")++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ body = response.json()+ assert body["total_count"] == 42+ assert body["status"] == EvaluationBackfillStatus.RUNNING+ assert body["conditions"] == [{"properties": [], "rollout_percentage": 50}]+ assert body["rerun_existing"] is False++ row = EvaluationBackfill.objects.unscoped().get(pk=body["id"])+ assert row.team_id == self.team.id+ assert row.target == "generation"++ call = connect.return_value.start_workflow.call_args+ assert call.args[0] == "llma-evaluation-backfill"+ assert call.args[1].backfill_id == str(row.id)+ assert call.args[1].team_id == self.team.id+ assert call.kwargs["id"] == f"llma-evaluation-backfill-{row.id}"+ assert call.kwargs["task_queue"] == settings.LLMA_TASK_QUEUE++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=7)+ @patch(f"{API_MODULE}.sync_connect")+ def test_create_uses_submitted_conditions_and_rerun_flag(self, connect, _count):+ connect.return_value = _temporal_client()+ conditions = [+ {"id": "sent", "properties": [{"key": "x", "value": "y", "type": "event"}], "rollout_percentage": 10}+ ]++ response = self.client.post(f"{self.url}/", _body(conditions=conditions, rerun_existing=True), format="json")++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ body = response.json()+ assert body["rerun_existing"] is True+ assert body["conditions"] == [+ {"properties": [{"key": "x", "value": "y", "type": "event"}], "rollout_percentage": 10}+ ]++ @parameterized.expand(+ [+ ("workflow_running", WorkflowExecutionStatus.RUNNING, None),+ # A concurrent create that has not reached start_workflow yet leaves nothing to+ # describe, and its row must survive the probe rather than be treated as stale.+ ("workflow_not_started_yet", None, None),+ ("workflow_unknown_to_temporal", None, _workflow_not_found()),+ ]+ )+ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=7)+ @patch(f"{API_MODULE}.sync_connect")+ def test_create_rejects_a_second_backfill_while_a_recent_row_is_active(+ self, _case, workflow_status, describe_error, connect, _count+ ):+ connect.return_value = _temporal_client(workflow_status, describe_error)+ active = self._running_backfill()++ response = self.client.post(f"{self.url}/", _body(), format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "already has a running backfill" in response.json()["detail"]+ active.refresh_from_db()+ assert active.status == EvaluationBackfillStatus.RUNNING++ @parameterized.expand(+ [+ ("workflow_completed", WorkflowExecutionStatus.COMPLETED, None),+ ("workflow_failed", WorkflowExecutionStatus.FAILED, None),+ ("workflow_gone", None, None),+ ("workflow_unknown_to_temporal", None, _workflow_not_found()),+ ]+ )+ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=7)+ @patch(f"{API_MODULE}.sync_connect")+ def test_create_releases_an_old_row_whose_workflow_is_no_longer_running(+ self, _case, workflow_status, describe_error, connect, _count+ ):+ connect.return_value = _temporal_client(workflow_status, describe_error)+ stale = self._stale_backfill()++ response = self.client.post(f"{self.url}/", _body(), format="json")++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ stale.refresh_from_db()+ assert stale.status == EvaluationBackfillStatus.CANCELLED+ assert stale.finished_at is not None++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=7)+ @patch(f"{API_MODULE}.sync_connect")+ def test_create_refuses_when_an_old_rows_workflow_still_runs(self, connect, _count):+ connect.return_value = _temporal_client(WorkflowExecutionStatus.RUNNING)+ active = self._stale_backfill()++ response = self.client.post(f"{self.url}/", _body(), format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert "already has a running backfill" in response.json()["detail"]+ active.refresh_from_db()+ assert active.status == EvaluationBackfillStatus.RUNNING++ @parameterized.expand(+ [+ ("temporal_answers_running", None, None),+ # The answers Temporal cannot give are the expensive ones, and the list still returns+ # 200 for them, so the tab keeps polling at its floor and only the cache holds the rate.+ ("temporal_cannot_be_reached", RuntimeError("temporal down"), None),+ ("describe_fails", None, RPCError("unavailable", RPCStatusCode.UNAVAILABLE, b"")),+ ]+ )+ @patch(f"{API_MODULE}.sync_connect")+ def test_an_alive_answer_is_reused_instead_of_probing_temporal_again(+ self, _case, connect_error, describe_error, connect+ ):+ if connect_error is not None:+ connect.side_effect = connect_error+ else:+ connect.return_value = _temporal_client(describe_error=describe_error)+ stale = self._stale_backfill()++ for _ in range(3):+ assert self.client.get(f"{self.url}/").status_code == status.HTTP_200_OK++ assert connect.call_count == 1+ stale.refresh_from_db()+ assert stale.status == EvaluationBackfillStatus.RUNNING++ @patch(f"{API_MODULE}.sync_connect")+ def test_list_releases_an_old_row_whose_workflow_is_gone(self, connect):+ connect.return_value = _temporal_client(None)+ stale = self._stale_backfill()++ response = self.client.get(f"{self.url}/")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["results"][0]["status"] == EvaluationBackfillStatus.CANCELLED+ stale.refresh_from_db()+ assert stale.status == EvaluationBackfillStatus.CANCELLED++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=7)+ @patch(f"{API_MODULE}.sync_connect", side_effect=RuntimeError("temporal down"))+ def test_create_keeps_refusing_when_temporal_cannot_be_reached(self, _connect, _count):+ stale = self._stale_backfill()++ response = self.client.post(f"{self.url}/", _body(), format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "already has a running backfill" in response.json()["detail"]+ stale.refresh_from_db()+ assert stale.status == EvaluationBackfillStatus.RUNNING++ @parameterized.expand(["start_after_end", "entirely_in_future"])+ def test_create_rejects_bad_windows(self, case):+ now = timezone.now()+ windows = {+ "start_after_end": (now, now - timedelta(days=1)),+ "entirely_in_future": (now + timedelta(days=1), now + timedelta(days=2)),+ }+ window_start, window_end = windows[case]++ response = self.client.post(+ f"{self.url}/",+ {"window_start": window_start.isoformat(), "window_end": window_end.isoformat()},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert EvaluationBackfill.objects.unscoped().count() == 0++ @parameterized.expand(["evaluation_has_no_conditions", "explicit_empty_list"])+ def test_rejects_a_backfill_with_no_condition_sets(self, case):+ body = _body()+ if case == "evaluation_has_no_conditions":+ self.evaluation.conditions = []+ self.evaluation.save()+ else:+ body["conditions"] = []++ for path in (f"{self.url}/", f"{self.url}/estimate/"):+ response = self.client.post(path, body, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST, (path, response.json())+ assert "at least one condition set" in response.json()["detail"]+ assert EvaluationBackfill.objects.unscoped().count() == 0++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=3)+ @patch(f"{API_MODULE}.sync_connect")+ def test_clamps_a_window_wider_than_retention(self, connect, _count):+ connect.return_value = _temporal_client()+ now = timezone.now()+ body = _body(+ window_start=(now - timedelta(days=90)).isoformat(),+ window_end=(now + timedelta(days=1)).isoformat(),+ )++ estimate = self.client.post(f"{self.url}/estimate/", body, format="json")+ assert estimate.status_code == status.HTTP_200_OK, estimate.json()+ assert abs(datetime.fromisoformat(estimate.json()["window_end"]) - now) < 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)++ created = self.client.post(f"{self.url}/", body, format="json")+ assert created.status_code == status.HTTP_201_CREATED, created.json()+ row = EvaluationBackfill.objects.unscoped().get(pk=created.json()["id"])+ assert abs(row.window_end - now) < timedelta(seconds=5)+ assert abs(row.window_start - expected_start) < timedelta(seconds=5)++ @parameterized.expand(+ [+ ("a trace settles over its fixed window", "trace", {"strategy": "fixed_window", "window_seconds": 1800}),+ (+ "a session settles no later than its max age",+ "session",+ {"strategy": "inactivity", "quiet_period_seconds": 3600, "max_age_seconds": 7200},+ ),+ ]+ )+ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=3)+ @patch(f"{API_MODULE}.sync_connect")+ def test_holds_the_window_back_from_units_the_live_path_is_still_grading(+ self, _case, target, target_config, connect, _count+ ):+ connect.return_value = _temporal_client()+ evaluation = _evaluation(self.team, target=target, target_config=target_config)+ url = f"/api/projects/{self.team.id}/evaluations/{evaluation.id}/backfills"+ now = timezone.now()+ hold = timedelta(seconds=target_config.get("max_age_seconds") or target_config["window_seconds"])++ estimate = self.client.post(f"{url}/estimate/", _body(), format="json")+ assert estimate.status_code == status.HTTP_200_OK, estimate.json()+ window_end = datetime.fromisoformat(estimate.json()["window_end"])+ assert abs(window_end - (now - hold)) < timedelta(seconds=30)++ # A range that ends inside the hold has nothing the live path has finished with.+ too_recent = _body(window_start=(now - hold / 2).isoformat())+ refused = self.client.post(f"{url}/", too_recent, format="json")+ assert refused.status_code == status.HTTP_400_BAD_REQUEST, refused.json()+ assert "has to end before that" in refused.json()["detail"]+ assert EvaluationBackfill.objects.unscoped().count() == 0++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=3)+ @patch(f"{API_MODULE}.sync_connect")+ def test_a_generation_backfill_reaches_up_to_now(self, connect, _count):+ connect.return_value = _temporal_client()+ now = timezone.now()++ estimate = self.client.post(f"{self.url}/estimate/", _body(), format="json")++ assert estimate.status_code == status.HTTP_200_OK, estimate.json()+ assert abs(datetime.fromisoformat(estimate.json()["window_end"]) - now) < timedelta(seconds=30)++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=3)+ @patch(f"{API_MODULE}.sync_connect")+ def test_clamps_the_window_to_the_projects_drop_threshold(self, connect, _count):+ connect.return_value = _temporal_client()+ self.team.drop_events_older_than = timedelta(days=3)+ self.team.save()+ now = timezone.now()+ body = _body(window_start=(now - timedelta(days=20)).isoformat())++ created = self.client.post(f"{self.url}/", body, format="json")++ assert created.status_code == status.HTTP_201_CREATED, created.json()+ row = EvaluationBackfill.objects.unscoped().get(pk=created.json()["id"])+ # The margin buys the walk time to reach the oldest units before their verdicts age out.+ expected = now - timedelta(days=3) + BACKFILL_RETENTION_MARGIN+ assert abs(row.window_start - expected) < timedelta(seconds=5)++ @parameterized.expand(+ [+ # Past the margin the message has to quote the reach, which is the threshold minus it.+ (+ "days",+ timedelta(days=3),+ "Backfills on this project can only reach back 2 days, because older events are dropped. "+ "Try a more recent range.",+ ),+ (+ "fractional_days",+ timedelta(days=1, hours=12),+ "Backfills on this project can only reach back 12 hours, because older events are dropped. "+ "Try a more recent range.",+ ),+ # The margin alone leaves no window at all, so the project cannot backfill anything.+ (+ "threshold_at_the_margin",+ timedelta(days=1),+ "Backfills are not available for this project because it drops events older than 1 day.",+ ),+ # A reach under an hour would render as "about 0 hours", so it is refused instead.+ (+ "reach_under_an_hour",+ timedelta(days=1, minutes=30),+ "Backfills are not available for this project because it drops events older than about 1 day.",+ ),+ (+ "threshold_under_the_margin",+ timedelta(hours=6),+ "Backfills are not available for this project because it drops events older than 6 hours.",+ ),+ ]+ )+ def test_rejects_a_window_entirely_older_than_the_drop_threshold(self, _case, threshold, expected_detail):+ self.team.drop_events_older_than = threshold+ self.team.save()+ now = timezone.now()+ body = _body(+ window_start=(now - timedelta(days=10)).isoformat(),+ window_end=(now - timedelta(days=9)).isoformat(),+ )++ response = self.client.post(f"{self.url}/", body, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["detail"] == expected_detail+ assert EvaluationBackfill.objects.unscoped().count() == 0++ @parameterized.expand(+ [+ ("hogql_that_does_not_parse", {"type": "hogql", "key": "not ! valid"}),+ # Outside strict mode these two compile to a constant true instead of a filter, which+ # would run the backfill over every unit in the window rather than the ones asked for.+ ("filter_row_left_without_a_value", {"type": "event", "key": "$ai_model", "operator": "exact"}),+ ("filter_of_a_type_that_does_not_exist", {"type": "nonsense", "key": "x", "value": "y"}),+ ]+ )+ def test_a_condition_the_query_cannot_apply_is_a_bad_request(self, _case, property_filter):+ body = _body(conditions=[{"id": "c1", "properties": [property_filter], "rollout_percentage": 100}])++ for path in (f"{self.url}/", f"{self.url}/estimate/"):+ response = self.client.post(path, body, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, (path, response.json())+ assert response.json()["detail"] == "A condition could not be applied. Check the filters and try again."+ assert EvaluationBackfill.objects.unscoped().count() == 0++ @parameterized.expand(["create", "estimate"])+ def test_a_disabled_evaluation_cannot_be_backfilled(self, case):+ self.evaluation.enabled = False+ self.evaluation.save()+ path = f"{self.url}/" if case == "create" else f"{self.url}/estimate/"++ response = self.client.post(path, _body(), format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["detail"] == "Enable the evaluation before backfilling it."+ assert EvaluationBackfill.objects.unscoped().count() == 0++ @parameterized.expand(["list", "estimate"])+ def test_another_teams_evaluation_is_not_addressable(self, case):+ other_evaluation = _evaluation(_other_team())+ url = f"/api/projects/{self.team.id}/evaluations/{other_evaluation.id}/backfills"++ if case == "list":+ response = self.client.get(f"{url}/")+ else:+ response = self.client.post(f"{url}/estimate/", _body(), format="json")++ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=0)+ def test_create_rejects_empty_window(self, _count):+ response = self.client.post(f"{self.url}/", _body(), format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "No generations in this range" in response.json()["detail"]+ assert EvaluationBackfill.objects.unscoped().count() == 0++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=5)+ @patch(f"{API_MODULE}.sync_connect", side_effect=RuntimeError("temporal down"))+ def test_create_rolls_back_row_when_temporal_is_unreachable(self, _connect, _count):+ response = self.client.post(f"{self.url}/", _body(), format="json")++ assert response.status_code >= 500+ assert EvaluationBackfill.objects.unscoped().count() == 0++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=5)+ @patch(f"{API_MODULE}.sync_connect")+ def test_create_keeps_the_row_when_the_start_result_is_unknown(self, connect, _count):+ connect.return_value = _temporal_client()+ connect.return_value.start_workflow.side_effect = RuntimeError("stream closed")++ response = self.client.post(f"{self.url}/", _body(), format="json")++ assert response.status_code >= 500+ row = EvaluationBackfill.objects.unscoped().get()+ assert row.status == EvaluationBackfillStatus.RUNNING++ @patch(f"{API_MODULE}.sync_connect")+ def test_cancel_marks_terminal_and_is_idempotent(self, connect):+ connect.return_value = _temporal_client()+ backfill = self._running_backfill()++ first = self.client.post(f"{self.url}/{backfill.id}/cancel/", format="json")+ assert first.status_code == status.HTTP_200_OK, first.json()+ assert first.json()["status"] == EvaluationBackfillStatus.CANCELLED+ assert first.json()["finished_at"] is not None+ connect.return_value.get_workflow_handle.assert_called_once_with(f"llma-evaluation-backfill-{backfill.id}")+ connect.return_value.get_workflow_handle.return_value.cancel.assert_awaited_once()++ second = self.client.post(f"{self.url}/{backfill.id}/cancel/", format="json")+ assert second.status_code == status.HTTP_200_OK+ assert second.json()["status"] == EvaluationBackfillStatus.CANCELLED+ assert second.json()["finished_at"] == first.json()["finished_at"]++ @parameterized.expand(+ [+ ("list", "get", "/", None),+ (+ "estimate",+ "post",+ "/estimate/",+ {"window_start": "2024-01-01T00:00:00Z", "window_end": "2024-01-02T00:00:00Z"},+ ),+ ("create", "post", "/", {"window_start": "2024-01-01T00:00:00Z", "window_end": "2024-01-02T00:00:00Z"}),+ ]+ )+ def test_every_action_is_off_while_the_flag_is_off(self, _case, method, path, payload):+ with patch("posthog.permissions.posthog_feature_flag_enabled", return_value=False):+ response = getattr(self.client, method)(f"{self.url}{path}", payload, format="json")++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()+ assert EvaluationBackfill.objects.unscoped().count() == 0++ def test_list_is_scoped_to_evaluation_and_team(self):+ mine = self._running_backfill()+ self._running_backfill(_evaluation(_other_team()))++ response = self.client.get(f"{self.url}/")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert [row["id"] for row in response.json()["results"]] == [str(mine.id)]+++class TestEvaluationBackfillsAccessControl(APIBaseTest):+ def setUp(self):+ super().setUp()+ _enable_backfills_flag(self)+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ self.evaluation = _evaluation(self.team)+ self.url = f"/api/projects/{self.team.id}/evaluations/{self.evaluation.id}/backfills"+ self.viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self.viewer_membership = OrganizationMembership.objects.get(user=self.viewer, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="evaluation",+ resource_id=None,+ access_level="viewer",+ organization_member=self.viewer_membership,+ )+ self.client.force_login(self.viewer)++ def _grant_editor_on_this_evaluation(self) -> None:+ AccessControl.objects.create(+ team=self.team,+ resource="evaluation",+ resource_id=str(self.evaluation.id),+ access_level="editor",+ organization_member=self.viewer_membership,+ )++ def _authenticate_viewer_with_api_key(self, scopes: list[str]) -> None:+ key_value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="backfill key", user=self.viewer, secure_value=hash_key_value(key_value), scopes=scopes+ )+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key_value}")++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=4)+ def test_viewer_can_estimate_but_cannot_create(self, _count):+ body = _body()++ estimate = self.client.post(f"{self.url}/estimate/", body, format="json")+ assert estimate.status_code == status.HTTP_200_OK, estimate.json()+ assert estimate.json()["total_units"] == 4++ created = self.client.post(f"{self.url}/", body, format="json")+ assert created.status_code == status.HTTP_403_FORBIDDEN, created.json()+ assert EvaluationBackfill.objects.unscoped().count() == 0++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=4)+ @patch(f"{API_MODULE}.sync_connect")+ def test_editor_on_this_evaluation_can_create_despite_being_a_viewer_on_the_resource(self, connect, _count):+ connect.return_value = _temporal_client()+ self._grant_editor_on_this_evaluation()++ created = self.client.post(f"{self.url}/", _body(), format="json")++ assert created.status_code == status.HTTP_201_CREATED, created.json()+ assert EvaluationBackfill.objects.unscoped().count() == 1++ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=4)+ @patch(f"{API_MODULE}.sync_connect")+ def test_a_personal_api_key_reaches_the_same_per_evaluation_grant_as_a_session(self, connect, _count):+ connect.return_value = _temporal_client()+ self._grant_editor_on_this_evaluation()+ self._authenticate_viewer_with_api_key(["evaluation:write"])++ created = self.client.post(f"{self.url}/", _body(), format="json")++ assert created.status_code == status.HTTP_201_CREATED, created.json()+ assert EvaluationBackfill.objects.unscoped().count() == 1++ @parameterized.expand(+ [+ ("without_the_grant", False, ["evaluation:write"]),+ ("read_scope_only", True, ["evaluation:read"]),+ ]+ )+ def test_a_personal_api_key_is_still_refused_without_write_access(self, _case, grant_editor, scopes):+ if grant_editor:+ self._grant_editor_on_this_evaluation()+ self._authenticate_viewer_with_api_key(scopes)++ created = self.client.post(f"{self.url}/", _body(), format="json")++ assert created.status_code == status.HTTP_403_FORBIDDEN, created.json()+ assert EvaluationBackfill.objects.unscoped().count() == 0+++class TestBackfillThrottleBuckets(APIBaseTest):+ @parameterized.expand(+ [+ ("estimate", AIObservabilityBackfillEstimateThrottle),+ ("create", AIObservabilityBackfillCreateThrottle),+ ]+ )+ def test_two_users_on_one_project_do_not_share_a_bucket(self, _case, throttle_class):+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ view = SimpleNamespace(team_id=self.team.id)+ throttle = throttle_class()++ keys = [throttle.get_cache_key(_throttle_request(user), view) for user in (self.user, other_user, self.user)]++ assert keys[0] != keys[1]+ assert keys[0] == keys[2]++ @parameterized.expand(+ [+ ("estimate", AIObservabilityBackfillEstimateThrottle),+ ("create", AIObservabilityBackfillCreateThrottle),+ ]+ )+ def test_each_personal_api_key_gets_its_own_bucket(self, _case, throttle_class):+ view = SimpleNamespace(team_id=self.team.id)+ throttle = throttle_class()+ first_key, second_key = (self._personal_api_key(f"key-{index}") for index in (1, 2))++ session = throttle.get_cache_key(_throttle_request(self.user), view)+ first = throttle.get_cache_key(_throttle_request(self.user, personal_api_key=first_key), view)+ second = throttle.get_cache_key(_throttle_request(self.user, personal_api_key=second_key), view)++ assert len({session, first, second}) == 3++ @parameterized.expand(+ [+ ("estimate", AIObservabilityBackfillEstimateSustainedThrottle),+ ("create", AIObservabilityBackfillCreateSustainedThrottle),+ ]+ )+ def test_the_sustained_bucket_is_one_per_project(self, _case, throttle_class):+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ view = SimpleNamespace(team_id=self.team.id)+ throttle = throttle_class()+ key = self._personal_api_key("key-sustained")++ keys = {+ throttle.get_cache_key(_throttle_request(self.user), view),+ throttle.get_cache_key(_throttle_request(other_user), view),+ throttle.get_cache_key(_throttle_request(self.user, personal_api_key=key), view),+ }++ assert len(keys) == 1++ def _personal_api_key(self, label: str) -> str:+ key_value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label=label, user=self.user, secure_value=hash_key_value(key_value), scopes=["evaluation:write"]+ )+ return key_valuediff --git a/products/ai_observability/backend/routes.py b/products/ai_observability/backend/routes.pyindex c1082648ab7c..b4b57fa67f76 100644--- a/products/ai_observability/backend/routes.py+++ b/products/ai_observability/backend/routes.py@@ -13,6 +13,7 @@ from products.ai_observability.backend.api import (ClusteringJobViewSet,DatasetItemViewSet,DatasetViewSet,+ EvaluationBackfillViewSet,EvaluationConfigViewSet,EvaluationDirectoryViewSet,EvaluationReportViewSet,@@ -56,7 +57,15 @@ def register_routes(routers: RouterRegistry) -> None:)routers.projects.register(r"datasets", DatasetViewSet, "project_datasets", ["team_id"])routers.projects.register(r"dataset_items", DatasetItemViewSet, "project_dataset_items", ["team_id"])- routers.projects.register(r"evaluations", EvaluationViewSet, "project_evaluations", ["team_id"])+ project_evaluations_router = routers.projects.register(+ r"evaluations", EvaluationViewSet, "project_evaluations", ["team_id"]+ )+ project_evaluations_router.register(+ r"backfills",+ EvaluationBackfillViewSet,+ "project_evaluation_backfills",+ ["team_id", "evaluation_id"],+ )routers.projects.register(r"evaluation_directories",EvaluationDirectoryViewSet,diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsxindex 74f35a089f9f..19d045ebc8e6 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx@@ -20,10 +20,12 @@ import {import { AccessControlAction } from 'lib/components/AccessControlAction'import { DurationPicker } from 'lib/components/DurationPicker/DurationPicker'import { NotFound } from 'lib/components/NotFound'+import { TZLabel } from 'lib/components/TZLabel'import { FEATURE_FLAGS } from 'lib/constants'import { LemonField } from 'lib/lemon-ui/LemonField'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { pluralize } from 'lib/utils/strings'import { SceneExport } from 'scenes/sceneTypes'import { SceneBreadcrumbBackButton } from '~/layout/scenes/components/SceneBreadcrumbs'@@ -37,6 +39,7 @@ import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'import { getModelPickerFooterLink, ModelPicker } from '../ModelPicker'import { modelPickerLogic } from '../modelPickerLogic'import { providerKeyStateIssueDescription, providerLabel } from '../settings/providerKeyStateUtils'+import { EvaluationBackfillsTab } from './components/EvaluationBackfillsTab'import { EvaluationCodeEditor } from './components/EvaluationCodeEditor'import { EvaluationPromptEditor } from './components/EvaluationPromptEditor'import { EvaluationReportConfig } from './components/EvaluationReportConfig'@@ -62,11 +65,14 @@ import {DEFAULT_TRACE_QUIET_PERIOD_SECONDS,DEFAULT_TRACE_WINDOW_SECONDS,LLMEvaluationLogicProps,+ hasUnsetConditionRollout,llmEvaluationLogic,} from './llmEvaluationLogic'import { statusReasonLabel, statusReasonRecoveryLabel } from './statusDisplay'import { EvaluationSettleStrategy, EvaluationTarget, EvaluationType } from './types'+const RUNS_BACKFILL_TIME_FORMAT = { formatDate: 'MMM D, YYYY', formatTime: 'HH:mm' }+export function AIObservabilityEvaluation(): JSX.Element {const {evaluation,@@ -77,6 +83,8 @@ export function AIObservabilityEvaluation(): JSX.Element {formValid,isNewEvaluation,runsSummary,+ runsBackfillId,+ runsBackfill,evaluationProviderKeyIssue,activeTab,canEnable,@@ -86,6 +94,7 @@ export function AIObservabilityEvaluation(): JSX.Element {const { searchParams } = useValues(router)const { featureFlags } = useValues(featureFlagLogic)const settlingStrategyEnabled = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVAL_SETTLING_STRATEGY]+ const backfillsEnabled = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVAL_BACKFILLS]const {setEvaluationName,setEvaluationDescription,@@ -198,11 +207,15 @@ export function AIObservabilityEvaluation(): JSX.Element {const hasSelectedJudgeModel = !modelSelectionRequired || Boolean(evaluation.model_configuration?.model.trim())const hasName = evaluation.name.length > 0const basicFieldsValid = hasName && configValid- const percentageUnset = evaluation.conditions.some((c) => (c.rollout_percentage ?? 0) === 0)+ const percentageUnset = hasUnsetConditionRollout(evaluation.conditions)const percentageOutOfRange = evaluation.conditions.some((c) => (c.rollout_percentage ?? 0) > 100 || (c.rollout_percentage ?? 0) < 0)const hasConditions = evaluation.conditions.length > 0+ // The save writes the evaluation configuration and then returns to the evaluations list. Runs+ // edits nothing, and Backfills holds a setup this save does not carry, plus its own Start+ // button, so leaving the page from either tab only does what the user did not ask for.+ const showSaveAction = activeTab !== 'runs' && activeTab !== 'backfills'const saveButtonDisabledReason = !hasName? 'Add a name for this evaluation': !configValid@@ -326,7 +339,7 @@ export function AIObservabilityEvaluation(): JSX.Element {<LemonButton type="secondary" icon={<IconArrowLeft />} onClick={handleCancel}>{hasUnsavedChanges ? 'Cancel' : 'Back'}</LemonButton>- {activeTab !== 'runs' && (+ {showSaveAction && (<AccessControlActionresourceType={AccessControlResourceType.Evaluation}minAccessLevel={AccessControlLevel.Editor}@@ -402,6 +415,7 @@ export function AIObservabilityEvaluation(): JSX.Element {</>)}</p>+{isReportableEvaluation && (<EvaluationReportsCalloutevaluationId={evaluation.id}@@ -439,10 +453,51 @@ export function AIObservabilityEvaluation(): JSX.Element {<div className="text-muted">Errors</div></div></div>- <div className="text-muted text-xs">Across all runs, all time</div>+ <div className="text-muted text-xs">+ {runsBackfillId ? 'From this backfill' : 'Across all runs, all time'}+ </div></div>)}</div>+ {runsBackfillId && (+ <LemonBanner+ type="info"+ className="mb-4"+ action={{+ children: 'Show all runs',+ onClick: () =>+ router.actions.push(+ router.values.location.pathname,+ { ...router.values.searchParams, backfill_id: undefined },+ router.values.hashParams+ ),+ }}+ >+ <span className="font-semibold">Showing runs from one backfill.</span>+ {runsBackfill && (+ <>+ {' '}+ It covered {pluralize(+ runsBackfill.total_count,+ runsBackfill.target+ )}{' '}+ between{' '}+ <TZLabel+ time={runsBackfill.window_start}+ timestampStyle="absolute"+ {...RUNS_BACKFILL_TIME_FORMAT}+ />+ {' and '}+ <TZLabel+ time={runsBackfill.window_end}+ timestampStyle="absolute"+ {...RUNS_BACKFILL_TIME_FORMAT}+ />+ .+ </>+ )}+ </LemonBanner>+ )}<EvaluationRunsTable /></div>),@@ -460,6 +515,19 @@ export function AIObservabilityEvaluation(): JSX.Element {/>),},+ !isNewEvaluation &&+ backfillsEnabled && {+ key: 'backfills',+ label: 'Backfills',+ 'data-attr': 'llma-evaluation-backfills-tab',+ content: (+ <EvaluationBackfillsTab+ evaluationId={evaluation.id}+ userAccessLevel={evaluation.user_access_level ?? undefined}+ onConfigurationClick={() => setActiveTab('configuration')}+ />+ ),+ },{key: 'configuration',label: 'Configuration',@@ -776,9 +844,40 @@ export function AIObservabilityEvaluation(): JSX.Element {<div ref={triggersRef} className="bg-bg-light border rounded p-6"><h3 className="text-lg font-semibold mb-4">Triggers</h3><p className="text-muted text-sm mb-4">- Configure when this evaluation should run on your LLM generations.+ The evaluation runs on generations that match any one of these condition+ sets. Within a set, all filters must match, and sampling decides how many of+ the matching generations get evaluated.+ {evaluation.target === 'trace' && (+ <>+ {' '}+ Conditions match individual generations. The whole trace is+ evaluated once any of its generations matches, and sampling applies+ per trace.+ </>+ )}</p><EvaluationTriggers />+ <div className="bg-bg-light border rounded p-3 text-sm mt-6">+ <h4 className="font-semibold mb-2">Examples:</h4>+ <ul className="space-y-1 text-muted list-disc list-inside">+ <li>+ <strong>10% of all generations:</strong> Set 10% sampling with no+ filter conditions+ </li>+ <li>+ <strong>5% of GPT-4 generations:</strong> Set 5% sampling with+ $ai_model = "gpt-4o"+ </li>+ <li>+ <strong>Exclude internal users:</strong> Set 100% sampling with+ person property is_internal ≠ true+ </li>+ <li>+ <strong>High-cost generations:</strong> Set 100% sampling with+ $ai_total_cost_usd > 0.01+ </li>+ </ul>+ </div></div>{/* Scheduled Reports (inline config for new evaluations) */}diff --git a/products/ai_observability/frontend/evaluations/backfillConditions.test.ts b/products/ai_observability/frontend/evaluations/backfillConditions.test.tsnew file mode 100644index 000000000000..ee6604f4cb0f--- /dev/null+++ b/products/ai_observability/frontend/evaluations/backfillConditions.test.ts@@ -0,0 +1,26 @@+import { dayjs } from 'lib/dayjs'++import { backfillRangeDateFormat, backfillSamplingLabel } from './backfillConditions'++describe('backfillConditions', () => {+ it.each([+ [undefined, '100% sampled'],+ [100, '100% sampled'],+ [50, '50% sampled'],+ [0.5, '0.5% sampled'],+ [0.04, '0.04% sampled'],+ [63.75, '63.8% sampled'],+ [99.95, '99.9% sampled'],+ [99.999, '99.9% sampled'],+ ])('renders rollout %s as %s', (rolloutPercentage: number | undefined, expected: string) => {+ expect(backfillSamplingLabel({ rollout_percentage: rolloutPercentage })).toBe(expected)+ })++ it.each([+ ['both bounds in the current year', '2026-08-31T00:00:00Z', '2026-09-07T00:00:00Z', 'MMM D'],+ ['a range crossing into the current year', '2025-12-28T00:00:00Z', '2026-01-03T00:00:00Z', 'MMM D, YYYY'],+ ['both bounds in a past year', '2025-03-01T00:00:00Z', '2025-03-08T00:00:00Z', 'MMM D, YYYY'],+ ])('formats %s', (_name: string, start: string, end: string, expected: string) => {+ expect(backfillRangeDateFormat(start, end, dayjs('2026-09-07T12:00:00Z'))).toBe(expected)+ })+})diff --git a/products/ai_observability/frontend/evaluations/backfillConditions.ts b/products/ai_observability/frontend/evaluations/backfillConditions.tsnew file mode 100644index 000000000000..12c6c47dfdd9--- /dev/null+++ b/products/ai_observability/frontend/evaluations/backfillConditions.ts@@ -0,0 +1,20 @@+import { dayjs } from 'lib/dayjs'++import type { EvaluationBackfillConditionApi } from '../generated/api.schemas'++export function backfillSamplingLabel(condition: EvaluationBackfillConditionApi): string {+ const percent = condition.rollout_percentage ?? 100+ // A rollout under 1% is still a real sample, so one decimal is not enough to tell 0.04 from 0.+ const decimals = percent < 1 ? 2 : percent < 100 ? 1 : 0+ const factor = 10 ** decimals+ // A partial sample that rounds up to 100 would read as "every unit", so hold it below.+ const shown = percent < 100 ? Math.min(Math.round(percent * factor), 100 * factor - 1) / factor : percent+ return `${parseFloat(shown.toFixed(decimals))}% sampled`+}++/** The year is noise while a range sits inside the current year, and load-bearing as soon as+ * either bound leaves it. Both bounds share one format so the range reads as one span. */+export function backfillRangeDateFormat(start: string, end: string, now: dayjs.Dayjs): string {+ const sameYear = dayjs(start).isSame(now, 'year') && dayjs(end).isSame(now, 'year')+ return sameYear ? 'MMM D' : 'MMM D, YYYY'+}diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsxnew file mode 100644index 000000000000..98c41eb12f5b--- /dev/null+++ b/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx@@ -0,0 +1,504 @@+import { useActions, useValues } from 'kea'+import { combineUrl, router } from 'kea-router'++import { LemonBanner, LemonButton, LemonSwitch, LemonTable, LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'++import { AccessControlAction } from 'lib/components/AccessControlAction'+import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'+import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'+import { TZLabel } from 'lib/components/TZLabel'+import { dayjs } from 'lib/dayjs'+import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { Link } from 'lib/lemon-ui/Link'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { pluralize } from 'lib/utils/strings'++import {+ AccessControlLevel,+ AccessControlResourceType,+ AnyPropertyFilter,+ DateMappingOption,+ UserBasicType,+} from '~/types'++import type {+ EvaluationBackfillApi,+ EvaluationBackfillConditionApi,+ EvaluationBackfillStatusEnumApi,+} from '../../generated/api.schemas'+import { backfillRangeDateFormat, backfillSamplingLabel } from '../backfillConditions'+import { evaluationBackfillsLogic } from '../evaluationBackfillsLogic'+import { EvaluationTriggers } from './EvaluationTriggers'++const BACKFILL_DATE_OPTIONS: DateMappingOption[] = [+ { key: CUSTOM_OPTION_KEY, values: [] },+ { key: 'Last 24 hours', values: ['-24h'] },+ { key: 'Last 7 days', values: ['-7d'] },+ { key: 'Last 14 days', values: ['-14d'] },+ { key: 'Last 30 days', values: ['-30d'] },+]++const BACKFILL_STATUS_TAG: Record<EvaluationBackfillStatusEnumApi, { label: string; type: LemonTagType }> = {+ running: { label: 'Running', type: 'primary' },+ completed: { label: 'Completed', type: 'success' },+ cancelled: { label: 'Cancelled', type: 'muted' },+}++const WINDOW_TIME_FORMAT = { formatDate: 'MMM D, YYYY', formatTime: 'HH:mm' }++function backfillUnitPlural(backfill: EvaluationBackfillApi): string {+ return pluralize(2, backfill.target, undefined, false)+}++function ConditionSetScope({+ condition,+ unitPlural,+}: {+ condition: EvaluationBackfillConditionApi+ unitPlural: string+}): JSX.Element {+ // The generated type carries property filters as plain dicts, while the display components take+ // the filter union. The two agree at runtime, mirroring the cast in `toRequestConditions`.+ const filters = (condition.properties ?? []) as AnyPropertyFilter[]+ return filters.length > 0 ? (+ <PropertyFiltersDisplay filters={filters} compact />+ ) : (+ <span className="whitespace-nowrap">All {unitPlural}</span>+ )+}++interface EvaluationBackfillsTabProps {+ evaluationId: string+ userAccessLevel?: AccessControlLevel+ onConfigurationClick: () => void+}++export function EvaluationBackfillsTab({+ evaluationId,+ userAccessLevel,+ onConfigurationClick,+}: EvaluationBackfillsTabProps): JSX.Element {+ const logic = evaluationBackfillsLogic({ evaluationId })+ const {+ backfills,+ backfillsError,+ backfillsLoading,+ clampedWindow,+ conditions,+ creatingBackfill,+ estimate,+ estimateError,+ estimateLoading,+ expandedBackfillIds,+ rerunExisting,+ settleWait,+ startDisabledReason,+ transitioningIds,+ unit,+ windowDateFrom,+ windowDateTo,+ } = useValues(logic)+ const {+ setWindowRange,+ setConditions,+ setRerunExisting,+ createBackfill,+ cancelBackfill,+ expandBackfill,+ collapseBackfill,+ loadBackfills,+ } = useActions(logic)++ const confirmStart = (): void => {+ LemonDialog.open({+ title: 'Start this backfill?',+ description: estimate ? (+ <>+ {pluralize(estimate.total_units, estimate.unit)}+ {clampedWindow ? ` between ${clampedWindow.start} and ${clampedWindow.end}` : ''} will be evaluated,+ and each one is billed as an AI observability event. You can cancel a run while it is in progress,+ but results it already saved will stay.+ </>+ ) : undefined,+ primaryButton: {+ children: 'Start backfill',+ onClick: createBackfill,+ 'data-attr': 'llma-eval-backfill-start-confirm',+ },+ secondaryButton: { children: 'Cancel' },+ // The overlay aligns modals to the top by default, as in WebAnalyticsFilterPresets.+ overlayClassName: '!items-center',+ })+ }++ const unitPlural = pluralize(2, unit, undefined, false)++ const columns: LemonTableColumns<EvaluationBackfillApi> = [+ {+ title: 'Range',+ key: 'window',+ // `timestampStyle="absolute"` suppresses the Today/Yesterday substitution, so two rows+ // can be compared as exact instants. TZLabel's timezone popover still holds the time of day.+ render: (_, backfill) => {+ const formatDate = backfillRangeDateFormat(backfill.window_start, backfill.window_end, dayjs())+ return (+ <div className="flex items-center gap-1 flex-wrap">+ <TZLabel+ time={backfill.window_start}+ timestampStyle="absolute"+ formatDate={formatDate}+ formatTime=""+ />+ <span className="text-muted">–</span>+ <TZLabel+ time={backfill.window_end}+ timestampStyle="absolute"+ formatDate={formatDate}+ formatTime=""+ />+ </div>+ )+ },+ },+ {+ title: 'Status',+ key: 'status',+ render: (_, backfill) => {+ const statusTag = (+ <LemonTag type={BACKFILL_STATUS_TAG[backfill.status].type}>+ {BACKFILL_STATUS_TAG[backfill.status].label}+ </LemonTag>+ )+ return (+ <div className="flex items-center gap-1 flex-wrap">+ {/* A completed row means every unit was sent out, not that every evaluation has finished. */}+ {backfill.status === 'completed' ? (+ <Tooltip+ title={`Each ${backfill.target} is evaluated on its own, so the last results can take a few minutes to appear in the Runs tab.`}+ >+ {statusTag}+ </Tooltip>+ ) : (+ statusTag+ )}+ </div>+ )+ },+ },+ {+ title: 'Scope',+ key: 'conditions',+ render: (_, backfill) => {+ // The Scope cell shows one condition set and folds the rest behind a "+N more".+ const [first, ...rest] = backfill.conditions+ if (!first) {+ return <span className="text-secondary">-</span>+ }+ const rowUnitPlural = backfillUnitPlural(backfill)+ return (+ <div className="flex items-center gap-1 flex-wrap">+ <ConditionSetScope condition={first} unitPlural={rowUnitPlural} />+ {rest.length > 0 && (+ <Tooltip+ title={+ <div className="flex flex-col gap-1">+ {/* Frozen condition sets carry no id and never reorder. */}+ {rest.map((condition, index) => (+ <div key={index} className="flex items-center gap-1 flex-wrap">+ <ConditionSetScope condition={condition} unitPlural={rowUnitPlural} />+ {(condition.rollout_percentage ?? 100) < 100 && (+ <span>{backfillSamplingLabel(condition)}</span>+ )}+ </div>+ ))}+ </div>+ }+ >+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={() => expandBackfill(backfill.id)}+ data-attr="llma-eval-backfill-more-conditions"+ >+ +{rest.length} more+ </LemonButton>+ </Tooltip>+ )}+ {(first.rollout_percentage ?? 100) < 100 && (+ <LemonTag type="muted" size="small">+ {backfillSamplingLabel(first)}+ </LemonTag>+ )}+ {backfill.rerun_existing && (+ <LemonTag type="muted" size="small">+ Includes {rowUnitPlural} with a result+ </LemonTag>+ )}+ </div>+ )+ },+ },+ {+ title: 'Started',+ key: 'progress',+ render: (_, backfill) => {+ // The walk has handled a unit once it started it, or skipped it because the live+ // path had covered it already. A rerun over a window that keeps growing can hand+ // back more than the total it started from, so the bar stops at that total.+ const handled = Math.min(backfill.dispatched_count + backfill.skipped_count, backfill.total_count)+ return (+ <Tooltip title="How many units this backfill has started evaluating. It does not track which of them have finished.">+ <div className="min-w-24">+ <span className="whitespace-nowrap" translate="no">+ {backfill.dispatched_count.toLocaleString('en-US')} /{' '}+ {backfill.total_count.toLocaleString('en-US')}+ </span>+ {backfill.skipped_count > 0 && (+ <span className="text-muted whitespace-nowrap">+ {' '}+ · {backfill.skipped_count.toLocaleString('en-US')} skipped+ </span>+ )}+ <LemonProgress+ className="mt-1"+ percent={backfill.total_count > 0 ? (handled / backfill.total_count) * 100 : 0}+ strokeColor={backfill.status === 'running' ? undefined : 'var(--border)'}+ />+ </div>+ </Tooltip>+ )+ },+ },+ {+ title: 'Created',+ key: 'created_at',+ render: (_, backfill) => <TZLabel time={backfill.created_at} />,+ },+ {+ title: 'Created by',+ key: 'created_by',+ render: (_, backfill) =>+ backfill.created_by ? (+ <ProfilePicture user={backfill.created_by as UserBasicType} size="md" showName />+ ) : (+ <span className="text-secondary">-</span>+ ),+ },+ {+ key: 'actions',+ width: 0,+ render: (_, backfill) =>+ backfill.status === 'running' ? (+ <More+ data-attr="llma-eval-backfill-actions"+ overlay={+ <AccessControlAction+ resourceType={AccessControlResourceType.Evaluation}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={userAccessLevel}+ >+ <LemonButton+ fullWidth+ status="danger"+ onClick={() => cancelBackfill(backfill.id)}+ disabledReason={transitioningIds.includes(backfill.id) ? 'Cancelling…' : undefined}+ data-attr="llma-eval-backfill-cancel"+ >+ Cancel+ </LemonButton>+ </AccessControlAction>+ }+ />+ ) : null,+ },+ ]++ return (+ <div className="flex flex-col gap-4 max-w-6xl">+ <div className="rounded border p-4 flex flex-col gap-3">+ <div>+ <h3 className="mb-1">Evaluate past {unitPlural}</h3>+ <p className="text-muted mb-0">Run this evaluation over a past time range.</p>+ </div>++ {settleWait && (+ <p className="text-muted mb-0">+ This evaluation waits {settleWait} before it evaluates a {unit}, so a backfill can only cover+ what is older than that.{' '}+ <Link onClick={onConfigurationClick} data-attr="llma-eval-backfill-settle-configuration">+ Change the wait+ </Link>+ </p>+ )}++ <div className="flex items-center gap-2 flex-wrap">+ <DateFilter+ size="small"+ dateFrom={windowDateFrom}+ dateTo={windowDateTo}+ dateOptions={BACKFILL_DATE_OPTIONS}+ onChange={(dateFrom, dateTo) => setWindowRange(dateFrom, dateTo)}+ allowTimePrecision+ allowFixedRangeWithTime+ />+ <LemonSwitch+ bordered+ checked={rerunExisting}+ onChange={setRerunExisting}+ label={`Include ${unitPlural} that already have a result`}+ data-attr="llma-eval-backfill-rerun"+ />+ </div>++ <LemonCollapse+ panels={[+ {+ key: 'conditions',+ header: 'Conditions',+ dataAttr: 'llma-eval-backfill-conditions',+ content: (+ <EvaluationTriggers conditions={conditions} onChange={setConditions} unit={unit} />+ ),+ },+ ]}+ />++ <div className="flex items-center justify-between gap-2 flex-wrap">+ <span className={estimateError ? 'text-danger' : 'text-muted'}>+ {estimateLoading+ ? 'Counting…'+ : estimateError+ ? estimateError+ : estimate+ ? `${pluralize(estimate.total_units, estimate.unit)} would be evaluated${+ clampedWindow ? ` between ${clampedWindow.start} and ${clampedWindow.end}` : ''+ }`+ : null}+ </span>+ <AccessControlAction+ resourceType={AccessControlResourceType.Evaluation}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={userAccessLevel}+ >+ <LemonButton+ type="primary"+ onClick={confirmStart}+ loading={creatingBackfill}+ disabledReason={startDisabledReason}+ data-attr="llma-eval-backfill-start"+ >+ Start backfill+ </LemonButton>+ </AccessControlAction>+ </div>+ </div>++ {/* The table's own empty state carries this error when there is nothing to list, so the+ banner covers the rows-on-screen case: a failing poll leaves stale progress with+ the table still drawn, and without this the user reads a live run as stalled. */}+ {backfillsError && backfills.length > 0 && (+ <LemonBanner+ type="error"+ action={{+ children: 'Retry',+ onClick: () => loadBackfills(),+ loading: backfillsLoading,+ 'data-attr': 'llma-eval-backfill-retry',+ }}+ >+ {backfillsError}+ </LemonBanner>+ )}++ <LemonTable+ dataSource={backfills}+ columns={columns}+ loading={backfillsLoading}+ rowKey="id"+ expandable={{+ // -1 leaves a row on LemonTable's own toggle state, so only a "+N more" click forces one open.+ isRowExpanded: (backfill) => (expandedBackfillIds.includes(backfill.id) ? 1 : -1),+ onRowExpand: (backfill) => expandBackfill(backfill.id),+ onRowCollapse: (backfill) => collapseBackfill(backfill.id),+ expandedRowRender: (backfill) => (+ <div className="flex items-center justify-between gap-4 px-2 py-3">+ <div className="flex flex-col gap-2 min-w-0">+ {backfill.conditions.map((condition, index) => (+ <div key={index} className="flex items-center gap-1 flex-wrap">+ <ConditionSetScope+ condition={condition}+ unitPlural={backfillUnitPlural(backfill)}+ />+ <span className="text-muted whitespace-nowrap">+ {backfillSamplingLabel(condition)}+ </span>+ </div>+ ))}+ <div className="flex items-center gap-2 flex-wrap text-muted">+ <span className="flex items-center gap-1">+ <TZLabel+ time={backfill.window_start}+ timestampStyle="absolute"+ {...WINDOW_TIME_FORMAT}+ />+ <span>→</span>+ <TZLabel+ time={backfill.window_end}+ timestampStyle="absolute"+ {...WINDOW_TIME_FORMAT}+ />+ </span>+ <span>·</span>+ <span>+ {backfill.dispatched_count.toLocaleString('en-US')} started,{' '}+ {backfill.skipped_count.toLocaleString('en-US')} skipped, out of{' '}+ {pluralize(backfill.total_count, backfill.target)} in range+ {backfill.rerun_existing &&+ `, including ${backfillUnitPlural(backfill)} that already had a result`}+ </span>+ </div>+ </div>+ <LemonButton+ size="xsmall"+ type="secondary"+ to={+ combineUrl(router.values.location.pathname, {+ ...router.values.searchParams,+ evaluation_tab: 'runs',+ backfill_id: backfill.id,+ }).url+ }+ data-attr="llma-eval-backfill-view-results"+ >+ View results from this run+ </LemonButton>+ </div>+ ),+ }}+ emptyState={+ backfillsError ? (+ <div className="flex items-center justify-center gap-2 flex-wrap">+ <span className="text-danger">{backfillsError}</span>+ <LemonButton+ size="small"+ type="secondary"+ onClick={() => loadBackfills()}+ data-attr="llma-eval-backfill-retry"+ >+ Retry+ </LemonButton>+ </div>+ ) : (+ `No backfills yet. Pick a range above to evaluate past ${unitPlural}.`+ )+ }+ data-attr="llma-eval-backfill-table"+ />+ </div>+ )+}diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsxindex 15c22d488993..aceb37055236 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsx@@ -6,11 +6,21 @@ import { LemonButton, LemonInput } from '@posthog/lemon-ui'import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { LemonSlider } from 'lib/lemon-ui/LemonSlider'+import { pluralize } from 'lib/utils/strings'import { llmEvaluationLogic } from '../llmEvaluationLogic'-import { EvaluationConditionSet } from '../types'+import { EvaluationConditionSet, EvaluationTarget } from '../types'++interface EvaluationTriggersProps {+ conditions?: EvaluationConditionSet[]+ onChange?: (conditions: EvaluationConditionSet[]) => void+ /** The unit the sampling percentage applies to. The configuration editor describes the+ * evaluation's own target, so it leaves this unset. The backfill editor passes the unit the+ * server counted, which is still the saved target after an unsaved target edit. */+ unit?: EvaluationTarget+}-export function EvaluationTriggers(): JSX.Element {+export function EvaluationTriggers({ conditions, onChange, unit }: EvaluationTriggersProps = {}): JSX.Element {const { evaluation } = useValues(llmEvaluationLogic)const { setTriggerConditions } = useActions(llmEvaluationLogic)@@ -18,59 +28,50 @@ export function EvaluationTriggers(): JSX.Element {return <div>Loading...</div>}+ const current = conditions ?? evaluation.conditions+ const update = onChange ?? setTriggerConditions+const addConditionSet = (): void => {const newCondition: EvaluationConditionSet = {id: `cond-${Date.now()}`,rollout_percentage: 100,properties: [],}- setTriggerConditions([...evaluation.conditions, newCondition])+ update([...current, newCondition])}const updateConditionSet = (index: number, updates: Partial<EvaluationConditionSet>): void => {- const updatedConditions = evaluation.conditions.map((condition, i) =>+ const updatedConditions = current.map((condition, i) =>i === index ? { ...condition, ...updates } : condition)- setTriggerConditions(updatedConditions)+ update(updatedConditions)}const removeConditionSet = (index: number): void => {- if (evaluation.conditions.length === 1) {+ if (current.length === 1) {// Keep at least one condition setreturn}- const updatedConditions = evaluation.conditions.filter((_, i) => i !== index)- setTriggerConditions(updatedConditions)+ const updatedConditions = current.filter((_, i) => i !== index)+ update(updatedConditions)}const duplicateConditionSet = (index: number): void => {- const conditionToDuplicate = evaluation.conditions[index]+ const conditionToDuplicate = current[index]const duplicatedCondition: EvaluationConditionSet = {...conditionToDuplicate,id: `cond-${Date.now()}`,}- const updatedConditions = [...evaluation.conditions]+ const updatedConditions = [...current]updatedConditions.splice(index + 1, 0, duplicatedCondition)- setTriggerConditions(updatedConditions)+ update(updatedConditions)}- const isTraceTarget = evaluation.target === 'trace'+ const unitPlural = pluralize(2, unit ?? evaluation.target, undefined, false)return (<div className="space-y-6">- <div className="text-sm text-muted">- Each condition set below defines when this evaluation should trigger. If multiple condition sets exist,- the evaluation will trigger if ANY of them match (OR logic).- {isTraceTarget && (- <>- {' '}- Conditions match individual generations — the whole trace is evaluated once any of its- generations matches, and sampling applies per trace.- </>- )}- </div>-- {evaluation.conditions.map((condition, index) => {+ {current.map((condition, index) => {const percentageValue = condition.rollout_percentage || 0return (@@ -79,7 +80,7 @@ export function EvaluationTriggers(): JSX.Element {<div className="flex justify-between items-center"><div className="flex items-center gap-2"><h4 className="font-semibold">Condition set {index + 1}</h4>- {evaluation.conditions.length > 1 && (+ {current.length > 1 && (<div className="text-sm text-muted">{index === 0 ? 'IF' : 'OR IF'}</div>)}</div>@@ -91,7 +92,7 @@ export function EvaluationTriggers(): JSX.Element {onClick={() => duplicateConditionSet(index)}tooltip="Duplicate condition set"/>- {evaluation.conditions.length > 1 && (+ {current.length > 1 && (<LemonButtonicon={<IconTrash />}size="small"@@ -141,8 +142,7 @@ export function EvaluationTriggers(): JSX.Element {</div>) : (<div className="text-xs text-muted">- This evaluation will run on {percentageValue.toFixed(2)}% of matching{' '}- {isTraceTarget ? 'traces' : 'generations'}+ This evaluation will run on {percentageValue.toFixed(2)}% of matching {unitPlural}</div>)}</div>@@ -179,26 +179,6 @@ export function EvaluationTriggers(): JSX.Element {Add Condition Set</LemonButton></div>-- {/* Help Section */}- <div className="bg-bg-light border rounded p-3 text-sm">- <h4 className="font-semibold mb-2">Examples:</h4>- <ul className="space-y-1 text-muted list-disc list-inside">- <li>- <strong>10% of all generations:</strong> Set 10% sampling with no filter conditions- </li>- <li>- <strong>5% of GPT-4 generations:</strong> Set 5% sampling with $ai_model_name = "gpt-4"- </li>- <li>- <strong>Exclude internal users:</strong> Set 100% sampling with person property is_internal ≠- true- </li>- <li>- <strong>High-cost generations:</strong> Set 100% sampling with $ai_total_cost_usd > 0.01- </li>- </ul>- </div></div>)}diff --git a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.tsnew file mode 100644index 000000000000..79bd90146afa--- /dev/null+++ b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts@@ -0,0 +1,560 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { ApiError } from 'lib/api'+import { dayjs } from 'lib/dayjs'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import {+ evaluationsBackfillsCancelCreate,+ evaluationsBackfillsCreate,+ evaluationsBackfillsEstimateCreate,+ evaluationsBackfillsList,+} from '../generated/api'+import type { EvaluationBackfillApi, EvaluationBackfillEstimateApi } from '../generated/api.schemas'+import { evaluationBackfillsLogic } from './evaluationBackfillsLogic'+import { llmEvaluationLogic } from './llmEvaluationLogic'+import type { EvaluationConfig } from './types'++jest.mock('../generated/api', () => ({+ ...jest.requireActual('../generated/api'),+ evaluationsBackfillsList: jest.fn(),+ evaluationsBackfillsCreate: jest.fn(),+ evaluationsBackfillsEstimateCreate: jest.fn(),+ evaluationsBackfillsCancelCreate: jest.fn(),+}))++const listMock = jest.mocked(evaluationsBackfillsList)+const createMock = jest.mocked(evaluationsBackfillsCreate)+const estimateMock = jest.mocked(evaluationsBackfillsEstimateCreate)+const cancelMock = jest.mocked(evaluationsBackfillsCancelCreate)++const EVALUATION_ID = 'eval-123'+// Mirrors ESTIMATE_DEBOUNCE_MS in the logic.+const ESTIMATE_DEBOUNCE_MS = 500+const WINDOW_LABEL = { start: 'Feb 1, 2024', end: 'Feb 8, 2024' }++const mockEvaluation = {+ id: EVALUATION_ID,+ name: 'Test Evaluation',+ description: '',+ directory_id: null,+ enabled: true,+ status: 'active',+ status_reason: null,+ status_reason_detail: null,+ evaluation_type: 'llm_judge',+ evaluation_config: { prompt: 'Is it helpful?' },+ output_type: 'boolean',+ output_config: {},+ conditions: [+ {+ id: 'cond-1',+ rollout_percentage: 50,+ properties: [{ key: '$ai_model', value: 'gpt-5', operator: 'exact', type: 'event' }],+ // The stored condition carries compiled state the backfill API does not accept.+ bytecode: ['_H', 1],+ },+ ],+ target: 'generation',+ target_config: {},+ model_configuration: null,+ total_runs: 0,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+}++function backfill(overrides: Partial<EvaluationBackfillApi> = {}): EvaluationBackfillApi {+ return {+ id: 'backfill-1',+ status: 'completed',+ target: 'generation',+ window_start: '2024-01-01T00:00:00Z',+ window_end: '2024-01-02T00:00:00Z',+ conditions: [{ properties: [], rollout_percentage: 100 }],+ rerun_existing: false,+ total_count: 10,+ dispatched_count: 8,+ skipped_count: 2,+ created_by: null,+ created_at: '2024-01-02T00:00:00Z',+ finished_at: '2024-01-02T01:00:00Z',+ ...overrides,+ }+}++function estimate(overrides: Partial<EvaluationBackfillEstimateApi> = {}): EvaluationBackfillEstimateApi {+ return {+ total_units: 42,+ unit: 'generation',+ window_start: '2024-01-01T00:00:00Z',+ window_end: '2024-01-08T00:00:00Z',+ ...overrides,+ }+}++describe('evaluationBackfillsLogic', () => {+ let logic: ReturnType<typeof evaluationBackfillsLogic.build>+ let toastError: jest.SpyInstance++ beforeEach(() => {+ toastError = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')+ useMocks({+ get: {+ '/api/environments/:teamId/llm_analytics/provider_keys/': { results: [] },+ '/api/environments/:teamId/llm_analytics/evaluation_config/': {+ active_provider_key: null,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ },+ '/api/projects/:teamId/evaluations/:id/': mockEvaluation,+ },+ })+ initKeaTests()+ listMock.mockReset().mockResolvedValue({ count: 0, results: [] })+ createMock.mockReset().mockResolvedValue(backfill({ status: 'running' }))+ estimateMock.mockReset().mockResolvedValue(estimate())+ cancelMock.mockReset().mockResolvedValue(backfill({ status: 'cancelled' }))+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ function mountLogic(): ReturnType<typeof evaluationBackfillsLogic.build> {+ logic = evaluationBackfillsLogic({ evaluationId: EVALUATION_ID })+ logic.mount()+ return logic+ }++ /** The header Save button lives outside the tab, so a save arrives from the evaluation logic. */+ function saveEvaluation(overrides: Partial<EvaluationConfig>): void {+ llmEvaluationLogic({ evaluationId: EVALUATION_ID }).actions.saveEvaluationSuccess({+ ...mockEvaluation,+ ...overrides,+ } as unknown as EvaluationConfig)+ }++ /** The tab opens on a default range and counts it once, so most cases start from that count. */+ async function mountAndSettle(): Promise<void> {+ mountLogic()+ await expectLogic(logic).toDispatchActions(['loadBackfillsSuccess', 'requestEstimateSuccess'])+ estimateMock.mockClear()+ }++ it('seeds conditions from the evaluation, strips keys the backfill API rejects, then counts the default range', async () => {+ const seededConditions = [+ {+ id: 'cond-1',+ rollout_percentage: 50,+ properties: [{ key: '$ai_model', value: 'gpt-5', operator: 'exact', type: 'event' }],+ },+ ]+ mountLogic()++ await expectLogic(logic).toDispatchActions(['requestEstimateSuccess']).toMatchValues({+ conditions: seededConditions,+ windowDateFrom: '-7d',+ windowDateTo: null,+ })++ // One count, and it uses the seeded conditions rather than the empty list held before load.+ expect(estimateMock).toHaveBeenCalledTimes(1)+ expect(estimateMock.mock.calls[0][2]).toEqual({+ window_start: dayjs().tz('UTC').startOf('day').subtract(7, 'day').toISOString(),+ window_end: expect.any(String),+ conditions: seededConditions,+ rerun_existing: false,+ })+ })++ it('debounces estimate requests and drops a stale response', async () => {+ jest.useFakeTimers()+ try {+ mountLogic()+ await jest.advanceTimersByTimeAsync(ESTIMATE_DEBOUNCE_MS)+ await expectLogic(logic).toDispatchActions(['loadBackfillsSuccess', 'requestEstimateSuccess'])+ estimateMock.mockClear()++ // Two changes inside the debounce window make one request, for the range picked last.+ logic.actions.setWindowRange('-30d', null)+ await jest.advanceTimersByTimeAsync(ESTIMATE_DEBOUNCE_MS - 100)+ logic.actions.setWindowRange('-7d', null)+ await jest.advanceTimersByTimeAsync(ESTIMATE_DEBOUNCE_MS)+ await expectLogic(logic).toDispatchActions(['requestEstimateSuccess'])+ expect(estimateMock).toHaveBeenCalledTimes(1)++ // A response that arrives after a newer request started must not land.+ let resolveStale: (value: EvaluationBackfillEstimateApi) => void = () => {}+ estimateMock.mockReturnValueOnce(+ new Promise<EvaluationBackfillEstimateApi>((resolve) => {+ resolveStale = resolve+ })+ )+ estimateMock.mockResolvedValueOnce(estimate({ total_units: 7 }))++ logic.actions.setWindowRange('-14d', null)+ await jest.advanceTimersByTimeAsync(ESTIMATE_DEBOUNCE_MS)+ logic.actions.setWindowRange('-24h', null)+ await jest.advanceTimersByTimeAsync(ESTIMATE_DEBOUNCE_MS)+ await expectLogic(logic).toDispatchActions(['requestEstimateSuccess'])++ resolveStale(estimate({ total_units: 999 }))+ await jest.advanceTimersByTimeAsync(0)++ await expectLogic(logic).toMatchValues({ estimate: expect.objectContaining({ total_units: 7 }) })+ } finally {+ jest.useRealTimers()+ }+ })++ it('reuses the count it has when an edit leaves the request unchanged', async () => {+ jest.useFakeTimers()+ try {+ mountLogic()+ await jest.advanceTimersByTimeAsync(ESTIMATE_DEBOUNCE_MS)+ await expectLogic(logic).toDispatchActions(['requestEstimateSuccess'])++ // A fixed range keeps the request body identical from one trigger to the next.+ logic.actions.setWindowRange('2024-01-01', '2024-01-08')+ await jest.advanceTimersByTimeAsync(ESTIMATE_DEBOUNCE_MS)+ await expectLogic(logic).toDispatchActions(['requestEstimateSuccess'])+ estimateMock.mockClear()++ logic.actions.setWindowRange('2024-01-01', '2024-01-08')+ await jest.advanceTimersByTimeAsync(ESTIMATE_DEBOUNCE_MS)+ await expectLogic(logic).toDispatchActions(['requestEstimateSuccess'])+ expect(estimateMock).not.toHaveBeenCalled()++ // An edited condition is a different request, so it is counted again.+ logic.actions.setConditions([{ id: 'cond-1', rollout_percentage: 25, properties: [] }])+ await jest.advanceTimersByTimeAsync(ESTIMATE_DEBOUNCE_MS)+ await expectLogic(logic).toDispatchActions(['requestEstimateSuccess'])+ expect(estimateMock).toHaveBeenCalledTimes(1)+ } finally {+ jest.useRealTimers()+ }+ })++ it('rounds a sampling percentage to two decimals before counting and before starting', async () => {+ await mountAndSettle()++ logic.actions.setConditions([{ id: 'cond-1', rollout_percentage: 33.333333, properties: [] }])+ await expectLogic(logic).toDispatchActions(['requestEstimateSuccess'])++ const rounded = [{ id: 'cond-1', rollout_percentage: 33.33, properties: [] }]+ expect(estimateMock.mock.calls[0][2].conditions).toEqual(rounded)++ logic.actions.createBackfill()+ await expectLogic(logic).toDispatchActions(['createBackfillDone'])+ expect(createMock).toHaveBeenCalledWith(+ expect.any(String),+ EVALUATION_ID,+ expect.objectContaining({ conditions: rounded })+ )+ })++ it('blocks the start button while a condition set samples nothing', async () => {+ await mountAndSettle()++ logic.actions.setConditions([{ id: 'cond-1', rollout_percentage: 0, properties: [] }])++ await expectLogic(logic).toMatchValues({+ startDisabledReason: 'Set a sampling percentage above 0% for every condition set',+ })+ })++ // The picker writes three fractional digits, the API writes none or six, so the unclamped cases+ // carry the shapes each side really sends rather than one shape for both.+ it.each([+ [+ 'the range the server counted when it clamped the one asked for',+ '2024-02-01T00:00:00Z',+ '2024-01-01T00:00:00.000Z',+ WINDOW_LABEL,+ ],+ [+ 'nothing when the server counted the range asked for',+ '2024-02-01T00:00:00Z',+ '2024-02-01T00:00:00.000Z',+ null,+ ],+ [+ 'nothing when the server answers the same instant in microseconds',+ '2024-02-01T00:00:00.123000Z',+ '2024-02-01T00:00:00.123Z',+ null,+ ],+ ])(+ 'reports %s',+ async (+ _name,+ estimateStart: string,+ requestedStart: string,+ expected: { start: string; end: string } | null+ ) => {+ await mountAndSettle()++ logic.actions.requestEstimateSuccess(+ estimate({ window_start: estimateStart, window_end: '2024-02-08T00:00:00Z' }),+ { window_start: requestedStart, window_end: '2024-02-08T00:00:00.000Z' }+ )++ await expectLogic(logic).toMatchValues({ clampedWindow: expected })+ }+ )++ it.each([+ ['no estimate yet', null, false, 'Pick a time range to see how many units match'],+ ['an empty estimate', 0, false, 'Nothing in this range matches these conditions'],+ ['a running backfill', 42, true, 'This evaluation already has a running backfill'],+ ['a usable estimate', 42, false, undefined],+ ])(+ 'reports the start button as blocked by %s',+ async (_name, totalUnits: number | null, running: boolean, expected: string | undefined) => {+ listMock.mockResolvedValue({+ count: running ? 1 : 0,+ results: running ? [backfill({ status: 'running' })] : [],+ })+ await mountAndSettle()++ if (totalUnits === null) {+ // Clearing the range is how a user gets back to having no count.+ logic.actions.setWindowRange(null, null)+ await expectLogic(logic).toDispatchActions(['requestEstimateFailure'])+ } else {+ logic.actions.requestEstimateSuccess(estimate({ total_units: totalUnits }))+ }++ await expectLogic(logic).toMatchValues({ startDisabledReason: expected })+ }+ )++ it('says it is counting while an estimate is in flight, then surfaces the failure', async () => {+ await mountAndSettle()++ estimateMock.mockRejectedValueOnce(new Error('Window too large'))+ logic.actions.setWindowRange('-14d', null)++ // An in-flight count must not read as "no range picked yet".+ await expectLogic(logic).toMatchValues({ startDisabledReason: 'Counting matching units' })++ await expectLogic(logic).toDispatchActions(['requestEstimateFailure'])+ await expectLogic(logic).toMatchValues({+ estimateError: 'Window too large',+ startDisabledReason: 'Window too large',+ })+ })++ it('stops counting when the estimate is requested with no range picked', async () => {+ await mountAndSettle()++ logic.actions.setWindowRange(null, null)++ await expectLogic(logic)+ .toDispatchActions(['requestEstimateFailure'])+ .toMatchValues({ estimateLoading: false, estimateError: null })+ expect(estimateMock).not.toHaveBeenCalled()+ })++ it('anchors a relative preset on the project timezone', async () => {+ const timezone = 'America/New_York'+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, timezone })+ await mountAndSettle()++ logic.actions.setWindowRange('-7d', null)+ await expectLogic(logic).toDispatchActions(['requestEstimateSuccess'])++ const body = estimateMock.mock.calls[estimateMock.mock.calls.length - 1][2]+ expect(body.window_start).toEqual(dayjs().tz(timezone).startOf('day').subtract(7, 'day').toISOString())+ expect(Math.abs(dayjs(body.window_end).diff(dayjs(), 'second'))).toBeLessThan(5)+ })++ it('polls the list while a backfill is running and stops once none is', async () => {+ listMock.mockResolvedValueOnce({ count: 1, results: [backfill({ status: 'running' })] })+ mountLogic()++ await expectLogic(logic).toDispatchActions(['loadBackfillsSuccess'])+ expect(logic.cache.disposables.registry.has('backfillPoll')).toBe(true)++ listMock.mockResolvedValue({ count: 1, results: [backfill({ status: 'completed' })] })+ logic.actions.loadBackfills(true)++ await expectLogic(logic).toDispatchActions(['loadBackfillsSuccess'])+ expect(logic.cache.disposables.registry.has('backfillPoll')).toBe(false)+ })++ it('keeps polling after a failed background load and returns to the base interval on success', async () => {+ jest.useFakeTimers()+ try {+ listMock.mockResolvedValue({ count: 1, results: [backfill({ status: 'running' })] })+ mountLogic()+ await jest.advanceTimersByTimeAsync(0)+ expect(listMock).toHaveBeenCalledTimes(1)++ // A failed poll re-arms itself at the base interval rather than ending the poll.+ listMock.mockRejectedValueOnce(new Error('gateway'))+ await jest.advanceTimersByTimeAsync(10_000)+ expect(listMock).toHaveBeenCalledTimes(2)+ expect(toastError).not.toHaveBeenCalled()++ // The second consecutive failure doubles the wait to 20 seconds.+ listMock.mockRejectedValueOnce(new Error('gateway'))+ await jest.advanceTimersByTimeAsync(10_000)+ expect(listMock).toHaveBeenCalledTimes(3)++ await jest.advanceTimersByTimeAsync(10_000)+ expect(listMock).toHaveBeenCalledTimes(3)+ await jest.advanceTimersByTimeAsync(10_000)+ expect(listMock).toHaveBeenCalledTimes(4)++ // That load succeeded, so the wait is back to the base interval.+ await jest.advanceTimersByTimeAsync(10_000)+ expect(listMock).toHaveBeenCalledTimes(5)+ } finally {+ jest.useRealTimers()+ }+ })++ it('recounts the range when a running backfill finishes', async () => {+ listMock.mockResolvedValueOnce({ count: 1, results: [backfill({ status: 'running' })] })+ await mountAndSettle()++ listMock.mockResolvedValue({ count: 1, results: [backfill({ status: 'completed' })] })+ logic.actions.loadBackfills(true)++ await expectLogic(logic).toDispatchActions([+ 'loadBackfillsSuccess',+ 'requestEstimate',+ 'requestEstimateSuccess',+ ])+ expect(estimateMock).toHaveBeenCalledTimes(1)+ })++ it('recounts the range when the refresh after a create already shows the run finished', async () => {+ await mountAndSettle()++ // A short walk can be over before the first refresh lands, so the list never shows it running.+ listMock.mockResolvedValue({ count: 1, results: [backfill({ status: 'completed' })] })+ logic.actions.createBackfill()++ await expectLogic(logic).toDispatchActions(['createBackfillDone', 'requestEstimate', 'requestEstimateSuccess'])+ await expectLogic(logic).toMatchValues({+ estimate: expect.objectContaining({ total_units: 42 }),+ startDisabledReason: undefined,+ })+ expect(estimateMock).toHaveBeenCalledTimes(1)+ })++ it('recounts after a save, because the server counts against the evaluation target', async () => {+ await mountAndSettle()++ // The target is not part of the request body, so the cached count cannot notice the change.+ estimateMock.mockResolvedValue(estimate({ unit: 'trace', total_units: 7 }))+ saveEvaluation({ target: 'trace' })++ await expectLogic(logic).toDispatchActions(['requestEstimate', 'requestEstimateSuccess'])+ expect(estimateMock).toHaveBeenCalledTimes(1)+ await expectLogic(logic).toMatchValues({+ unit: 'trace',+ estimate: expect.objectContaining({ total_units: 7 }),+ })+ })++ it('keeps edited condition sets through a save, and still recounts', async () => {+ await mountAndSettle()++ const edited = [{ id: 'cond-1', rollout_percentage: 25, properties: [] }]+ logic.actions.setConditions(edited)+ await expectLogic(logic).toDispatchActions(['requestEstimateSuccess'])+ estimateMock.mockClear()++ saveEvaluation({ target: 'trace' })++ await expectLogic(logic).toDispatchActions(['requestEstimate', 'requestEstimateSuccess'])+ await expectLogic(logic).toMatchValues({ conditions: edited })+ expect(estimateMock).toHaveBeenCalledTimes(1)+ })++ it('offers a retry when the list fails to load, instead of reading as an empty list', async () => {+ listMock.mockRejectedValueOnce(new ApiError('Backfills are unavailable', 503))+ mountLogic()++ await expectLogic(logic).toDispatchActions(['loadBackfillsFailure']).toMatchValues({+ backfills: [],+ backfillsError: 'Backfills are unavailable',+ backfillsLoading: false,+ })+ expect(toastError).toHaveBeenCalledWith('Backfills are unavailable')++ logic.actions.loadBackfills()+ await expectLogic(logic).toDispatchActions(['loadBackfillsSuccess']).toMatchValues({ backfillsError: null })+ })++ it('says when a throttled count can be retried', async () => {+ await mountAndSettle()++ estimateMock.mockRejectedValueOnce(new ApiError('Throttled', 429, new Headers({ 'Retry-After': '30' })))+ logic.actions.setWindowRange('-14d', null)++ await expectLogic(logic)+ .toDispatchActions(['requestEstimateFailure'])+ .toMatchValues({ estimateError: 'Too many requests. Try again in 30s.' })+ })++ it('sends the clamped window, the edited conditions and the rerun flag on create', async () => {+ await mountAndSettle()++ logic.actions.setConditions([{ id: 'cond-1', rollout_percentage: 10, properties: [] }])+ logic.actions.setRerunExisting(true)+ logic.actions.requestEstimateSuccess(+ estimate({ window_start: '2024-02-01T00:00:00Z', window_end: '2024-02-08T00:00:00Z' })+ )++ logic.actions.createBackfill()+ await expectLogic(logic).toDispatchActions(['createBackfillDone'])++ expect(createMock).toHaveBeenCalledWith(expect.any(String), EVALUATION_ID, {+ window_start: '2024-02-01T00:00:00Z',+ window_end: '2024-02-08T00:00:00Z',+ conditions: [{ id: 'cond-1', rollout_percentage: 10, properties: [] }],+ rerun_existing: true,+ })+ // The estimate belongs to the window that was just started, so it should not linger.+ await expectLogic(logic).toMatchValues({ estimate: null })+ })++ it('keeps the counted window on screen when create fails', async () => {+ await mountAndSettle()++ logic.actions.requestEstimateSuccess(estimate())+ createMock.mockRejectedValueOnce(new Error('nope'))++ logic.actions.createBackfill()+ await expectLogic(logic).toDispatchActions(['createBackfillDone'])++ await expectLogic(logic).toMatchValues({+ creatingBackfill: false,+ estimate: expect.objectContaining({ total_units: 42 }),+ })+ })++ it('cancels a backfill and reloads the list', async () => {+ listMock.mockResolvedValue({ count: 1, results: [backfill({ status: 'running' })] })+ mountLogic()+ await expectLogic(logic).toDispatchActions(['loadBackfillsSuccess'])++ logic.actions.cancelBackfill('backfill-1')+ await expectLogic(logic).toMatchValues({ transitioningIds: ['backfill-1'] })+ await expectLogic(logic).toDispatchActions(['transitionBackfillDone'])++ expect(cancelMock).toHaveBeenCalledWith(expect.any(String), EVALUATION_ID, 'backfill-1')+ await expectLogic(logic).toMatchValues({ transitioningIds: [] })+ })+})diff --git a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.ts b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.tsnew file mode 100644index 000000000000..0f39bb1c8eb4--- /dev/null+++ b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.ts@@ -0,0 +1,581 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'++import { ApiError } from 'lib/api'+import { dayjs } from 'lib/dayjs'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { dateStringToDayJs } from 'lib/utils/dateFilters'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { teamLogic } from 'scenes/teamLogic'++import {+ evaluationsBackfillsCancelCreate,+ evaluationsBackfillsCreate,+ evaluationsBackfillsEstimateCreate,+ evaluationsBackfillsList,+} from '../generated/api'+import type {+ EvaluationBackfillApi,+ EvaluationBackfillEstimateApi,+ EvaluationConditionApi,+ EvaluationConditionApiPropertiesItem,+ EvaluationTargetEnumApi,+} from '../generated/api.schemas'+import { evaluationErrorMessage } from './apiErrors'+import { backfillRangeDateFormat } from './backfillConditions'+import { hasUnsetConditionRollout, llmEvaluationLogic, normalizeConditionRollouts } from './llmEvaluationLogic'+import type { EvaluationConditionSet } from './types'+import type { EvaluationConfig } from './types'++export interface EvaluationBackfillsLogicProps {+ evaluationId: string+}++// Keeps progress counts fresh while a backfill dispatches, without hammering the API when idle.+const ACTIVE_POLL_INTERVAL_MS = 10_000+const MAX_POLL_INTERVAL_MS = 60_000+const POLL_KEY = 'backfillPoll'+const BACKFILL_PAGE_SIZE = 100+const DEFAULT_WINDOW_DATE_FROM = '-7d'+// Long enough that typing a custom date or dragging the sampling slider counts once, at the end.+const ESTIMATE_DEBOUNCE_MS = 500++interface BackfillWindow {+ window_start: string+ window_end: string+}++/** The backfill API rejects anything the editor or the stored config carries alongside a condition+ * set, compiled bytecode for one. */+function toBackfillCondition(condition: EvaluationConditionSet): EvaluationConditionSet {+ return {+ id: condition.id,+ rollout_percentage: condition.rollout_percentage,+ properties: condition.properties,+ }+}++function toRequestConditions(conditions: EvaluationConditionSet[]): EvaluationConditionApi[] {+ return normalizeConditionRollouts(conditions).map((condition) => ({+ ...condition,+ // The editor types property filters as a union, the request type as plain objects. They+ // agree at runtime, so only this field is cast.+ properties: condition.properties as EvaluationConditionApiPropertiesItem[] | undefined,+ }))+}++/** Turn the picker's DateFilter tokens (`-7d`, an ISO date) into the ISO instants the API accepts.+ * Relative presets anchor on the project's own calendar day, so the timezone has to come along. */+function resolveWindow(dateFrom: string | null, dateTo: string | null, timezone: string): BackfillWindow {+ const bound = (value: string | null, fallback: dayjs.Dayjs): string =>+ ((value && dateStringToDayJs(value, timezone)) || fallback).toISOString()+ return {+ window_start: bound(dateFrom, dayjs().subtract(30, 'day')),+ window_end: bound(dateTo, dayjs()),+ }+}++/** The picker writes bounds with `toISOString()`, which always has three fractional digits, while+ * the API writes them with DRF, which has none or six for the same instant. So the two sides never+ * agree as strings and have to be compared as instants. */+function isSameInstant(a: string, b: string): boolean {+ return dayjs(a).valueOf() === dayjs(b).valueOf()+}++function backfillErrorMessage(error: unknown, fallback: string): string {+ // `formattedRetryAfter` already reads as "in 30s" or "later", so the sentence adds no preposition.+ if (error instanceof ApiError && error.formattedRetryAfter) {+ return `Too many requests. Try again ${error.formattedRetryAfter}.`+ }+ return evaluationErrorMessage(error, fallback)+}++/** Each consecutive list failure doubles the wait, so an API that is already struggling is not+ * polled at full rate. The wait returns to the base interval as soon as one load succeeds. */+function pollDelayMs(consecutiveFailures: number): number {+ return Math.min(ACTIVE_POLL_INTERVAL_MS * 2 ** Math.max(consecutiveFailures - 1, 0), MAX_POLL_INTERVAL_MS)+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface evaluationBackfillsLogicValues {+ evaluation: EvaluationConfig | null // llmEvaluationLogic+ timezone: string // teamLogic+ backfills: EvaluationBackfillApi[]+ backfillsError: string | null+ backfillsLoading: boolean+ clampedWindow: {+ end: string+ start: string+ } | null+ conditions: EvaluationConditionSet[]+ conditionsDirty: boolean+ creatingBackfill: boolean+ estimate: EvaluationBackfillEstimateApi | null+ estimateError: string | null+ estimateLoading: boolean+ expandedBackfillIds: string[]+ hasActiveBackfill: boolean+ pollFailures: number+ requestedWindow: BackfillWindow | null+ rerunExisting: boolean+ settleWait: string | null+ startDisabledReason: string | undefined+ transitioningIds: string[]+ unit: EvaluationTargetEnumApi+ windowDateFrom: string | null+ windowDateTo: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface evaluationBackfillsLogicActions {+ loadEvaluationSuccess: (evaluation: EvaluationConfig | null) => {+ evaluation: EvaluationConfig | null+ requestedTab: string | null+ } // llmEvaluationLogic+ saveEvaluationSuccess: (evaluation: EvaluationConfig) => {+ evaluation: EvaluationConfig+ } // llmEvaluationLogic+ cancelBackfill: (id: string) => {+ id: string+ }+ collapseBackfill: (id: string) => {+ id: string+ }+ createBackfill: () => {+ value: true+ }+ createBackfillDone: (succeeded: boolean) => {+ succeeded: boolean+ }+ expandBackfill: (id: string) => {+ id: string+ }+ loadBackfills: (background?: boolean) => {+ background: boolean+ }+ loadBackfillsFailure: (error: string) => {+ error: string+ }+ loadBackfillsSuccess: (backfills: EvaluationBackfillApi[]) => {+ backfills: EvaluationBackfillApi[]+ }+ requestEstimate: () => {+ value: true+ }+ requestEstimateFailure: (error: string | null) => {+ error: string | null+ }+ requestEstimateSuccess: (+ estimate: EvaluationBackfillEstimateApi,+ requestedWindow?: BackfillWindow | null+ ) => {+ estimate: EvaluationBackfillEstimateApi+ requestedWindow: BackfillWindow | null+ }+ seedConditions: (conditions: EvaluationConditionSet[]) => {+ conditions: EvaluationConditionSet[]+ }+ setConditions: (conditions: EvaluationConditionSet[]) => {+ conditions: EvaluationConditionSet[]+ }+ setRerunExisting: (rerunExisting: boolean) => {+ rerunExisting: boolean+ }+ setWindowRange: (+ dateFrom: string | null,+ dateTo: string | null+ ) => {+ dateFrom: string | null+ dateTo: string | null+ }+ transitionBackfillDone: (id: string) => {+ id: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface evaluationBackfillsLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ hasActiveBackfill: (backfills: EvaluationBackfillApi[]) => boolean+ unit: (+ estimate: EvaluationBackfillEstimateApi | null,+ evaluation: EvaluationConfig | null+ ) => EvaluationTargetEnumApi+ startDisabledReason: (+ hasActiveBackfill: boolean,+ conditions: EvaluationConditionSet[],+ estimate: EvaluationBackfillEstimateApi | null,+ estimateLoading: boolean,+ estimateError: string | null+ ) => string | undefined+ settleWait: (estimate: EvaluationBackfillEstimateApi | null) => string | null+ clampedWindow: (+ estimate: EvaluationBackfillEstimateApi | null,+ requestedWindow: BackfillWindow | null,+ timezone: string+ ) => {+ end: string+ start: string+ } | null+ }+}++export type evaluationBackfillsLogicType = MakeLogicType<+ evaluationBackfillsLogicValues,+ evaluationBackfillsLogicActions,+ EvaluationBackfillsLogicProps,+ evaluationBackfillsLogicMeta+>++export const evaluationBackfillsLogic = kea<evaluationBackfillsLogicType>([+ path((key) => ['products', 'ai_observability', 'evaluations', 'evaluationBackfillsLogic', key]),+ props({} as EvaluationBackfillsLogicProps),+ key((props) => props.evaluationId),++ connect((props: EvaluationBackfillsLogicProps) => ({+ values: [llmEvaluationLogic({ evaluationId: props.evaluationId }), ['evaluation'], teamLogic, ['timezone']],+ actions: [+ llmEvaluationLogic({ evaluationId: props.evaluationId }),+ ['loadEvaluationSuccess', 'saveEvaluationSuccess'],+ ],+ })),++ actions({+ loadBackfills: (background: boolean = false) => ({ background }),+ loadBackfillsSuccess: (backfills: EvaluationBackfillApi[]) => ({ backfills }),+ loadBackfillsFailure: (error: string) => ({ error }),+ requestEstimate: true,+ requestEstimateSuccess: (+ estimate: EvaluationBackfillEstimateApi,+ requestedWindow: BackfillWindow | null = null+ ) => ({+ estimate,+ requestedWindow,+ }),+ requestEstimateFailure: (error: string | null) => ({ error }),+ createBackfill: true,+ createBackfillDone: (succeeded: boolean) => ({ succeeded }),+ cancelBackfill: (id: string) => ({ id }),+ transitionBackfillDone: (id: string) => ({ id }),+ expandBackfill: (id: string) => ({ id }),+ collapseBackfill: (id: string) => ({ id }),+ setWindowRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),+ setConditions: (conditions: EvaluationConditionSet[]) => ({ conditions }),+ seedConditions: (conditions: EvaluationConditionSet[]) => ({ conditions }),+ setRerunExisting: (rerunExisting: boolean) => ({ rerunExisting }),+ }),++ reducers({+ backfills: [[] as EvaluationBackfillApi[], { loadBackfillsSuccess: (_, { backfills }) => backfills }],+ backfillsError: [+ null as string | null,+ {+ loadBackfills: () => null,+ loadBackfillsSuccess: () => null,+ loadBackfillsFailure: (_, { error }) => error,+ },+ ],+ backfillsLoading: [+ false,+ {+ loadBackfills: (state, { background }) => (background ? state : true),+ loadBackfillsSuccess: () => false,+ loadBackfillsFailure: () => false,+ },+ ],+ pollFailures: [0, { loadBackfillsSuccess: () => 0, loadBackfillsFailure: (state) => state + 1 }],+ estimate: [+ null as EvaluationBackfillEstimateApi | null,+ {+ requestEstimate: () => null,+ requestEstimateSuccess: (_, { estimate }) => estimate,+ // A failed create leaves the counted window on screen so the user can retry it.+ createBackfillDone: (state, { succeeded }) => (succeeded ? null : state),+ },+ ],+ requestedWindow: [+ null as BackfillWindow | null,+ {+ requestEstimate: () => null,+ requestEstimateSuccess: (_, { requestedWindow }) => requestedWindow,+ },+ ],+ estimateError: [+ null as string | null,+ {+ requestEstimate: () => null,+ requestEstimateSuccess: () => null,+ requestEstimateFailure: (_, { error }) => error,+ },+ ],+ estimateLoading: [+ false,+ {+ requestEstimate: () => true,+ requestEstimateSuccess: () => false,+ requestEstimateFailure: () => false,+ },+ ],+ creatingBackfill: [false, { createBackfill: () => true, createBackfillDone: () => false }],+ windowDateFrom: [DEFAULT_WINDOW_DATE_FROM as string | null, { setWindowRange: (_, { dateFrom }) => dateFrom }],+ windowDateTo: [null as string | null, { setWindowRange: (_, { dateTo }) => dateTo }],+ conditions: [+ [] as EvaluationConditionSet[],+ {+ seedConditions: (_, { conditions }) => conditions,+ setConditions: (_, { conditions }) => conditions,+ },+ ],+ conditionsDirty: [false, { setConditions: () => true }],+ rerunExisting: [false, { setRerunExisting: (_, { rerunExisting }) => rerunExisting }],+ expandedBackfillIds: [+ [] as string[],+ {+ expandBackfill: (state, { id }) => (state.includes(id) ? state : [...state, id]),+ collapseBackfill: (state, { id }) => state.filter((expandedId) => expandedId !== id),+ },+ ],+ transitioningIds: [+ [] as string[],+ {+ cancelBackfill: (state, { id }) => [...state, id],+ transitionBackfillDone: (state, { id }) => state.filter((i) => i !== id),+ },+ ],+ }),++ selectors({+ hasActiveBackfill: [+ (s) => [s.backfills],+ (backfills: EvaluationBackfillApi[]): boolean => backfills.some((b) => b.status === 'running'),+ ],+ unit: [+ (s) => [s.estimate, s.evaluation],+ (+ estimate: EvaluationBackfillEstimateApi | null,+ evaluation: EvaluationConfig | null+ ): EvaluationTargetEnumApi => estimate?.unit ?? evaluation?.target ?? 'generation',+ ],+ startDisabledReason: [+ (s) => [s.hasActiveBackfill, s.conditions, s.estimate, s.estimateLoading, s.estimateError],+ (+ hasActiveBackfill: boolean,+ conditions: EvaluationConditionSet[],+ estimate: EvaluationBackfillEstimateApi | null,+ estimateLoading: boolean,+ estimateError: string | null+ ): string | undefined => {+ if (hasActiveBackfill) {+ return 'This evaluation already has a running backfill'+ }+ // Checked before the count, which reads as an empty range rather than as a 0% sample.+ if (hasUnsetConditionRollout(conditions)) {+ return 'Set a sampling percentage above 0% for every condition set'+ }+ if (estimateLoading) {+ return 'Counting matching units'+ }+ if (estimateError) {+ return estimateError+ }+ if (!estimate) {+ return 'Pick a time range to see how many units match'+ }+ if (estimate.total_units === 0) {+ return 'Nothing in this range matches these conditions'+ }+ return undefined+ },+ ],+ // The server holds the window back by the evaluation's wait, so the gap between the+ // counted end and now is that wait. Reading it back keeps one definition of the rule.+ settleWait: [+ (s) => [s.estimate],+ (estimate: EvaluationBackfillEstimateApi | null): string | null => {+ if (!estimate) {+ return null+ }+ const seconds = dayjs().diff(dayjs(estimate.window_end), 'second')+ return seconds > 60 ? humanFriendlyDuration(seconds, { maxUnits: 1 }) : null+ },+ ],+ clampedWindow: [+ (s) => [s.estimate, s.requestedWindow, s.timezone],+ (+ estimate: EvaluationBackfillEstimateApi | null,+ requestedWindow: BackfillWindow | null,+ timezone: string+ ): { start: string; end: string } | null => {+ if (!estimate || !requestedWindow) {+ return null+ }+ if (+ isSameInstant(estimate.window_start, requestedWindow.window_start) &&+ isSameInstant(estimate.window_end, requestedWindow.window_end)+ ) {+ return null+ }+ // The server counted a shorter span than the picker asked for, so name the span it counted.+ const format = backfillRangeDateFormat(estimate.window_start, estimate.window_end, dayjs())+ return {+ start: dayjs(estimate.window_start).tz(timezone).format(format),+ end: dayjs(estimate.window_end).tz(timezone).format(format),+ }+ },+ ],+ }),++ listeners(({ actions, props, values, cache }) => {+ /** Arms the next poll off the list the logic last saw, so a failed request keeps the poll+ * alive instead of ending it. */+ const schedulePoll = (): void => {+ if (!values.hasActiveBackfill) {+ cache.disposables.dispose(POLL_KEY)+ return+ }+ const delay = pollDelayMs(values.pollFailures)+ cache.disposables.add(() => {+ const timerId = window.setTimeout(() => actions.loadBackfills(true), delay)+ return () => window.clearTimeout(timerId)+ }, POLL_KEY)+ }+ /** The server counts against the evaluation's own target and target config, neither of+ * which the request carries, so a save that changes either leaves the cached count+ * describing a different unit. Seeding recounts on its own; an edited editor keeps its+ * condition sets and only recounts. */+ const followEvaluation = (): void => {+ cache.lastEstimate = null+ if (!values.conditionsDirty && values.evaluation) {+ actions.seedConditions(values.evaluation.conditions.map(toBackfillCondition))+ } else {+ actions.requestEstimate()+ }+ }+ return {+ loadEvaluationSuccess: followEvaluation,+ saveEvaluationSuccess: followEvaluation,+ loadBackfills: async ({ background }) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return+ }+ try {+ const response = await evaluationsBackfillsList(String(teamId), props.evaluationId, {+ limit: BACKFILL_PAGE_SIZE,+ })+ actions.loadBackfillsSuccess(response.results ?? [])+ if (values.hasActiveBackfill) {+ cache.recountWhenIdle = true+ } else if (cache.recountWhenIdle) {+ // A finished run changed which units already have a result, so the count is+ // stale. A short run can be over by the first refresh, so the recount hangs+ // off the run being gone rather than off having seen it running.+ cache.recountWhenIdle = false+ cache.lastEstimate = null+ actions.requestEstimate()+ }+ } catch (error) {+ const message = backfillErrorMessage(error, 'Couldn’t load backfills. Try again.')+ actions.loadBackfillsFailure(message)+ if (!background) {+ // A poll fails on its own in the background, where the inline error is enough.+ lemonToast.error(message)+ }+ }+ },+ loadBackfillsSuccess: schedulePoll,+ loadBackfillsFailure: schedulePoll,+ seedConditions: () => actions.requestEstimate(),+ setWindowRange: () => actions.requestEstimate(),+ setConditions: () => actions.requestEstimate(),+ setRerunExisting: () => actions.requestEstimate(),+ requestEstimate: async (_, breakpoint) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId || !values.windowDateFrom) {+ // Nothing was asked for, so there is no error to report, only a count to stop.+ actions.requestEstimateFailure(null)+ return+ }+ await breakpoint(ESTIMATE_DEBOUNCE_MS)+ const request = {+ ...resolveWindow(values.windowDateFrom, values.windowDateTo, values.timezone),+ conditions: toRequestConditions(values.conditions),+ rerun_existing: values.rerunExisting,+ }+ const requestKey = JSON.stringify(request)+ if (cache.lastEstimate && cache.lastEstimateKey === requestKey) {+ // Every edit recounts. An edit that leaves the request identical, such as a+ // filter put back the way it was, keeps the count it already has.+ actions.requestEstimateSuccess(cache.lastEstimate, request)+ return+ }+ try {+ const estimate = await evaluationsBackfillsEstimateCreate(+ String(teamId),+ props.evaluationId,+ request+ )+ breakpoint()+ cache.lastEstimateKey = requestKey+ cache.lastEstimate = estimate+ actions.requestEstimateSuccess(estimate, request)+ } catch (error) {+ breakpoint()+ // No toast: the count reruns on every edit, and `estimateError` shows inline.+ actions.requestEstimateFailure(backfillErrorMessage(error, 'Couldn’t count this range. Try again.'))+ }+ },+ createBackfill: async () => {+ const teamId = teamLogic.values.currentTeamId+ const estimate = values.estimate+ if (!teamId || !estimate) {+ actions.createBackfillDone(false)+ return+ }+ let succeeded = false+ try {+ // The window the server clamped for the estimate is the one it just counted.+ await evaluationsBackfillsCreate(String(teamId), props.evaluationId, {+ window_start: estimate.window_start,+ window_end: estimate.window_end,+ conditions: toRequestConditions(values.conditions),+ rerun_existing: values.rerunExisting,+ })+ succeeded = true+ // The units this run covers now have a result, so the count it started from is stale.+ cache.lastEstimate = null+ cache.recountWhenIdle = true+ lemonToast.success('Backfill started')+ actions.loadBackfills()+ } catch (error) {+ lemonToast.error(backfillErrorMessage(error, 'Couldn’t start the backfill. Try again.'))+ // A concurrent backfill can be the cause (only one may run at a time), so refresh+ // the table to show it.+ actions.loadBackfills(true)+ } finally {+ actions.createBackfillDone(succeeded)+ }+ },+ cancelBackfill: async ({ id }) => {+ const teamId = teamLogic.values.currentTeamId+ try {+ if (teamId) {+ await evaluationsBackfillsCancelCreate(String(teamId), props.evaluationId, id)+ actions.loadBackfills(true)+ }+ } catch (error) {+ lemonToast.error(backfillErrorMessage(error, 'Couldn’t cancel the backfill. Try again.'))+ } finally {+ actions.transitionBackfillDone(id)+ }+ },+ }+ }),++ afterMount(({ actions, values }) => {+ actions.loadBackfills()+ if (values.evaluation) {+ actions.seedConditions(values.evaluation.conditions.map(toBackfillCondition))+ }+ }),+])diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.tsindex ba563849bde1..ab0a80500454 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts@@ -1,10 +1,12 @@import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import { actionToUrl, router, urlToAction } from 'kea-router'+import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'import posthog from 'posthog-js'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'+import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -12,13 +14,15 @@ import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigatiimport { MaxContextInput, createMaxContextHelpers } from '~/scenes/max/maxTypes'import { ActivityScope, Breadcrumb } from '~/types'+import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'import {+ evaluationsBackfillsRetrieve,evaluationsCreate,evaluationsPartialUpdate,evaluationsRetrieve,evaluationsTestHogCreate,} from '../generated/api'-import type { TestHogRequestApi, TestHogResultItemApi } from '../generated/api.schemas'+import type { EvaluationBackfillApi, TestHogRequestApi, TestHogResultItemApi } from '../generated/api.schemas'import { parsePlaygroundProviderKeyId } from '../ModelPicker'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import type { EvaluationConfig as TeamEvaluationConfig } from '../settings/llmProviderKeysLogic'@@ -63,10 +67,17 @@ export const DEFAULT_SESSION_QUIET_PERIOD_SECONDS = 60 * 60export const DEFAULT_SESSION_MAX_AGE_SECONDS = 24 * 60 * 60const AGGREGATE_TARGETS: EvaluationTarget[] = ['trace', 'session']-const EVALUATION_DETAIL_TABS = new Set(['configuration', 'reports', 'runs'])+const EVALUATION_DETAIL_TABS = new Set(['configuration', 'reports', 'runs', 'backfills'])function evaluationDetailTab(value: unknown): string | null {- return typeof value === 'string' && EVALUATION_DETAIL_TABS.has(value) ? value : null+ if (typeof value !== 'string' || !EVALUATION_DETAIL_TABS.has(value)) {+ return null+ }+ // Backfills is flag-gated, so a bookmarked URL for it falls back to the default tab.+ if (value === 'backfills' && !featureFlagLogic.values.featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVAL_BACKFILLS]) {+ return null+ }+ return value}function seedSettleConfig(target: EvaluationTarget, strategy: EvaluationSettleStrategy): EvaluationTargetConfig {@@ -114,6 +125,21 @@ const DEFAULT_SENTIMENT_SOURCE = 'user_messages' as constconst DEFAULT_SENTIMENT_RUNS_FILTER = 'negative' as constconst DEFAULT_CONDITION_ROLLOUT_PERCENTAGE = 100+/** The rollout is a percentage the backend stores as typed, so the editor holds it to two decimals+ * before anything is sent. Conditions that never carried the key keep it absent. */+export function normalizeConditionRollouts<T extends { rollout_percentage?: number }>(conditions: T[]): T[] {+ return conditions.map((condition) =>+ condition.rollout_percentage != null+ ? { ...condition, rollout_percentage: Math.round(condition.rollout_percentage * 100) / 100 }+ : condition+ )+}++/** A condition set at 0% matches nothing, so both editors refuse to send one. */+export function hasUnsetConditionRollout(conditions: { rollout_percentage?: number }[]): boolean {+ return conditions.some((condition) => (condition.rollout_percentage ?? 0) === 0)+}+function toLLMJudgeEvaluation(evaluation: EvaluationConfig): LLMJudgeEvaluation {return {...evaluation,@@ -221,6 +247,7 @@ export interface LLMEvaluationLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface llmEvaluationLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogicactiveProviderKey: LLMProviderKey | null | undefined // llmProviderKeysLogicproviderKeys: LLMProviderKey[] // llmProviderKeysLogicproviderKeysLoading: boolean // llmProviderKeysLogic@@ -249,6 +276,9 @@ export interface llmEvaluationLogicValues {maxContext: MaxContextInput[]modelSelectionRequired: booleanoriginalEvaluation: EvaluationConfig | null+ runsBackfill: EvaluationBackfillApi | null+ runsBackfillId: string | null+ runsBackfillLoading: booleanrunsStats: EvaluationRunsStats | nullrunsStatsLoading: booleanrunsSummary: {@@ -299,6 +329,21 @@ export interface llmEvaluationLogicActions {evaluation: EvaluationConfig | nullrequestedTab: string | null}+ loadRunsBackfill: () => any+ loadRunsBackfillFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRunsBackfillSuccess: (+ runsBackfill: EvaluationBackfillApi | null,+ payload?: any+ ) => {+ runsBackfill: EvaluationBackfillApi | null+ payload?: any+ }loadRunsStats: () => anyloadRunsStatsFailure: (error: string,@@ -379,6 +424,9 @@ export interface llmEvaluationLogicActions {setModelConfiguration: (modelConfiguration: ModelConfiguration | null) => {modelConfiguration: ModelConfiguration | null}+ setRunsBackfillId: (backfillId: string | null) => {+ backfillId: string | null+ }setSettleStrategy: (strategy: EvaluationSettleStrategy) => {strategy: EvaluationSettleStrategy}@@ -477,6 +525,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([values: [llmProviderKeysLogic,['providerKeys', 'providerKeysLoading', 'requiresProviderKey', 'activeProviderKey'],+ featureFlagLogic,+ ['featureFlags'],],actions: [llmProviderKeysLogic, ['loadProviderKeys', 'loadEvaluationConfigSuccess']],})),@@ -501,6 +551,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([// Tab navigationsetActiveTab: (tab: string) => ({ tab }),+ setRunsBackfillId: (backfillId: string | null) => ({ backfillId }),// Evaluation management actionssaveEvaluation: true,@@ -596,11 +647,24 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([return await queryEvaluationRuns({evaluationId: props.evaluationId,+ backfillId: values.runsBackfillId ?? undefined,forceRefresh: values.isForceRefresh,})},},],+ runsBackfill: [+ null as EvaluationBackfillApi | null,+ {+ loadRunsBackfill: async () => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId || !values.runsBackfillId || props.evaluationId === 'new') {+ return null+ }+ return await evaluationsBackfillsRetrieve(String(teamId), props.evaluationId, values.runsBackfillId)+ },+ },+ ],runsStats: [null as EvaluationRunsStats | null,{@@ -611,6 +675,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([return await queryEvaluationRunsStats({evaluationId: props.evaluationId,+ backfillId: values.runsBackfillId ?? undefined,forceRefresh: values.isForceRefresh,})},@@ -645,16 +710,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([? { ...state, output_config: { ...state.output_config, true_is_failure: trueIsFailure } }: state,setTriggerConditions: (state, { conditions }) =>- state- ? {- ...state,- conditions: conditions.map((c) =>- c.rollout_percentage != null- ? { ...c, rollout_percentage: Math.round(c.rollout_percentage * 100) / 100 }- : c- ),- }- : null,+ state ? { ...state, conditions: normalizeConditionRollouts(conditions) } : null,setModelConfiguration: (state, { modelConfiguration }) =>state && isLLMJudgeEvaluation(state)? { ...state, model_configuration: modelConfiguration }@@ -805,6 +861,12 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([evaluation?.evaluation_type === 'sentiment' ? DEFAULT_SENTIMENT_RUNS_FILTER : 'all',},],+ runsBackfillId: [+ null as string | null,+ {+ setRunsBackfillId: (_, { backfillId }) => backfillId,+ },+ ],activeTab: ['configuration' as string,{@@ -1020,6 +1082,20 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([llmEvaluationsLogic.findMounted()?.actions.loadEvaluations()if (isNew) {globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.SetUpLlmEvaluation)+ // Saving navigates away, so the offer to cover past data travels with the user.+ if (response?.id && values.featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVAL_BACKFILLS]) {+ lemonToast.info('This evaluation grades new data from now on.', {+ button: {+ label: 'Evaluate past data',+ action: () =>+ router.actions.push(+ combineUrl(urls.aiObservabilityEvaluation(response.id), {+ evaluation_tab: 'backfills',+ }).url+ ),+ },+ })+ }}// Piggyback the scheduled-report draft onto the main save so the single@@ -1268,6 +1344,16 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([actions.setActiveTab(requestedTab)}+ const requestedBackfillId = searchParams.backfill_id ?? null+ if (requestedBackfillId !== values.runsBackfillId) {+ actions.setRunsBackfillId(requestedBackfillId)+ actions.loadEvaluationRuns()+ actions.loadRunsStats()+ if (requestedBackfillId) {+ actions.loadRunsBackfill()+ }+ }+// Only reload when navigating to a different evaluation, not on search param changes (e.g., pagination)const newEvaluationId = id && id !== 'new' ? id : 'new'if (method === 'PUSH' && newEvaluationId !== props.evaluationId) {diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 93b041e06d97..e5ca9ddea6ee 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -1020,6 +1020,107 @@ export interface PaginatedEvaluationListApi {results: EvaluationApi[]}+/**+ * * `running` - Running+ * * `completed` - Completed+ * * `cancelled` - Cancelled+ */+export type EvaluationBackfillStatusEnumApi =+ (typeof EvaluationBackfillStatusEnumApi)[keyof typeof EvaluationBackfillStatusEnumApi]++export const EvaluationBackfillStatusEnumApi = {+ Running: 'running',+ Completed: 'completed',+ Cancelled: 'cancelled',+} as const++export type EvaluationBackfillConditionApiPropertiesItem = { [key: string]: unknown }++/**+ * One condition set as it was frozen onto the backfill: no id, no compiled bytecode.+ */+export interface EvaluationBackfillConditionApi {+ /** Property filters (event or person) that scope which units match this condition set. */+ properties?: EvaluationBackfillConditionApiPropertiesItem[]+ /** Percentage (0-100) of matching units sampled for this condition set. */+ rollout_percentage?: number+}++export interface EvaluationBackfillApi {+ /** Backfill identifier. */+ readonly id: string+ /** running while the walk is dispatching, then completed or cancelled.+ *+ * * `running` - Running+ * * `completed` - Completed+ * * `cancelled` - Cancelled */+ readonly status: EvaluationBackfillStatusEnumApi+ /** What one unit is, frozen at creation: a generation, a trace, or a session.+ *+ * * `generation` - Generation+ * * `trace` - Trace+ * * `session` - Session */+ readonly target: EvaluationTargetEnumApi+ /** Inclusive start of the window, by unit timestamp. */+ readonly window_start: string+ /** Exclusive end of the window. */+ readonly window_end: string+ /** Condition sets frozen at creation, so an edit to the evaluation does not change this run. */+ readonly conditions: readonly EvaluationBackfillConditionApi[]+ /** Whether units with an existing result are evaluated again. */+ readonly rerun_existing: boolean+ /** Units matched at creation; the ceiling on dispatched_count. */+ readonly total_count: number+ /** Units the backfill has started an evaluation for so far. */+ readonly dispatched_count: number+ /** Units the live path had already covered, so nothing was dispatched. */+ readonly skipped_count: number+ /** User who started the backfill. */+ readonly created_by: UserBasicApi | null+ /** When the backfill was created. */+ readonly created_at: string+ /**+ * When the backfill reached a terminal status; null while it runs.+ * @nullable+ */+ readonly finished_at: string | null+}++export interface PaginatedEvaluationBackfillListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: EvaluationBackfillApi[]+}++export interface EvaluationBackfillRequestApi {+ /** Inclusive start of the window, by unit timestamp. */+ window_start: string+ /** Exclusive end of the window. Values in the future are clamped to now. */+ window_end: string+ /** Condition sets to match. Defaults to the evaluation's own condition sets. */+ conditions?: EvaluationConditionApi[]+ /** Evaluate units again even when this evaluation already has a result for them. */+ rerun_existing?: boolean+}++export interface EvaluationBackfillEstimateApi {+ /** Units that would be evaluated. */+ total_units: number+ /** What one unit is: a generation, a trace, or a session.+ *+ * * `generation` - Generation+ * * `trace` - Trace+ * * `session` - Session */+ unit: EvaluationTargetEnumApi+ /** Window start after clamping. */+ window_start: string+ /** Window end after clamping. */+ window_end: string+}+/*** Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}.*/@@ -3348,6 +3449,17 @@ export const EvaluationsListEvaluationType = {Sentiment: 'sentiment',} as const+export type EvaluationsBackfillsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type LlmAnalyticsClusteringJobsListParams = {/*** Number of results to return per page.diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.tsindex cf7e5bc81af2..d15dba93991a 100644--- a/products/ai_observability/frontend/generated/api.ts+++ b/products/ai_observability/frontend/generated/api.ts@@ -31,6 +31,9 @@ import type {DatasetsListParams,DatasetsRevisionsListParams,EvaluationApi,+ EvaluationBackfillApi,+ EvaluationBackfillEstimateApi,+ EvaluationBackfillRequestApi,EvaluationConfigApi,EvaluationConfigSetActiveKeyRequestApi,EvaluationDirectoryApi,@@ -38,6 +41,7 @@ import type {EvaluationReportUpdateApi,EvaluationRunRequestApi,EvaluationRunsCreate200,+ EvaluationsBackfillsListParams,EvaluationsListParams,InstrumentationCheckActionApi,InstrumentationChecklistApi,@@ -71,6 +75,7 @@ import type {PaginatedDatasetItemReadListApi,PaginatedDatasetReadListApi,PaginatedDatasetRevisionReadListApi,+ PaginatedEvaluationBackfillListApi,PaginatedEvaluationListApi,PaginatedEvaluationReportListApi,PaginatedEvaluationReportRunListApi,@@ -796,6 +801,127 @@ export const evaluationsCreate = async (})}+export const getEvaluationsBackfillsListUrl = (+ projectId: string,+ evaluationId: string,+ params?: EvaluationsBackfillsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/evaluations/${evaluationId}/backfills/?${stringifiedParams}`+ : `/api/projects/${projectId}/evaluations/${evaluationId}/backfills/`+}++/**+ * Historical runs of one evaluation over a closed time window (nested under an evaluation).+ */+export const evaluationsBackfillsList = async (+ projectId: string,+ evaluationId: string,+ params?: EvaluationsBackfillsListParams,+ options?: RequestInit+): Promise<PaginatedEvaluationBackfillListApi> => {+ return apiMutator<PaginatedEvaluationBackfillListApi>(+ getEvaluationsBackfillsListUrl(projectId, evaluationId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getEvaluationsBackfillsCreateUrl = (projectId: string, evaluationId: string) => {+ return `/api/projects/${projectId}/evaluations/${evaluationId}/backfills/`+}++/**+ * Create a backfill: freeze the conditions, count the units, start the walk.+ */+export const evaluationsBackfillsCreate = async (+ projectId: string,+ evaluationId: string,+ evaluationBackfillRequestApi: EvaluationBackfillRequestApi,+ options?: RequestInit+): Promise<EvaluationBackfillApi> => {+ return apiMutator<EvaluationBackfillApi>(getEvaluationsBackfillsCreateUrl(projectId, evaluationId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(evaluationBackfillRequestApi),+ })+}++export const getEvaluationsBackfillsRetrieveUrl = (projectId: string, evaluationId: string, id: string) => {+ return `/api/projects/${projectId}/evaluations/${evaluationId}/backfills/${id}/`+}++/**+ * Historical runs of one evaluation over a closed time window (nested under an evaluation).+ */+export const evaluationsBackfillsRetrieve = async (+ projectId: string,+ evaluationId: string,+ id: string,+ options?: RequestInit+): Promise<EvaluationBackfillApi> => {+ return apiMutator<EvaluationBackfillApi>(getEvaluationsBackfillsRetrieveUrl(projectId, evaluationId, id), {+ ...options,+ method: 'GET',+ })+}++export const getEvaluationsBackfillsCancelCreateUrl = (projectId: string, evaluationId: string, id: string) => {+ return `/api/projects/${projectId}/evaluations/${evaluationId}/backfills/${id}/cancel/`+}++/**+ * Stop a running backfill. Evaluations already dispatched still finish.+ */+export const evaluationsBackfillsCancelCreate = async (+ projectId: string,+ evaluationId: string,+ id: string,+ options?: RequestInit+): Promise<EvaluationBackfillApi> => {+ return apiMutator<EvaluationBackfillApi>(getEvaluationsBackfillsCancelCreateUrl(projectId, evaluationId, id), {+ ...options,+ method: 'POST',+ })+}++export const getEvaluationsBackfillsEstimateCreateUrl = (projectId: string, evaluationId: string) => {+ return `/api/projects/${projectId}/evaluations/${evaluationId}/backfills/estimate/`+}++/**+ * Count what a backfill over the given window would evaluate, without creating one.+ */+export const evaluationsBackfillsEstimateCreate = async (+ projectId: string,+ evaluationId: string,+ evaluationBackfillRequestApi: EvaluationBackfillRequestApi,+ options?: RequestInit+): Promise<EvaluationBackfillEstimateApi> => {+ return apiMutator<EvaluationBackfillEstimateApi>(+ getEvaluationsBackfillsEstimateCreateUrl(projectId, evaluationId),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(evaluationBackfillRequestApi),+ }+ )+}+export const getEvaluationsRetrieveUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/evaluations/${id}/`}diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.tsindex 30f005a7f80a..4e21ad828c8c 100644--- a/products/ai_observability/frontend/generated/api.zod.ts+++ b/products/ai_observability/frontend/generated/api.zod.ts@@ -462,6 +462,104 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod}).describe('An evaluation that scores LLM generations, traces, or sessions.')+/**+ * Create a backfill: freeze the conditions, count the units, start the walk.+ */+export const evaluationsBackfillsCreateBodyConditionsItemIdMax = 100++export const evaluationsBackfillsCreateBodyConditionsItemRolloutPercentageDefault = 100+export const evaluationsBackfillsCreateBodyConditionsItemRolloutPercentageMin = 0+export const evaluationsBackfillsCreateBodyConditionsItemRolloutPercentageMax = 100++export const evaluationsBackfillsCreateBodyRerunExistingDefault = false++export const EvaluationsBackfillsCreateBody = /* @__PURE__ */ zod.object({+ window_start: zod.iso.datetime({ offset: true }).describe('Inclusive start of the window, by unit timestamp.'),+ window_end: zod.iso+ .datetime({ offset: true })+ .describe('Exclusive end of the window. Values in the future are clamped to now.'),+ conditions: zod+ .array(+ zod+ .object({+ id: zod+ .string()+ .max(evaluationsBackfillsCreateBodyConditionsItemIdMax)+ .describe('Stable identifier for this condition set.'),+ rollout_percentage: zod+ .number()+ .min(evaluationsBackfillsCreateBodyConditionsItemRolloutPercentageMin)+ .max(evaluationsBackfillsCreateBodyConditionsItemRolloutPercentageMax)+ .default(evaluationsBackfillsCreateBodyConditionsItemRolloutPercentageDefault)+ .describe(+ 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ ),+ properties: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe(+ 'Property filters (event or person) that scope which generations match this condition set.'+ ),+ })+ .describe('A trigger condition set controlling which generations an evaluation runs on.')+ )+ .optional()+ .describe("Condition sets to match. Defaults to the evaluation's own condition sets."),+ rerun_existing: zod+ .boolean()+ .default(evaluationsBackfillsCreateBodyRerunExistingDefault)+ .describe('Evaluate units again even when this evaluation already has a result for them.'),+})++/**+ * Count what a backfill over the given window would evaluate, without creating one.+ */+export const evaluationsBackfillsEstimateCreateBodyConditionsItemIdMax = 100++export const evaluationsBackfillsEstimateCreateBodyConditionsItemRolloutPercentageDefault = 100+export const evaluationsBackfillsEstimateCreateBodyConditionsItemRolloutPercentageMin = 0+export const evaluationsBackfillsEstimateCreateBodyConditionsItemRolloutPercentageMax = 100++export const evaluationsBackfillsEstimateCreateBodyRerunExistingDefault = false++export const EvaluationsBackfillsEstimateCreateBody = /* @__PURE__ */ zod.object({+ window_start: zod.iso.datetime({ offset: true }).describe('Inclusive start of the window, by unit timestamp.'),+ window_end: zod.iso+ .datetime({ offset: true })+ .describe('Exclusive end of the window. Values in the future are clamped to now.'),+ conditions: zod+ .array(+ zod+ .object({+ id: zod+ .string()+ .max(evaluationsBackfillsEstimateCreateBodyConditionsItemIdMax)+ .describe('Stable identifier for this condition set.'),+ rollout_percentage: zod+ .number()+ .min(evaluationsBackfillsEstimateCreateBodyConditionsItemRolloutPercentageMin)+ .max(evaluationsBackfillsEstimateCreateBodyConditionsItemRolloutPercentageMax)+ .default(evaluationsBackfillsEstimateCreateBodyConditionsItemRolloutPercentageDefault)+ .describe(+ 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ ),+ properties: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe(+ 'Property filters (event or person) that scope which generations match this condition set.'+ ),+ })+ .describe('A trigger condition set controlling which generations an evaluation runs on.')+ )+ .optional()+ .describe("Condition sets to match. Defaults to the evaluation's own condition sets."),+ rerun_existing: zod+ .boolean()+ .default(evaluationsBackfillsEstimateCreateBodyRerunExistingDefault)+ .describe('Evaluate units again even when this evaluation already has a result for them.'),+})+export const evaluationsUpdateBodyNameMax = 400export const evaluationsUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.tsindex 07a93e654d99..8b5a655c07e8 100644--- a/products/ai_observability/frontend/utils.test.ts+++ b/products/ai_observability/frontend/utils.test.ts@@ -1,5 +1,7 @@import { RecipeNormalizer } from '@posthog/llm-normalizer'+import api from 'lib/api'+import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import { AnthropicInputMessage, CompatMessage, OpenAICompletionMessage } from './types'@@ -14,6 +16,7 @@ import {getSessionID,getSessionStartTimestamp,getSummarizationLookupDateRange,+ queryEvaluationRuns,hasCostBreakdown,hasStringContentField,isEmptyJSONStructure,@@ -2960,3 +2963,23 @@ describe.each(IMPLS)('AI observability utils [$name]', ({ normalizeMessage, norm})})})++describe('queryEvaluationRuns', () => {+ const queryHogQL = jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [] } as any)++ afterEach(() => queryHogQL.mockClear())++ it('narrows to one backfill as SQL rather than as a string', async () => {+ await queryEvaluationRuns({ evaluationId: 'eval-1', backfillId: 'run-1' })++ // A nested hogql template would arrive escaped as a value and fail to parse, so assert+ // the clause reached the query as SQL.+ expect(queryHogQL.mock.calls[0][0]).toContain("AND properties.$ai_evaluation_backfill_id = 'run-1'")+ })++ it('leaves the runs unfiltered when no backfill is given', async () => {+ await queryEvaluationRuns({ evaluationId: 'eval-1' })++ expect(queryHogQL.mock.calls[0][0]).not.toContain('$ai_evaluation_backfill_id')+ })+})diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.tsindex ced5141272f7..d0f3d50267e4 100644--- a/products/ai_observability/frontend/utils.ts+++ b/products/ai_observability/frontend/utils.ts@@ -5,7 +5,7 @@ import { dayjs } from 'lib/dayjs'import { isObject, isString } from 'lib/utils/guards'import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'-import { hogql } from '~/queries/utils'+import { escapeHogQLString, hogql } from '~/queries/utils'import type { SpanAggregation } from './aiObservabilityTraceDataLogic'import {@@ -1240,12 +1240,13 @@ export async function queryEvaluationRuns(params: {evaluationId?: stringtraceId?: stringsessionId?: string+ backfillId?: string/** Bounds the scan so it can prune partitions. Omitted for the trace and generation surfaces,* which read a single unit's runs and have always been unbounded. */lookbackDays?: numberforceRefresh?: boolean}): Promise<EvaluationRun[]> {- const { evaluationId, traceId, sessionId, lookbackDays, forceRefresh } = params+ const { evaluationId, traceId, sessionId, backfillId, lookbackDays, forceRefresh } = paramsconst propertyValue = evaluationId || traceId || sessionId@@ -1279,6 +1280,7 @@ export async function queryEvaluationRuns(params: {WHEREevent = '$ai_evaluation'AND ${hogql.raw(`properties.${propertyName}`)} = ${propertyValue}+ ${backfillId ? hogql.raw(`AND properties.$ai_evaluation_backfill_id = ${escapeHogQLString(backfillId)}`) : hogql.raw('')}${lookbackDays ? hogql.raw(`AND timestamp >= now() - INTERVAL ${Math.floor(lookbackDays)} DAY`) : hogql.raw('')}ORDER BY timestamp DESCLIMIT ${EVALUATION_RUNS_QUERY_LIMIT}@@ -1306,9 +1308,10 @@ export interface EvaluationRunsStats {export async function queryEvaluationRunsStats(params: {evaluationId?: stringtraceId?: string+ backfillId?: stringforceRefresh?: boolean}): Promise<EvaluationRunsStats> {- const { evaluationId, traceId, forceRefresh } = params+ const { evaluationId, traceId, backfillId, forceRefresh } = paramsconst propertyValue = evaluationId || traceId@@ -1327,6 +1330,7 @@ export async function queryEvaluationRunsStats(params: {WHEREevent = '$ai_evaluation'AND ${hogql.raw(`properties.${propertyName}`)} = ${propertyValue}+ ${backfillId ? hogql.raw(`AND properties.$ai_evaluation_backfill_id = ${escapeHogQLString(backfillId)}`) : hogql.raw('')}`const response = await api.queryHogQL(diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yamlindex 9f5315970e1d..61d90e78304c 100644--- a/products/ai_observability/mcp/tools.yaml+++ b/products/ai_observability/mcp/tools.yaml@@ -32,6 +32,21 @@ tools:datasets-exports-retrieve:operation: datasets_exports_retrieveenabled: false+ evaluations-backfills-cancel-create:+ operation: evaluations_backfills_cancel_create+ enabled: false+ evaluations-backfills-create:+ operation: evaluations_backfills_create+ enabled: false+ evaluations-backfills-estimate-create:+ operation: evaluations_backfills_estimate_create+ enabled: false+ evaluations-backfills-list:+ operation: evaluations_backfills_list+ enabled: false+ evaluations-backfills-retrieve:+ operation: evaluations_backfills_retrieve+ enabled: falsellm-analytics-offline-evaluations-experiment-items-create:operation: llm_analytics_offline_evaluations_experiment_items_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ef9d19b8f3e7..6b77b53d4ab1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -35752,6 +35752,98 @@ export namespace Schemas {readonly user_access_level: string | null;}+ /**+ * * `running` - Running+ * * `completed` - Completed+ * * `cancelled` - Cancelled+ */+ export type EvaluationBackfillStatusEnum = typeof EvaluationBackfillStatusEnum[keyof typeof EvaluationBackfillStatusEnum];+++ export const EvaluationBackfillStatusEnum = {+ Running: 'running',+ Completed: 'completed',+ Cancelled: 'cancelled',+ } as const;++ export type EvaluationBackfillConditionPropertiesItem = { [key: string]: unknown };++ /**+ * One condition set as it was frozen onto the backfill: no id, no compiled bytecode.+ */+ export interface EvaluationBackfillCondition {+ /** Property filters (event or person) that scope which units match this condition set. */+ properties?: EvaluationBackfillConditionPropertiesItem[];+ /** Percentage (0-100) of matching units sampled for this condition set. */+ rollout_percentage?: number;+ }++ export interface EvaluationBackfill {+ /** Backfill identifier. */+ readonly id: string;+ /** running while the walk is dispatching, then completed or cancelled.+ *+ * * `running` - Running+ * * `completed` - Completed+ * * `cancelled` - Cancelled */+ readonly status: EvaluationBackfillStatusEnum;+ /** What one unit is, frozen at creation: a generation, a trace, or a session.+ *+ * * `generation` - Generation+ * * `trace` - Trace+ * * `session` - Session */+ readonly target: EvaluationTargetEnum;+ /** Inclusive start of the window, by unit timestamp. */+ readonly window_start: string;+ /** Exclusive end of the window. */+ readonly window_end: string;+ /** Condition sets frozen at creation, so an edit to the evaluation does not change this run. */+ readonly conditions: readonly EvaluationBackfillCondition[];+ /** Whether units with an existing result are evaluated again. */+ readonly rerun_existing: boolean;+ /** Units matched at creation; the ceiling on dispatched_count. */+ readonly total_count: number;+ /** Units the backfill has started an evaluation for so far. */+ readonly dispatched_count: number;+ /** Units the live path had already covered, so nothing was dispatched. */+ readonly skipped_count: number;+ /** User who started the backfill. */+ readonly created_by: UserBasic | null;+ /** When the backfill was created. */+ readonly created_at: string;+ /**+ * When the backfill reached a terminal status; null while it runs.+ * @nullable+ */+ readonly finished_at: string | null;+ }++ export interface EvaluationBackfillEstimate {+ /** Units that would be evaluated. */+ total_units: number;+ /** What one unit is: a generation, a trace, or a session.+ *+ * * `generation` - Generation+ * * `trace` - Trace+ * * `session` - Session */+ unit: EvaluationTargetEnum;+ /** Window start after clamping. */+ window_start: string;+ /** Window end after clamping. */+ window_end: string;+ }++ export interface EvaluationBackfillRequest {+ /** Inclusive start of the window, by unit timestamp. */+ window_start: string;+ /** Exclusive end of the window. Values in the future are clamped to now. */+ window_end: string;+ /** Condition sets to match. Defaults to the evaluation's own condition sets. */+ conditions?: EvaluationCondition[];+ /** Evaluate units again even when this evaluation already has a result for them. */+ rerun_existing?: boolean;+ }+/*** * `unknown` - Unknown* * `ok` - Ok@@ -58856,6 +58948,15 @@ export namespace Schemas {results: ErrorTrackingSymbolSet[];}+ export interface PaginatedEvaluationBackfillList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: EvaluationBackfill[];+ }+export interface PaginatedEvaluationList {count: number;/** @nullable */@@ -102401,6 +102502,17 @@ export namespace Schemas {Sentiment: 'sentiment',} as const;+ export type EvaluationsBackfillsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type EventDefinitionsListParams = {/*** When true, omit events that have been explicitly hidden by a team admin (Enterprise only).