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(data-quality): report check create, update, delete and run events (#114929)

Thiago Salvatore557297e7c209
diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.py
index b68db08b4129..b9eb89072f2c 100644
--- a/products/data_quality/backend/presentation/views.py
+++ b/products/data_quality/backend/presentation/views.py
@@ -9,6 +9,7 @@ check -- every trigger hands off to Temporal and returns a suite-run handle to p
from collections import defaultdict
from collections.abc import Mapping, Sequence
from dataclasses import replace
+from enum import StrEnum
from functools import cached_property
from typing import TYPE_CHECKING, Any, ClassVar, cast
from uuid import UUID
@@ -28,6 +29,7 @@ from rest_framework.views import APIView
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
+from posthog.event_usage import report_user_action
from posthog.models import Team, User
from posthog.permissions import APIScopePermission, TeamMemberAccessPermission, get_authenticator_scopes
from posthog.rate_limit import HogQLQueryThrottle
@@ -63,6 +65,23 @@ if TYPE_CHECKING:
from rest_framework.permissions import _SupportsHasPermission
+class _CheckEvent(StrEnum):
+ CREATED = "data quality check created"
+ UPDATED = "data quality check updated"
+ DELETED = "data quality check deleted"
+ RUN = "data quality checks run"
+
+
+class _RunScope(StrEnum):
+ CHECK = "check"
+ SUBJECT = "subject"
+ PROJECT = "project"
+
+
+def _event_properties(check: DataQualityCheck) -> dict[str, Any]:
+ return {"check_type": check.check_type, "subject_type": check.subject_type}
+
+
class _DataQualitySubjectPermission(BasePermission):
def has_permission(self, request: Request, view: APIView) -> bool:
if not isinstance(view, _QualityGatedViewSet):
@@ -317,6 +336,19 @@ class _ProjectQualityViewSet(_QualityGatedViewSet):
if not self._authorized_subject_types(write=request.method not in SAFE_METHODS):
raise PermissionDenied("You need access to warehouse objects or the data catalog to work with checks.")
+ def _report(self, event: _CheckEvent, properties: dict[str, Any]) -> None:
+ report_user_action(
+ self.request.user,
+ event,
+ properties,
+ team=self.team,
+ organization=self.team.organization,
+ request=self.request,
+ )
+
+ def _report_run(self, scope: _RunScope, check_count: int | None = None) -> None:
+ self._report(_CheckEvent.RUN, {"scope": scope, "check_count": check_count})
+
_EDIT_DESCRIPTION = (
"Edit this check in place, including what it asserts (check_type, column_name, config). The "
@@ -519,6 +551,11 @@ class DataQualityCheckViewSet(_ProjectQualityViewSet, viewsets.ModelViewSet):
# the one way to read history that list hides, retrieve 403s and runs/ empties.
if not created and self._last_run_is_hidden(check):
self._redact_last_run(check)
+ if created:
+ self._report(
+ _CheckEvent.CREATED,
+ {**_event_properties(check), "severity": check.severity, "created_source": check.created_source},
+ )
return Response(
self.get_serializer(check).data,
status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,
@@ -536,7 +573,14 @@ class DataQualityCheckViewSet(_ProjectQualityViewSet, viewsets.ModelViewSet):
serializer.context["authorize_check_edit"] = lambda current: self._authorize_check_edit(
current, serializer.validated_data
)
+ previous_check = cast(DataQualityCheck, serializer.instance)
updated_check = cast(DataQualityCheck, serializer.save())
+ changed_fields = sorted(
+ field
+ for field in serializer.validated_data
+ if getattr(previous_check, field, None) != getattr(updated_check, field, None)
+ )
+ self._report(_CheckEvent.UPDATED, {**_event_properties(updated_check), "changed_fields": changed_fields})
if self._last_run_is_hidden(updated_check):
self._redact_last_run(updated_check)
@@ -554,6 +598,7 @@ class DataQualityCheckViewSet(_ProjectQualityViewSet, viewsets.ModelViewSet):
def perform_destroy(self, instance: DataQualityCheck) -> None:
api.soft_delete_check(instance)
+ self._report(_CheckEvent.DELETED, _event_properties(instance))
@extend_schema(
description="Run this check now. Returns the suite run to poll for the report.",
@@ -576,6 +621,7 @@ class DataQualityCheckViewSet(_ProjectQualityViewSet, viewsets.ModelViewSet):
subject_uuids=[subject.subject_uuid] if subject else [],
check_ids=[str(check.id)],
)
+ self._report_run(_RunScope.CHECK, check_count=1)
return Response(DataQualitySuiteRunSerializer(suite_run).data)
@extend_schema(
@@ -858,7 +904,9 @@ class DataQualityRunViewSet(
requested = [str(check_id) for check_id in serializer.validated_data.get("check_ids") or []]
subject = self._optional_subject(serializer.validated_data)
if subject is not None and not requested:
- return Response(self._run_subject(subject, cast(User, request.user)))
+ suite = self._run_subject(subject, cast(User, request.user))
+ self._report_run(_RunScope.SUBJECT)
+ return Response(suite)
runnable = api.live_subject_checks(
DataQualityCheck.objects.for_team(self.team_id).filter(deleted=False, enabled=True)
@@ -878,6 +926,7 @@ class DataQualityRunViewSet(
user=cast(User, request.user),
check_ids=[str(check.id) for check in checks],
)
+ self._report_run(_RunScope.CHECK if requested else _RunScope.PROJECT, check_count=len(checks))
return Response(DataQualitySuiteRunSerializer(suite_run).data)
def _run_subject(self, subject: api.SubjectIdentity, user: User) -> dict:
diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.py
index aba1b419c406..72498fea1142 100644
--- a/products/data_quality/backend/tests/test_api.py
+++ b/products/data_quality/backend/tests/test_api.py
@@ -17,6 +17,7 @@ from posthog.hogql.database.database import Database
from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog, Detail, log_activity
+from posthog.models.organization import Organization
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -43,6 +44,7 @@ from .schedule_helpers import schedule_client
START_SUITE = "products.data_quality.backend.logic.checks.sync_connect"
FLAG = "products.data_quality.backend.presentation.views.is_data_quality_checks_enabled"
+REPORT_USER_ACTION = "products.data_quality.backend.presentation.views.report_user_action"
class TestMetricCheckAPI(APIBaseTest):
@@ -642,6 +644,77 @@ class TestDataQualityCheckAPI(APIBaseTest):
assert entry is not None
assert entry.activity == "deleted"
+ @parameterized.expand(
+ [
+ (
+ "create",
+ lambda self, check: self.client.post(f"{self.url}/", self._payload(check_type=CheckType.UNIQUE)),
+ "data quality check created",
+ {"check_type": "unique", "subject_type": "view", "severity": "error", "created_source": "user"},
+ ),
+ (
+ "update",
+ lambda self, check: self.client.patch(
+ f"{self.url}/{check.id}/", {"description": "why", "severity": CheckSeverity.ERROR}
+ ),
+ "data quality check updated",
+ {"check_type": "not_null", "subject_type": "view", "changed_fields": ["description"]},
+ ),
+ (
+ "delete",
+ lambda self, check: self.client.delete(f"{self.url}/{check.id}/"),
+ "data quality check deleted",
+ {"check_type": "not_null", "subject_type": "view"},
+ ),
+ (
+ "run_one_check",
+ lambda self, check: self.client.post(f"{self.url}/{check.id}/run/"),
+ "data quality checks run",
+ {"scope": "check", "check_count": 1},
+ ),
+ (
+ "run_subject",
+ lambda self, check: self.client.post(f"{self.suites_url}/", self.subject),
+ "data quality checks run",
+ {"scope": "subject"},
+ ),
+ (
+ "run_project",
+ lambda self, check: self.client.post(f"{self.suites_url}/", {}),
+ "data quality checks run",
+ {"scope": "project", "check_count": 1},
+ ),
+ ]
+ )
+ def test_check_actions_are_reported(self, _name, act, event, expected_properties) -> None:
+ check = self._create_check()
+ with (
+ patch(REPORT_USER_ACTION) as report,
+ patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())),
+ ):
+ response = act(self, check)
+
+ assert response.status_code < 300, response.content
+ report.assert_called_once()
+ assert report.call_args.args[1] == event
+ properties = report.call_args.args[2]
+ assert {key: properties.get(key) for key in expected_properties} == expected_properties
+
+ def test_check_events_belong_to_the_projects_organization(self) -> None:
+ Organization.objects.bootstrap(self.user)
+ with patch("posthog.event_usage.posthoganalytics.capture") as capture:
+ self._create_check()
+
+ assert capture.call_args.kwargs["groups"]["organization"] == str(self.organization.id)
+
+ def test_recreating_an_existing_check_reports_nothing(self) -> None:
+ self._create_check()
+ with patch(REPORT_USER_ACTION) as report:
+ response = self.client.post(f"{self.url}/", self._payload())
+
+ assert response.status_code == status.HTTP_200_OK
+ report.assert_not_called()
+
def _subject_query(self, subject_uuid, subject_type: str = SubjectType.VIEW) -> str:
return f"subject_type={subject_type}&subject_uuid={subject_uuid}"