: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(replay-vision): count scans that produce no result (#96026)
Arno Hillenab36d033162e
diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.pyindex 50e1072f307d..2dd747fc15ef 100644--- a/products/replay_vision/backend/temporal/activities/observation_state.py+++ b/products/replay_vision/backend/temporal/activities/observation_state.py@@ -47,6 +47,63 @@ def _kind_from_error_reason(error_reason: str, valid_kinds: Container[str]) -> sreturn kind if kind in valid_kinds else "unknown"+# One event per terminal status, so a scan that produced nothing is countable next to+# `replay_vision_scan_completed` instead of only reaching Prometheus.+_TERMINAL_SCAN_EVENTS: dict[str, str] = {+ ObservationStatus.FAILED: "replay_vision_scan_failed",+ ObservationStatus.INELIGIBLE: "replay_vision_scan_ineligible",+}+++def _capture_terminal_scan(*, observation_id: UUID, status: ObservationStatus, scanner_type: str, kind: str) -> None:+ """Internal cross-customer telemetry for a scan that ended with no result.++ `replay_vision_scan_completed` fires only on success, so on its own it is a numerator with no+ denominator: no failure rate is computable for any team, model, or scanner type. The+ human-readable half of `error_reason` stays out, because a provider message can quote session+ content, and `kind` is the enum a rate would be segmented by anyway.+ """+ event = _TERMINAL_SCAN_EVENTS.get(status)+ if event is None:+ return+ obs = ReplayObservation.objects.values(+ "team_id",+ "team__organization_id",+ "team__uuid",+ "scanner_id",+ "triggered_by",+ "scanner_snapshot__model",+ "scanner_snapshot__scanner_version",+ ).get(pk=observation_id)+ posthoganalytics.capture(+ distinct_id=replay_vision_distinct_id(obs["team_id"]),+ event=event,+ # Deterministic dedup key. Exactly one terminal transition ever lands per observation, so+ # sharing the key with `replay_vision_scan_completed` also stops one scan being counted as+ # both a success and a failure.+ uuid=str(observation_id),+ properties={+ "observation_id": str(observation_id),+ "scanner_id": str(obs["scanner_id"]),+ "scanner_type": str(scanner_type),+ "model": obs["scanner_snapshot__model"] or "",+ "triggered_by": obs["triggered_by"],+ "kind": kind,+ # The version that produced this scan, from the snapshot rather than the live scanner, so a+ # later edit cannot retro-attribute a failure to the config that replaced it.+ "scanner_version": obs["scanner_snapshot__scanner_version"],+ "team_id": obs["team_id"],+ "organization_id": str(obs["team__organization_id"]),+ },+ # Mirrors posthog.event_usage.groups() without fetching the Team row.+ groups={+ "instance": SITE_URL,+ "organization": str(obs["team__organization_id"]),+ "project": str(obs["team__uuid"]),+ },+ )++@activity.defn@track_activity()def mark_observation_running_activity(inputs: MarkObservationRunningInputs) -> None:@@ -90,6 +147,12 @@ def mark_observation_terminal(kind=kind,error_reason=error_reason,)+ try:+ _capture_terminal_scan(observation_id=observation_id, status=status, scanner_type=scanner_type, kind=kind)+ except Exception:+ # Fail-soft: the row is already settled, and the transition is sticky, so raising here would+ # retry an activity that has nothing left to do.+ logger.exception("replay_vision.observation.terminal_capture_failed", observation_id=str(observation_id))return True@@ -145,6 +208,7 @@ def mark_observation_succeeded_activity(inputs: MarkObservationSucceededInputs)"triggered_by","created_at","scanner_snapshot__model",+ "scanner_snapshot__scanner_version",).get(pk=inputs.observation_id)model = obs["scanner_snapshot__model"] or ""credits = observation_credits_for_model(model)@@ -189,6 +253,9 @@ def mark_observation_succeeded_activity(inputs: MarkObservationSucceededInputs)"model": model,"credits": credits,"triggered_by": obs["triggered_by"],+ # Pairs with the same property on the failure events, so a failure rate splits by the+ # config that produced it and a prompt edit's effect on quality becomes measurable.+ "scanner_version": obs["scanner_snapshot__scanner_version"],"team_id": obs["team_id"],"organization_id": str(obs["team__organization_id"]),},diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex 4936b2279973..508de484fdb8 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -1206,6 +1206,113 @@ class TestObservationStateActivities:assert ReplayObservationUsage.objects.filter(observation_id=observation.id).count() == 0+ @pytest.mark.parametrize(+ "activity_fn,inputs_cls,error_reason,expected_event,expected_kind",+ [+ (+ mark_observation_failed_activity,+ MarkObservationFailedInputs,+ "provider_rejected:nope",+ "replay_vision_scan_failed",+ "provider_rejected",+ ),+ (+ mark_observation_ineligible_activity,+ MarkObservationIneligibleInputs,+ "too_short:only 5s long",+ "replay_vision_scan_ineligible",+ "too_short",+ ),+ ],+ )+ def test_terminal_scan_telemetry_carries_kind_and_fires_once(+ self, activity_fn, inputs_cls, error_reason: str, expected_event: str, expected_kind: str+ ) -> None:+ # Without these events `replay_vision_scan_completed` is a numerator with no denominator, so no+ # failure rate exists. A retry must not inflate the denominator either.+ scanner = _make_scanner()+ observation = _make_observation(scanner, status=ObservationStatus.RUNNING, started_at=timezone.now())+ inputs = inputs_cls(observation_id=observation.id, error_reason=error_reason, scanner_type=ScannerType.MONITOR)++ with patch(+ "products.replay_vision.backend.temporal.activities.observation_state.posthoganalytics.capture"+ ) as capture:+ activity_fn(inputs)+ activity_fn(inputs) # retry: the transition is sticky, so no second event++ capture.assert_called_once()+ kwargs = capture.call_args.kwargs+ assert kwargs["event"] == expected_event+ assert kwargs["distinct_id"] == f"replay-vision:{observation.team_id}"+ # Shared with the success event, so one scan can never count as both.+ assert kwargs["uuid"] == str(observation.id)+ properties = kwargs["properties"]+ assert properties["kind"] == expected_kind+ assert properties["scanner_type"] == "monitor"+ assert properties["scanner_id"] == str(scanner.id)+ assert properties["scanner_version"] == observation.scanner_snapshot["scanner_version"]+ assert properties["organization_id"] == str(observation.team.organization_id)+ # The message half of `error_reason` can quote session content, so it must not ride along.+ assert error_reason.split(":", 1)[1] not in str(properties)+ assert kwargs["groups"]["project"] == str(observation.team.uuid)++ @pytest.mark.parametrize("status", [ObservationStatus.SUCCEEDED, ObservationStatus.FAILED])+ def test_scan_telemetry_reports_the_version_that_produced_it(self, status: str) -> None:+ # Reading the live scanner instead of the snapshot would retro-attribute every past scan to+ # whatever config replaced it, which inverts the before/after comparison a prompt edit is+ # judged on. The scanner here sits at version 1 while the snapshot says 7.+ scanner = _make_scanner()+ snapshot = {**_snapshot_for(scanner), "scanner_version": 7}+ observation = _make_observation(+ scanner, status=ObservationStatus.RUNNING, started_at=timezone.now(), scanner_snapshot=snapshot+ )+ assert scanner.scanner_version != 7++ with patch(+ "products.replay_vision.backend.temporal.activities.observation_state.posthoganalytics.capture"+ ) as capture:+ if status == ObservationStatus.SUCCEEDED:+ mark_observation_succeeded_activity(+ MarkObservationSucceededInputs(+ observation_id=observation.id,+ scanner_result=ScannerResult(+ model_output=MonitorOutput(verdict="yes", reasoning="ok", confidence=0.9)+ ),+ scanner_type=ScannerType.MONITOR,+ )+ )+ else:+ mark_observation_failed_activity(+ MarkObservationFailedInputs(+ observation_id=observation.id,+ error_reason="internal_error:boom",+ scanner_type=ScannerType.MONITOR,+ )+ )++ assert capture.call_args.kwargs["properties"]["scanner_version"] == 7++ def test_terminal_scan_settles_even_when_telemetry_raises(self) -> None:+ # The row is already settled when the capture runs, and the transition is sticky, so a telemetry+ # outage must not fail the activity into a retry that can no longer do anything.+ scanner = _make_scanner()+ observation = _make_observation(scanner, status=ObservationStatus.RUNNING, started_at=timezone.now())++ with patch(+ "products.replay_vision.backend.temporal.activities.observation_state.posthoganalytics.capture",+ side_effect=RuntimeError("analytics down"),+ ):+ mark_observation_failed_activity(+ MarkObservationFailedInputs(+ observation_id=observation.id,+ error_reason="internal_error:boom",+ scanner_type=ScannerType.MONITOR,+ )+ )++ observation.refresh_from_db()+ assert observation.status == ObservationStatus.FAILED+@pytest.mark.django_db(transaction=True)class TestEmitObservationEventActivity: