Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(aio): capture product analytics for evaluation backfills (#108219)

Bernat Torres1a2c4ca9b65f
diff --git a/posthog/temporal/ai_observability/evaluation_backfill.py b/posthog/temporal/ai_observability/evaluation_backfill.py
index b4fa042d058c..b3622ddedd41 100644
--- a/posthog/temporal/ai_observability/evaluation_backfill.py
+++ b/posthog/temporal/ai_observability/evaluation_backfill.py
@@ -23,7 +23,9 @@ from temporalio.exceptions import WorkflowAlreadyStartedError, is_cancelled_exce
from temporalio.workflow import ParentClosePolicy
from posthog.dataclasses import frozen
+from posthog.event_usage import groups
from posthog.models.team import Team
+from posthog.ph_client import ph_background_capture
from posthog.sync import database_sync_to_async
from posthog.temporal.ai_observability.evaluation_event_io import as_utc_datetime
from posthog.temporal.ai_observability.evaluation_types import EVALUATION_WORKFLOW_PREFIXES
@@ -214,10 +216,55 @@ def cancel_backfill(team_id: int, backfill_id: str | UUID) -> int:
)
+def report_backfill_finished(
+ team_id: int, backfill_id: str, *, status: str | None = None, stop_reason: str | None = None
+) -> None:
+ """Never raises, because a lost analytics event must not fail the activity that ends the run."""
+ try:
+ row = (
+ EvaluationBackfill.objects.for_team(team_id)
+ .select_related("evaluation", "created_by", "team__organization")
+ .get(pk=backfill_id)
+ )
+ if status is None and row.status != EvaluationBackfillStatus.COMPLETED:
+ return
+ finished_at = row.finished_at or timezone.now()
+ ph_background_capture()(
+ distinct_id=(row.created_by.distinct_id if row.created_by else None) or str(row.team.uuid),
+ event="llma evaluation backfill finished",
+ properties={
+ "backfill_id": str(row.pk),
+ "evaluation_id": str(row.evaluation_id),
+ # Failed and stopped runs are both stored as cancelled, so only the caller can tell them apart.
+ "status": status or row.status,
+ "stop_reason": stop_reason,
+ "target": row.target,
+ "evaluation_type": row.evaluation.evaluation_type,
+ "rerun_existing": row.rerun_existing,
+ "total_count": row.total_count,
+ "dispatched_count": row.dispatched_count,
+ "skipped_count": row.skipped_count,
+ "failed_count": row.failed_count,
+ "remaining_count": row.remaining_count,
+ # Each dispatched evaluation emits one billed $ai_evaluation event.
+ "billed_evaluations": row.dispatched_count,
+ "duration_seconds": (finished_at - row.created_at).total_seconds(),
+ },
+ groups=groups(row.team.organization, row.team),
+ )
+ except Exception:
+ logger.exception("llma.evaluation_backfill_capture_failed", backfill_id=backfill_id, team_id=team_id)
+
+
+def _fail_backfill(inputs: EvaluationBackfillInputs) -> None:
+ if cancel_backfill(inputs.team_id, inputs.backfill_id):
+ report_backfill_finished(inputs.team_id, inputs.backfill_id, status="failed")
+
+
@temporalio.activity.defn
async def fail_evaluation_backfill_activity(inputs: EvaluationBackfillInputs) -> None:
"""Stop a backfill whose ticks keep failing, so the row does not stay RUNNING forever."""
- await database_sync_to_async(cancel_backfill, thread_sensitive=False)(inputs.team_id, inputs.backfill_id)
+ await database_sync_to_async(_fail_backfill, thread_sensitive=False)(inputs)
def _prepare_backfill_tick(inputs: EvaluationBackfillInputs) -> PrepareTickOutput:
@@ -237,7 +284,15 @@ def _prepare_backfill_tick(inputs: EvaluationBackfillInputs) -> PrepareTickOutpu
# backfill too, because nothing would tell the loop the evaluation came back, so holding the
# cursor would leave the row RUNNING and the workflow ticking forever.
if evaluation.deleted or not evaluation.enabled or evaluation.evaluation_type not in EVALUATION_WORKFLOW_PREFIXES:
- cancel_backfill(inputs.team_id, inputs.backfill_id)
+ if cancel_backfill(inputs.team_id, inputs.backfill_id):
+ stop_reason = (
+ "evaluation_deleted"
+ if evaluation.deleted
+ else "evaluation_disabled"
+ if not evaluation.enabled
+ else "unsupported_evaluation_type"
+ )
+ report_backfill_finished(inputs.team_id, inputs.backfill_id, status="stopped", stop_reason=stop_reason)
return PrepareTickOutput(action=TickAction.FINISHED)
return PrepareTickOutput(
@@ -408,9 +463,24 @@ def _measure_backfill_remainder(inputs: MeasureRemainderInputs) -> None:
)
+def _is_last_measure_attempt() -> bool:
+ if not temporalio.activity.in_activity():
+ return True
+ return temporalio.activity.info().attempt >= (ACTIVITY_RETRY_POLICY.maximum_attempts or 0)
+
+
@temporalio.activity.defn
async def measure_evaluation_backfill_remainder_activity(inputs: MeasureRemainderInputs) -> None:
- await database_sync_to_async(_measure_backfill_remainder, thread_sensitive=False)(inputs)
+ report = database_sync_to_async(report_backfill_finished, thread_sensitive=False)
+ try:
+ await database_sync_to_async(_measure_backfill_remainder, thread_sensitive=False)(inputs)
+ except Exception:
+ # The workflow gives up on the count after the last attempt, so the run is reported then,
+ # with no remainder, rather than never.
+ if _is_last_measure_attempt():
+ await report(inputs.team_id, inputs.backfill_id)
+ raise
+ await report(inputs.team_id, inputs.backfill_id)
@temporalio.workflow.defn(name=BACKFILL_WORKFLOW_NAME)
diff --git a/posthog/temporal/ai_observability/test_evaluation_backfill.py b/posthog/temporal/ai_observability/test_evaluation_backfill.py
index 46af86ad9ef8..8809f1f0981f 100644
--- a/posthog/temporal/ai_observability/test_evaluation_backfill.py
+++ b/posthog/temporal/ai_observability/test_evaluation_backfill.py
@@ -1,9 +1,10 @@
import uuid
+import dataclasses
from datetime import UTC, datetime, timedelta
from typing import Any, cast
import pytest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.conf import settings
from django.test import override_settings
@@ -11,10 +12,12 @@ from django.test import override_settings
from asgiref.sync import async_to_sync
from temporalio.common import WorkflowIDReusePolicy
from temporalio.exceptions import ActivityError, CancelledError, WorkflowAlreadyStartedError
+from temporalio.testing import ActivityEnvironment
from temporalio.workflow import ParentClosePolicy
from posthog.models import Organization, Team
from posthog.temporal.ai_observability.evaluation_backfill import (
+ ACTIVITY_RETRY_POLICY,
BACKFILL_MAX_CONSECUTIVE_FAILURES,
MAX_BACKFILL_BATCH_SIZE,
AdvanceCursorInputs,
@@ -47,6 +50,7 @@ from products.ai_observability.backend.models.evaluations import Evaluation
WINDOW_START = datetime(2026, 1, 1, tzinfo=UTC)
WINDOW_END = datetime(2026, 2, 1, tzinfo=UTC)
UNIT_TIMESTAMP = datetime(2026, 1, 15, 12, 0, tzinfo=UTC)
+BACKFILL_MODULE = "posthog.temporal.ai_observability.evaluation_backfill"
class _BackfillMocks:
@@ -438,6 +442,18 @@ def _update_backfill(backfill_data, **fields) -> None:
)
+def _finished_events(capture: MagicMock) -> list[dict]:
+ return [
+ call.kwargs["properties"]
+ for call in capture.return_value.call_args_list
+ if call.kwargs["event"] == "llma evaluation backfill finished"
+ ]
+
+
+def _measure_inputs(backfill_data) -> MeasureRemainderInputs:
+ return MeasureRemainderInputs(backfill_id=str(backfill_data["backfill"].id), team_id=backfill_data["team"].id)
+
+
def _activity_inputs(backfill_data) -> EvaluationBackfillInputs:
return EvaluationBackfillInputs(backfill_id=str(backfill_data["backfill"].id), team_id=backfill_data["team"].id)
@@ -506,6 +522,88 @@ class TestEvaluationBackfillActivities:
backfill_data["backfill"].refresh_from_db()
assert backfill_data["backfill"].remaining_count == expected
+ @pytest.mark.parametrize(
+ "status,reported",
+ [(EvaluationBackfillStatus.COMPLETED, True), (EvaluationBackfillStatus.CANCELLED, False)],
+ )
+ def test_measuring_a_completed_run_reports_it_finished(self, backfill_data, status, reported) -> None:
+ _update_backfill(
+ backfill_data,
+ status=status,
+ dispatched_count=6,
+ skipped_count=1,
+ failed_count=1,
+ finished_at=backfill_data["backfill"].created_at + timedelta(minutes=5),
+ )
+
+ with (
+ patch(
+ f"{BACKFILL_MODULE}.count_backfill_candidates",
+ return_value=BackfillScope(to_evaluate=3, already_judged=0),
+ ),
+ patch(f"{BACKFILL_MODULE}.ph_background_capture") as capture,
+ ):
+ async_to_sync(measure_evaluation_backfill_remainder_activity)(_measure_inputs(backfill_data))
+
+ expected = {
+ "backfill_id": str(backfill_data["backfill"].id),
+ "evaluation_id": str(backfill_data["evaluation"].id),
+ "status": "completed",
+ "target": "generation",
+ "evaluation_type": "hog",
+ "rerun_existing": False,
+ "total_count": 10,
+ "dispatched_count": 6,
+ "skipped_count": 1,
+ "failed_count": 1,
+ "remaining_count": 1,
+ "billed_evaluations": 6,
+ "duration_seconds": 300.0,
+ "stop_reason": None,
+ }
+ assert _finished_events(capture) == ([expected] if reported else [])
+ if reported:
+ assert capture.return_value.call_args.kwargs["groups"]["project"] == str(backfill_data["team"].uuid)
+
+ @pytest.mark.parametrize("attempt,reported", [(1, False), (ACTIVITY_RETRY_POLICY.maximum_attempts, True)])
+ def test_a_count_that_keeps_failing_reports_the_run_without_a_remainder(
+ self, backfill_data, attempt, reported
+ ) -> None:
+ _update_backfill(
+ backfill_data,
+ status=EvaluationBackfillStatus.COMPLETED,
+ finished_at=backfill_data["backfill"].created_at + timedelta(minutes=5),
+ )
+ env = ActivityEnvironment()
+ env.info = dataclasses.replace(env.info, attempt=attempt)
+
+ async def measure() -> None:
+ await env.run(measure_evaluation_backfill_remainder_activity, _measure_inputs(backfill_data))
+
+ with (
+ patch(f"{BACKFILL_MODULE}.count_backfill_candidates", side_effect=RuntimeError("clickhouse down")),
+ patch(f"{BACKFILL_MODULE}.ph_background_capture") as capture,
+ pytest.raises(RuntimeError),
+ ):
+ async_to_sync(measure)()
+
+ events = _finished_events(capture)
+ assert [event["remaining_count"] for event in events] == ([None] if reported else [])
+
+ def test_failing_a_backfill_reports_it_once_as_failed(self, backfill_data) -> None:
+ with patch(f"{BACKFILL_MODULE}.ph_background_capture") as capture:
+ async_to_sync(fail_evaluation_backfill_activity)(_activity_inputs(backfill_data))
+ async_to_sync(fail_evaluation_backfill_activity)(_activity_inputs(backfill_data))
+
+ assert [event["status"] for event in _finished_events(capture)] == ["failed"]
+
+ def test_a_failed_capture_still_fails_the_backfill(self, backfill_data) -> None:
+ with patch(f"{BACKFILL_MODULE}.ph_background_capture", side_effect=RuntimeError("capture down")):
+ async_to_sync(fail_evaluation_backfill_activity)(_activity_inputs(backfill_data))
+
+ backfill_data["backfill"].refresh_from_db()
+ assert backfill_data["backfill"].status == EvaluationBackfillStatus.CANCELLED
+
@pytest.mark.parametrize("status", [EvaluationBackfillStatus.COMPLETED, EvaluationBackfillStatus.CANCELLED, None])
def test_prepare_returns_finished_for_missing_or_terminal_row(self, backfill_data, status) -> None:
inputs = _activity_inputs(backfill_data)
@@ -519,25 +617,30 @@ class TestEvaluationBackfillActivities:
assert result.action == TickAction.FINISHED
@pytest.mark.parametrize(
- "update",
+ "update,stop_reason",
[
- {"deleted": True},
+ ({"deleted": True}, "evaluation_deleted"),
# No workflow id prefix exists for this type, so no child could ever be started.
- {"evaluation_type": "not_a_real_type"},
+ ({"evaluation_type": "not_a_real_type"}, "unsupported_evaluation_type"),
# Nothing tells the loop a paused evaluation came back, so holding the cursor would
# leave the row RUNNING and the workflow ticking forever.
- {"enabled": False},
+ ({"enabled": False}, "evaluation_disabled"),
],
)
- def test_prepare_cancels_the_row_when_the_evaluation_cannot_run(self, backfill_data, update) -> None:
+ def test_prepare_cancels_the_row_when_the_evaluation_cannot_run(self, backfill_data, update, stop_reason) -> None:
Evaluation.objects.filter(pk=backfill_data["evaluation"].id).update(**update)
- result = async_to_sync(prepare_evaluation_backfill_tick_activity)(_activity_inputs(backfill_data))
+ with patch(f"{BACKFILL_MODULE}.ph_background_capture") as capture:
+ result = async_to_sync(prepare_evaluation_backfill_tick_activity)(_activity_inputs(backfill_data))
+ async_to_sync(prepare_evaluation_backfill_tick_activity)(_activity_inputs(backfill_data))
assert result.action == TickAction.FINISHED
backfill_data["backfill"].refresh_from_db()
assert backfill_data["backfill"].status == EvaluationBackfillStatus.CANCELLED
assert backfill_data["backfill"].finished_at is not None
+ assert [(event["status"], event["stop_reason"]) for event in _finished_events(capture)] == [
+ ("stopped", stop_reason)
+ ]
@pytest.mark.parametrize(
"configured,expected",
diff --git a/products/ai_observability/backend/api/evaluation_backfills.py b/products/ai_observability/backend/api/evaluation_backfills.py
index b9fc508b3f9f..3f719de68f4d 100644
--- a/products/ai_observability/backend/api/evaluation_backfills.py
+++ b/products/ai_observability/backend/api/evaluation_backfills.py
@@ -29,6 +29,7 @@ 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.event_usage import report_user_action
from posthog.models.user import User
from posthog.permissions import (
AccessControlPermission,
@@ -47,6 +48,7 @@ from posthog.temporal.ai_observability.evaluation_backfill import (
EvaluationBackfillInputs,
backfill_workflow_id,
cancel_backfill,
+ report_backfill_finished,
settle_horizon,
)
from posthog.temporal.ai_observability.run_aggregate_evaluation import INGESTION_LAG_MARGIN_SECONDS
@@ -465,6 +467,25 @@ class EvaluationBackfillViewSet(
except BaseHogQLError as error:
raise self._condition_rejected(evaluation, error)
+ def _report(self, event: str, properties: dict[str, Any]) -> None:
+ try:
+ report_user_action(self.request.user, event, properties, team=self.team, request=self.request)
+ except Exception:
+ logger.exception("llma.evaluation_backfill_capture_failed", analytics_event=event)
+
+ def _scope_properties(
+ self, evaluation: Evaluation, window: BackfillWindow, rerun_existing: bool, scope: BackfillScope
+ ) -> dict[str, Any]:
+ return {
+ "evaluation_id": str(evaluation.id),
+ "target": evaluation.target,
+ "evaluation_type": evaluation.evaluation_type,
+ "units_to_evaluate": scope.to_evaluate,
+ "units_already_evaluated": scope.already_judged,
+ "window_days": round((window.end - window.start).total_seconds() / 86400, 2),
+ "rerun_existing": rerun_existing,
+ }
+
@extend_schema(
request=EvaluationBackfillRequestSerializer,
responses={200: EvaluationBackfillEstimateSerializer},
@@ -487,6 +508,10 @@ class EvaluationBackfillViewSet(
"window_end": window.end,
}
)
+ self._report(
+ "llma evaluation backfill estimated",
+ self._scope_properties(evaluation, window, data["rerun_existing"], scope),
+ )
return Response(response.data)
def _workflow_is_alive(self, backfill: EvaluationBackfill) -> bool:
@@ -515,7 +540,10 @@ class EvaluationBackfillViewSet(
team_id=self.team_id,
workflow_id=workflow_id,
)
- cancel_backfill(self.team_id, backfill.pk)
+ if cancel_backfill(self.team_id, backfill.pk):
+ report_backfill_finished(
+ self.team_id, str(backfill.pk), status="failed", stop_reason="workflow_not_running"
+ )
return False
def _probe_reads_alive(self, backfill: EvaluationBackfill, workflow_id: str) -> bool:
@@ -619,6 +647,14 @@ class EvaluationBackfillViewSet(
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.")
+ self._report(
+ "llma evaluation backfill started",
+ {
+ **self._scope_properties(evaluation, window, rerun_existing, scope),
+ "backfill_id": str(backfill.id),
+ "total_count": backfill.total_count,
+ },
+ )
return Response(self.get_serializer(backfill).data, status=status.HTTP_201_CREATED)
@extend_schema(request=None, responses={200: EvaluationBackfillSerializer})
@@ -636,4 +672,15 @@ class EvaluationBackfillViewSet(
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()
+ self._report(
+ "llma evaluation backfill cancelled",
+ {
+ "backfill_id": str(backfill.pk),
+ "evaluation_id": str(backfill.evaluation_id),
+ "target": backfill.target,
+ "dispatched_count": backfill.dispatched_count,
+ "skipped_count": backfill.skipped_count,
+ "total_count": backfill.total_count,
+ },
+ )
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.py
index 4d99b4e19ffd..cafd5987a1a9 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_backfills.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_backfills.py
@@ -36,6 +36,7 @@ from products.ai_observability.backend.models.evaluation_backfill import Evaluat
from products.ai_observability.backend.models.evaluations import Evaluation
API_MODULE = "products.ai_observability.backend.api.evaluation_backfills"
+CAPTURE = "posthog.event_usage.posthoganalytics.capture"
def _other_team() -> Team:
@@ -105,6 +106,10 @@ def _scope(to_evaluate: int, already_judged: int = 0) -> BackfillScope:
return BackfillScope(to_evaluate=to_evaluate, already_judged=already_judged)
+def _captured(capture: MagicMock, event: str) -> list[dict]:
+ return [call.kwargs["properties"] for call in capture.call_args_list if call.kwargs["event"] == event]
+
+
def _workflow_not_found() -> RPCError:
return RPCError("workflow not found", RPCStatusCode.NOT_FOUND, b"")
@@ -168,8 +173,9 @@ class TestEvaluationBackfillsApi(APIBaseTest):
throttled = self.client.post(f"{self.url}/estimate/", _body(), format="json")
assert throttled.status_code == status.HTTP_429_TOO_MANY_REQUESTS, throttled.json()
+ @patch(CAPTURE)
@patch(f"{API_MODULE}.count_backfill_candidates", return_value=_scope(42, already_judged=8))
- def test_estimate_counts_without_creating_a_row(self, _count):
+ def test_estimate_counts_without_creating_a_row(self, _count, capture):
response = self.client.post(f"{self.url}/estimate/", _body(), format="json")
assert response.status_code == status.HTTP_200_OK, response.json()
@@ -177,10 +183,30 @@ class TestEvaluationBackfillsApi(APIBaseTest):
assert response.json()["already_evaluated_units"] == 8
assert response.json()["unit"] == "generation"
assert EvaluationBackfill.objects.unscoped().count() == 0
+ [properties] = _captured(capture, "llma evaluation backfill estimated")
+ assert properties == {
+ **properties,
+ "source": "web",
+ "evaluation_id": str(self.evaluation.id),
+ "target": "generation",
+ "evaluation_type": "hog",
+ "units_to_evaluate": 42,
+ "units_already_evaluated": 8,
+ "window_days": 7.0,
+ "rerun_existing": False,
+ }
+
+ @patch(CAPTURE, side_effect=RuntimeError("capture down"))
+ @patch(f"{API_MODULE}.count_backfill_candidates", return_value=_scope(42))
+ def test_a_failed_capture_does_not_fail_the_request(self, _count, _capture):
+ response = self.client.post(f"{self.url}/estimate/", _body(), format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ @patch(CAPTURE)
@patch(f"{API_MODULE}.count_backfill_candidates", return_value=_scope(42))
@patch(f"{API_MODULE}.sync_connect")
- def test_create_freezes_conditions_and_starts_workflow(self, connect, _count):
+ def test_create_freezes_conditions_and_starts_workflow(self, connect, _count, capture):
connect.return_value = _temporal_client()
response = self.client.post(f"{self.url}/", _body(), format="json")
@@ -203,6 +229,17 @@ class TestEvaluationBackfillsApi(APIBaseTest):
assert call.kwargs["id"] == f"llma-evaluation-backfill-{row.id}"
assert call.kwargs["task_queue"] == settings.LLMA_TASK_QUEUE
+ [properties] = _captured(capture, "llma evaluation backfill started")
+ assert properties == {
+ **properties,
+ "source": "web",
+ "backfill_id": str(row.id),
+ "total_count": 42,
+ "units_to_evaluate": 42,
+ "evaluation_type": "hog",
+ "rerun_existing": False,
+ }
+
@patch(f"{API_MODULE}.count_backfill_candidates", return_value=_scope(7))
@patch(f"{API_MODULE}.sync_connect")
def test_create_uses_submitted_conditions_and_rerun_flag(self, connect, _count):
@@ -260,12 +297,21 @@ class TestEvaluationBackfillsApi(APIBaseTest):
connect.return_value = _temporal_client(workflow_status, describe_error)
stale = self._stale_backfill()
- response = self.client.post(f"{self.url}/", _body(), format="json")
+ with patch("posthog.temporal.ai_observability.evaluation_backfill.ph_background_capture") as capture:
+ 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
+ finished = [
+ call.kwargs["properties"]
+ for call in capture.return_value.call_args_list
+ if call.kwargs["event"] == "llma evaluation backfill finished"
+ ]
+ assert [(event["backfill_id"], event["status"], event["stop_reason"]) for event in finished] == [
+ (str(stale.pk), "failed", "workflow_not_running")
+ ]
@patch(f"{API_MODULE}.count_backfill_candidates", return_value=_scope(7))
@patch(f"{API_MODULE}.sync_connect")
@@ -518,7 +564,8 @@ class TestEvaluationBackfillsApi(APIBaseTest):
assert EvaluationBackfill.objects.unscoped().count() == 0
@parameterized.expand(["create", "estimate"])
- def test_a_disabled_evaluation_cannot_be_backfilled(self, case):
+ @patch(CAPTURE)
+ def test_a_disabled_evaluation_cannot_be_backfilled(self, case, capture):
self.evaluation.enabled = False
self.evaluation.save()
path = f"{self.url}/" if case == "create" else f"{self.url}/estimate/"
@@ -528,6 +575,7 @@ class TestEvaluationBackfillsApi(APIBaseTest):
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
+ capture.assert_not_called()
@parameterized.expand(["list", "estimate"])
def test_another_teams_evaluation_is_not_addressable(self, case):
@@ -564,9 +612,10 @@ class TestEvaluationBackfillsApi(APIBaseTest):
assert response.status_code >= 500
assert EvaluationBackfill.objects.unscoped().count() == 0
+ @patch(CAPTURE)
@patch(f"{API_MODULE}.count_backfill_candidates", return_value=_scope(5))
@patch(f"{API_MODULE}.sync_connect")
- def test_create_keeps_the_row_when_the_start_result_is_unknown(self, connect, _count):
+ def test_create_keeps_the_row_when_the_start_result_is_unknown(self, connect, _count, capture):
connect.return_value = _temporal_client()
connect.return_value.start_workflow.side_effect = RuntimeError("stream closed")
@@ -575,9 +624,11 @@ class TestEvaluationBackfillsApi(APIBaseTest):
assert response.status_code >= 500
row = EvaluationBackfill.objects.unscoped().get()
assert row.status == EvaluationBackfillStatus.RUNNING
+ assert _captured(capture, "llma evaluation backfill started") == []
+ @patch(CAPTURE)
@patch(f"{API_MODULE}.sync_connect")
- def test_cancel_marks_terminal_and_is_idempotent(self, connect):
+ def test_cancel_marks_terminal_and_is_idempotent(self, connect, capture):
connect.return_value = _temporal_client()
backfill = self._running_backfill()
@@ -592,6 +643,8 @@ class TestEvaluationBackfillsApi(APIBaseTest):
assert second.status_code == status.HTTP_200_OK
assert second.json()["status"] == EvaluationBackfillStatus.CANCELLED
assert second.json()["finished_at"] == first.json()["finished_at"]
+ [properties] = _captured(capture, "llma evaluation backfill cancelled")
+ assert properties == {**properties, "source": "web", "backfill_id": str(backfill.id), "total_count": 1}
@parameterized.expand(
[
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx
index c7ea878746fb..c185151cd399 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationBackfillsTab.tsx
@@ -130,9 +130,11 @@ export function EvaluationBackfillsTab({
expandBackfill,
collapseBackfill,
loadBackfills,
+ startClicked,
} = useActions(logic)
const confirmStart = (): void => {
+ startClicked()
LemonDialog.open({
title: 'Start this backfill?',
description: estimate ? (
diff --git a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts
index 17753f54aa82..493504bd5f81 100644
--- a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts
@@ -1,6 +1,7 @@
import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { ApiError } from 'lib/api'
import { dayjs } from 'lib/dayjs'
@@ -178,6 +179,31 @@ describe('evaluationBackfillsLogic', () => {
})
})
+ it('reports a view of the tab once when it mounts', async () => {
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+
+ await mountAndSettle()
+
+ expect(capture.mock.calls.filter(([event]) => event === 'llma evaluation backfills tab viewed')).toEqual([
+ ['llma evaluation backfills tab viewed', expect.objectContaining({ evaluation_id: EVALUATION_ID })],
+ ])
+ })
+
+ it('reports a click on Start with the count the user saw', async () => {
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ await mountAndSettle()
+ logic.actions.requestEstimateSuccess(estimate({ total_units: 7 }))
+
+ logic.actions.startClicked()
+
+ expect(capture.mock.calls.filter(([event]) => event === 'llma evaluation backfill start clicked')).toEqual([
+ [
+ 'llma evaluation backfill start clicked',
+ { evaluation_id: EVALUATION_ID, units_to_evaluate: 7, rerun_existing: false },
+ ],
+ ])
+ })
+
it('debounces estimate requests and drops a stale response', async () => {
jest.useFakeTimers()
try {
diff --git a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.ts b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.ts
index e548be2b6b4a..d8f0e9c52eb0 100644
--- a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.ts
@@ -1,4 +1,5 @@
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
import { ApiError } from 'lib/api'
import { dayjs } from 'lib/dayjs'
@@ -194,6 +195,9 @@ export interface evaluationBackfillsLogicActions {
dateFrom: string | null
dateTo: string | null
}
+ startClicked: () => {
+ value: true
+ }
transitionBackfillDone: (id: string) => {
id: string
}
@@ -272,6 +276,7 @@ export const evaluationBackfillsLogic = kea<evaluationBackfillsLogicType>([
setConditions: (conditions: EvaluationConditionSet[]) => ({ conditions }),
seedConditions: (conditions: EvaluationConditionSet[]) => ({ conditions }),
setRerunExisting: (rerunExisting: boolean) => ({ rerunExisting }),
+ startClicked: true,
}),
reducers({
@@ -532,6 +537,14 @@ export const evaluationBackfillsLogic = kea<evaluationBackfillsLogicType>([
setWindowRange: () => actions.requestEstimate(),
setConditions: () => actions.requestEstimate(),
setRerunExisting: () => actions.requestEstimate(),
+ // The estimate reloads on every edit, so this is the step that shows intent to start.
+ startClicked: () => {
+ posthog.capture('llma evaluation backfill start clicked', {
+ evaluation_id: props.evaluationId,
+ units_to_evaluate: values.estimate?.total_units ?? null,
+ rerun_existing: values.rerunExisting,
+ })
+ },
requestEstimate: async (_, breakpoint) => {
const teamId = teamLogic.values.currentTeamId
if (!teamId || !values.windowDateFrom) {
@@ -615,7 +628,13 @@ export const evaluationBackfillsLogic = kea<evaluationBackfillsLogicType>([
}
}),
- afterMount(({ actions, values }) => {
+ afterMount(({ actions, values, props }) => {
+ // Only the Backfills tab mounts this logic, so a mount is a view of the tab.
+ posthog.capture('llma evaluation backfills tab viewed', {
+ evaluation_id: props.evaluationId,
+ evaluation_type: values.evaluation?.evaluation_type,
+ target: values.evaluation?.target,
+ })
actions.loadBackfills()
if (values.evaluation) {
actions.seedConditions(values.evaluation.conditions.map(toBackfillCondition))