: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): instrument user-facing events for GA (#74444)
coryslater65a686dcfd1f
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex 74a30afa4df7..ba07b7b29dcb 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -25,6 +25,7 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.streaming import sse_streaming_response+from posthog.event_usage import report_user_actionfrom posthog.models.user import Userfrom posthog.renderers import ServerSentEventRendererfrom posthog.utils import relative_date_parse@@ -42,6 +43,7 @@ from products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.error_kinds import ERROR_REASON_HELP_TEXTfrom products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermissionfrom products.replay_vision.backend.models.replay_observation import (+ IN_FLIGHT_STATUSES,ObservationStatus,ObservationTrigger,ReplayObservation,@@ -701,7 +703,22 @@ class ReplayObservationViewSet(def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:observation = self.get_object()context = {**self.get_serializer_context(), "neighbors": self._observation_neighbors(observation)}- return Response(self.get_serializer(observation, context=context).data)+ response = Response(self.get_serializer(observation, context=context).data)+ # Viewed step of the created → viewed → rated funnel. In-flight observations are excluded+ # because the observation scene polls this endpoint every few seconds while a scan runs.+ if observation.status not in IN_FLIGHT_STATUSES:+ report_user_action(+ cast(User, request.user),+ "replay_vision_observation_viewed",+ {+ "observation_id": str(observation.id),+ "scanner_id": str(observation.scanner_id),+ "status": observation.status,+ },+ team=self.team,+ request=request,+ )+ return responsedef _observation_neighbors(self, observation: ReplayObservation) -> dict[str, uuid.UUID | None]:# Neighbors honor the same filters and ordering as the scanner's list endpoint, so prev/next@@ -921,6 +938,19 @@ class ReplayObservationViewSet("created_by": user,},)+ # The core quality/calibration signal: thumbs up/down on whether the scanner got the session right.+ report_user_action(+ user,+ "replay_vision_observation_rated",+ {+ "observation_id": str(observation.id),+ "scanner_id": str(observation.scanner_id),+ "is_correct": label.is_correct,+ "has_feedback": bool(label.feedback),+ },+ team=self.team,+ request=request,+ )return Response(ReplayObservationLabelSerializer(label).data)diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 032997cd5b24..32f502b28cc3 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -21,6 +21,7 @@ from posthog.schema import RecordingsQueryfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import report_user_action+from posthog.exceptions import QuotaLimitExceededfrom posthog.models.user import Userfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixin@@ -488,10 +489,18 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode# Flag-gated so teams without the actions feature don't accrue synthesis runs they can't see.if is_replay_vision_actions_enabled(user, team):provision_scanner_digest(scanner, user)- report_user_action(user, "replay vision scanner created", _scanner_lifecycle_properties(scanner), team=team)+ report_user_action(+ user,+ "replay_vision_scanner_created",+ _scanner_lifecycle_properties(scanner),+ team=team,+ request=self.context["request"],+ )return scannerdef update(self, instance: ReplayScanner, validated_data: dict[str, Any]) -> ReplayScanner:+ # The UI PATCHes the whole form on save, so edits are detected by comparing values, not keys.+ before = {field: getattr(instance, field) for field in validated_data}was_enabled = instance.enabledtry:scanner = super().update(instance, validated_data)@@ -504,12 +513,26 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode)if needs_refresh:_refresh_estimate_fail_soft(scanner)+ changed_fields = sorted(field for field, value in before.items() if getattr(scanner, field) != value)+ request = self.context["request"]+ user = cast(User, request.user)+ team = self.context["get_team"]()if scanner.enabled != was_enabled:report_user_action(- cast(User, self.context["request"].user),- "replay vision scanner enabled" if scanner.enabled else "replay vision scanner disabled",+ user,+ "replay_vision_scanner_enabled" if scanner.enabled else "replay_vision_scanner_disabled",_scanner_lifecycle_properties(scanner),- team=self.context["get_team"](),+ team=team,+ request=request,+ )+ # A pure enable/disable toggle is not a config edit. A save that also flips enabled fires both events.+ if any(field != "enabled" for field in changed_fields):+ report_user_action(+ user,+ "replay_vision_scanner_edited",+ {**_scanner_lifecycle_properties(scanner), "edited_fields": changed_fields},+ team=team,+ request=request,)return scanner@@ -1044,6 +1067,30 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, videf safely_get_queryset(self, queryset: QuerySet[ReplayScanner]) -> QuerySet[ReplayScanner]:return queryset.filter(team_id=self.team_id).select_related("created_by").order_by("name", "id")+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ response = super().retrieve(request, *args, **kwargs)+ # Funnel entry point (created → viewed → rated).+ report_user_action(+ cast(User, request.user),+ "replay_vision_scanner_viewed",+ {"scanner_id": str(response.data["id"])},+ team=self.team,+ request=request,+ )+ return response++ def perform_destroy(self, instance: ReplayScanner) -> None:+ # Snapshot lifecycle props before the row is deleted.+ properties = _scanner_lifecycle_properties(instance)+ super().perform_destroy(instance)+ report_user_action(+ cast(User, self.request.user),+ "replay_vision_scanner_deleted",+ properties,+ team=self.team,+ request=self.request,+ )+@extend_schema(responses={200: ScannerCreatorsResponseSerializer})@action(detail=False, methods=["get"], pagination_class=None)def creators(self, request: Request, **kwargs: Any) -> Response:@@ -1092,17 +1139,21 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, videf observe(self, request: Request, **kwargs: Any) -> Response:"""Apply this scanner to one specific session, on demand. Returns 202 with the workflow handle."""scanner = self.get_object()+ user = cast(User, request.user)# Observation output exposes recording contents, so observe requires session_recording read.if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):raise PermissionDenied("Triggering an on-demand observation requires session_recording read access.")- check_observation_quota(self.team.organization_id, observation_credits_for_model(scanner.model))+ try:+ check_observation_quota(self.team.organization_id, observation_credits_for_model(scanner.model))+ except QuotaLimitExceeded:+ self._report_quota_exhausted(scanner, "on_demand")+ raisecheck_team_in_flight_capacity(self.team.id)body = ObserveRequestSerializer(data=request.data)body.is_valid(raise_exception=True)session_id: str = body.validated_data["session_id"]- user = cast(User, request.user)workflow_id, outcome = start_apply_scanner_workflow(scanner, session_id, triggered_by_user_id=user.id, trigger=ObservationTrigger.ON_DEMAND@@ -1116,6 +1167,17 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vistatus=status.HTTP_503_SERVICE_UNAVAILABLE,)+ report_user_action(+ user,+ "replay_vision_scan_requested_on_demand",+ {+ "scanner_id": str(scanner.id),+ "scanner_type": scanner.scanner_type,+ "model": scanner.model,+ },+ team=self.team,+ request=request,+ )return Response(ObserveResponseSerializer({"workflow_id": workflow_id}).data,status=status.HTTP_202_ACCEPTED,@@ -1180,11 +1242,41 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vielse:results.append({"session_id": session_id, "scan_outcome": "failed"})+ report_user_action(+ user,+ "replay_vision_bulk_scan_started",+ {+ "scanner_id": str(scanner.id),+ "scanner_type": scanner.scanner_type,+ "requested": len(session_ids),+ "started": started,+ },+ team=self.team,+ request=request,+ )+ # Key off the outcomes, not skip_reason: skip_reason only names the limit that would bind+ # first, and a batch that never reached the cap must not report exhaustion.+ if any(result["scan_outcome"] == "skipped_quota" for result in results):+ self._report_quota_exhausted(scanner, "bulk")return Response(BulkObserveResponseSerializer({"started": started, "results": results}).data,status=status.HTTP_202_ACCEPTED,)+ def _report_quota_exhausted(self, scanner: ReplayScanner, trigger: str) -> None:+ """A scan was blocked or capped by the org's monthly Replay vision credit limit."""+ report_user_action(+ cast(User, self.request.user),+ "replay_vision_quota_exhausted",+ {+ "scanner_id": str(scanner.id),+ "scanner_type": scanner.scanner_type,+ "trigger": trigger,+ },+ team=self.team,+ request=self.request,+ )+def _bulk_observe_headroom(self, scanner: ReplayScanner) -> tuple[int, str, int, int]:"""(max_starts, skip_reason, team_rows, scanner_rows): how many new scans can start, thereason once that's used up, and the row counts reused by the per-start slot claims."""@@ -1270,6 +1362,19 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi)except ValueError as exc:raise ValidationError(str(exc)) from exc+ report_user_action(+ cast(User, request.user),+ "replay_vision_affected_cohort_created",+ {+ "scanner_id": str(scanner.id),+ "scanner_type": scanner.scanner_type,+ "cohort_id": cohort.id,+ "users_in_cohort": inserted,+ "window_days": window_days,+ },+ team=self.team,+ request=request,+ )return Response(AffectedCohortResponseSerializer({diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 1750178a6bac..f030fa49a18e 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -685,9 +685,9 @@ class TestReplayScannerViewSet(_VisionAPITestCase):class TestScannerLifecycleTelemetry(_VisionAPITestCase):def test_create_reports_config_choices(self) -> None:- # Launch dashboards read these to see whether the 100%/comprehensive defaults get changed;- # dropped properties or a silent non-fire makes that read a lie.- with patch("products.replay_vision.backend.api.scanners.report_user_action") as report:+ # Launch dashboards read these config choices, so a dropped property or a silent non-fire+ # makes that read a lie. Asserted at the capture boundary, where the source tag lands.+ with patch("posthoganalytics.capture") as capture:resp = self.client.post(self.scanners_url,data={@@ -702,21 +702,27 @@ class TestScannerLifecycleTelemetry(_VisionAPITestCase):)self.assertEqual(resp.status_code, 201, resp.json())- report.assert_called_once()- event, properties = report.call_args.args[1], report.call_args.args[2]- self.assertEqual(event, "replay vision scanner created")+ created = [+ call for call in capture.call_args_list if call.kwargs.get("event") == "replay_vision_scanner_created"+ ]+ self.assertEqual(len(created), 1)+ properties = created[0].kwargs["properties"]self.assertEqual(properties["scanner_type"], ScannerType.MONITOR)self.assertEqual(properties["sampling_rate"], 0.25)self.assertTrue(properties["has_filters"])+ self.assertTrue(properties["enabled"])self.assertEqual(properties["organization_id"], str(self.team.organization_id))+ # Session auth resolves to "web" (the app UI), MCP callers to "mcp".+ self.assertEqual(properties["source"], "web")@parameterized.expand([- ("disable", True, False, "replay vision scanner disabled"),- ("enable", False, True, "replay vision scanner enabled"),+ ("disable", True, False, "replay_vision_scanner_disabled"),+ ("enable", False, True, "replay_vision_scanner_enabled"),])def test_enabled_transition_reports_once(self, _name: str, before: bool, after: bool, event: str) -> None:+ # A pure enable/disable toggle fires the transition event only, not the config-edit event.scanner = self._create_scanner(enabled=before)with patch("products.replay_vision.backend.api.scanners.report_user_action") as report:resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data={"enabled": after}, format="json")@@ -725,14 +731,33 @@ class TestScannerLifecycleTelemetry(_VisionAPITestCase):report.assert_called_once()self.assertEqual(report.call_args.args[1], event)- def test_update_without_enabled_transition_reports_nothing(self) -> None:- # A rename must not show up as an enable/disable in the lifecycle funnel.+ @parameterized.expand(+ [+ ("rename", {"name": "renamed"}, ["replay_vision_scanner_edited"]),+ ("no_op", {}, []),+ ]+ )+ def test_full_body_save_reports_only_actually_changed_fields(+ self, _name: str, mutation: dict[str, Any], expected_events: list[str]+ ) -> None:+ # The UI PATCHes the entire form on save, so submitted-but-unchanged fields must not be+ # reported as edits and a save that changes nothing must not fire at all.scanner = self._create_scanner(enabled=True)+ body = {+ "name": scanner.name,+ "scanner_config": scanner.scanner_config,+ "model": scanner.model,+ "sampling_rate": scanner.sampling_rate,+ "enabled": scanner.enabled,+ **mutation,+ }with patch("products.replay_vision.backend.api.scanners.report_user_action") as report:- resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data={"name": "renamed"}, format="json")+ resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data=body, format="json")self.assertEqual(resp.status_code, 200, resp.json())- report.assert_not_called()+ self.assertEqual([call.args[1] for call in report.call_args_list], expected_events)+ if expected_events:+ self.assertEqual(report.call_args.args[2]["edited_fields"], sorted(mutation.keys()))class TestScannerDigestProvisioning(_VisionAPITestCase):@@ -950,6 +975,24 @@ class TestReplayObservationViewSet(_VisionAPITestCase):self.assertIsNone(body["previous_observation_id"])self.assertIsNone(body["next_observation_id"])+ @parameterized.expand(+ [+ ("in_flight_poll_tick", ObservationStatus.PENDING, []),+ ("terminal_result", ObservationStatus.SUCCEEDED, ["replay_vision_observation_viewed"]),+ ]+ )+ def test_retrieve_reports_viewed_only_for_terminal_observations(+ self, _name: str, status_value: ObservationStatus, expected_events: list[str]+ ) -> None:+ # An in-flight fetch is a poll tick (the scene polls every few seconds), not a person viewing results.+ completed_at = timezone.now() if status_value == ObservationStatus.SUCCEEDED else None+ observation = self._create_observation(session_id="viewed", status=status_value, completed_at=completed_at)+ with patch("products.replay_vision.backend.api.observations.report_user_action") as report:+ resp = self.client.get(f"{self.observations_url(str(self.scanner.id))}{observation.id}/")++ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertEqual([call.args[1] for call in report.call_args_list], expected_events)+def test_list_observations_for_scanner(self) -> None:self._create_observation(session_id="s1")self._create_observation(session_id="s2")@@ -1704,6 +1747,25 @@ class TestObserveAction(_VisionAPITestCase):start_workflow.assert_not_called()self.assertFalse(ReplayObservation.objects.filter(scanner=self.scanner, session_id="sess-capped").exists())+ def test_quota_blocked_observe_reports_exhaustion(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # A quota-blocked 402 must still report the exhaustion event.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()++ exhausted = MagicMock(credit_limit=500, period_end=timezone.now())+ with patch("products.replay_vision.backend.api.trigger.compute_quota_snapshot", return_value=exhausted):+ with patch("products.replay_vision.backend.api.scanners.report_user_action") as report:+ resp = self.client.post(+ self.observe_url(str(self.scanner.id)), data={"session_id": "sess-quota"}, format="json"+ )++ self.assertEqual(resp.status_code, 402, resp.json())+ report.assert_called_once()+ self.assertEqual(report.call_args.args[1], "replay_vision_quota_exhausted")+ self.assertEqual(report.call_args.args[2]["trigger"], "on_demand")+@patch("products.replay_vision.backend.api.trigger.async_to_sync")@patch("products.replay_vision.backend.api.trigger.sync_connect")@@ -1780,13 +1842,41 @@ class TestBulkObserveAction(_VisionAPITestCase):# binding limit, so the skip reason must say quota, not in-flight.cost = observation_credits_for_model(self.scanner.model)with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", cost):- resp = self.client.post(- self.bulk_url(str(self.scanner.id)), data={"session_ids": ["p", "q"]}, format="json"- )+ with patch("products.replay_vision.backend.api.scanners.report_user_action") as report:+ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["p", "q"]}, format="json"+ )self.assertEqual(resp.status_code, 202, resp.json())body = resp.json()self.assertEqual(body["started"], 1)self.assertEqual([r["scan_outcome"] for r in body["results"]], ["started", "skipped_quota"])+ events = [call.args[1] for call in report.call_args_list]+ self.assertEqual(events, ["replay_vision_bulk_scan_started", "replay_vision_quota_exhausted"])+ self.assertEqual(report.call_args.args[2]["trigger"], "bulk")++ def test_quota_bound_batch_that_fits_does_not_report_exhaustion(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_sync_connect.return_value = MagicMock()++ def _start(*args: Any, **kwargs: Any) -> None:+ if kwargs["id"] == build_apply_scanner_workflow_id(self.scanner.id, "already"):+ raise WorkflowAlreadyStartedError(workflow_id=kwargs["id"], workflow_type=APPLY_SCANNER_WORKFLOW_NAME)++ mock_async_to_sync.return_value = MagicMock(side_effect=_start)+ # Claims left by earlier tests' mocked starts would shrink the in-flight headroom below the quota.+ get_client().delete(_team_key(self.team.id), _scanner_key(self.scanner.id))+ # Quota is the tighter limit, but the whole batch fits under it: one session is merely+ # already running, so no exhaustion should be reported.+ cost = observation_credits_for_model(self.scanner.model)+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 2 * cost):+ with patch("products.replay_vision.backend.api.scanners.report_user_action") as report:+ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["already", "b"]}, format="json"+ )+ self.assertEqual(resp.status_code, 202, resp.json())+ self.assertEqual([r["scan_outcome"] for r in resp.json()["results"]], ["already_running", "started"])+ self.assertEqual([call.args[1] for call in report.call_args_list], ["replay_vision_bulk_scan_started"])def test_concurrent_claim_exhaustion_maps_to_skipped_limit(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMockdiff --git a/products/replay_vision/backend/tests/test_observation_labels_api.py b/products/replay_vision/backend/tests/test_observation_labels_api.pyindex 453a23832fda..47a9e2fecd76 100644--- a/products/replay_vision/backend/tests/test_observation_labels_api.py+++ b/products/replay_vision/backend/tests/test_observation_labels_api.py@@ -54,6 +54,23 @@ class TestObservationLabels(_VisionAPITestCase):label = self.client.get(self._retrieve_url(self.observation)).json()["label"]self.assertEqual(label, {"is_correct": False, "feedback": "should be yes"})+ def test_rating_reports_calibration_event(self) -> None:+ # The thumb direction, feedback presence, and calling surface must all ride on the event.+ # Asserted at the capture boundary, where the source tag lands.+ with patch("posthoganalytics.capture") as capture:+ resp = self.client.post(+ self._label_url(self.observation), {"is_correct": False, "feedback": "should be yes"}, format="json"+ )+ self.assertEqual(resp.status_code, 200, resp.content)+ rated = [+ call for call in capture.call_args_list if call.kwargs.get("event") == "replay_vision_observation_rated"+ ]+ self.assertEqual(len(rated), 1)+ properties = rated[0].kwargs["properties"]+ self.assertFalse(properties["is_correct"])+ self.assertTrue(properties["has_feedback"])+ self.assertEqual(properties["source"], "web")+def test_product_flag_off_hides_observation_endpoints(self) -> None:with patch("products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled", return_value=False):post_resp = self.client.post(self._label_url(self.observation), {"is_correct": True}, format="json")