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-deletion): add self-service request API (#104278)

Paweł Szczur62e3277de668
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.yml
index 5876beefeb75..b9f65a9e69d9 100644
--- a/.github/workflows/ci-dagster.yml
+++ b/.github/workflows/ci-dagster.yml
@@ -167,6 +167,7 @@ jobs:
- 'posthog/session/**'
- 'posthog/schema.py'
- 'posthog/schema_enums.py' # enum-only schema changes touch only this file
+ - 'posthog/data_deletion.py'
- 'posthog/dataclasses.py'
- 'posthog/utils.py'
- 'posthog/errors.py'
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 4931a18b2575..af627b4d6fbb 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -3718,6 +3718,151 @@ export interface SharingConfigurationApi {
readonly user_access_level: string | null
}
+/**
+ * * `draft` - Draft
+ * * `pending` - Pending
+ * * `approved` - Approved
+ * * `in_progress` - In Progress
+ * * `queued` - Queued
+ * * `completed` - Completed
+ * * `failed` - Failed
+ */
+export type RequestStatusEnumApi = (typeof RequestStatusEnumApi)[keyof typeof RequestStatusEnumApi]
+
+export const RequestStatusEnumApi = {
+ Draft: 'draft',
+ Pending: 'pending',
+ Approved: 'approved',
+ InProgress: 'in_progress',
+ Queued: 'queued',
+ Completed: 'completed',
+ Failed: 'failed',
+} as const
+
+/**
+ * Submitted HogQL variable snapshot.
+ */
+export type DataDeletionRequestApiVariables = {
+ [key: string]: {
+ code_name: string
+ isNull?: boolean | null
+ value?: unknown
+ variableId: string
+ }
+}
+
+export interface DataDeletionRequestApi {
+ /** Deletion request identifier. */
+ readonly id: string
+ /** Current deletion workflow status.
+ *
+ * * `draft` - Draft
+ * * `pending` - Pending
+ * * `approved` - Approved
+ * * `in_progress` - In Progress
+ * * `queued` - Queued
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ readonly status: RequestStatusEnumApi
+ /** Submitted HogQL query snapshot. */
+ readonly query: string
+ /** Submitted HogQL variable snapshot. */
+ readonly variables: DataDeletionRequestApiVariables
+ /**
+ * Client-generated idempotency identifier.
+ * @nullable
+ */
+ readonly submission_id: string | null
+ /**
+ * Number of selected events, when calculated.
+ * @nullable
+ */
+ readonly count: number | null
+ /**
+ * Identifier of the user who submitted the request.
+ * @nullable
+ */
+ readonly created_by_id: number | null
+ /**
+ * Whether the submitter was a PostHog staff user.
+ * @nullable
+ */
+ readonly created_by_staff: boolean | null
+ /** Time when the request was submitted. */
+ readonly created_at: string
+ /** Time when the request last changed. */
+ readonly updated_at: string
+ /**
+ * Time when the request was approved, if approved.
+ * @nullable
+ */
+ readonly approved_at: string | null
+ /**
+ * Time when selection statistics were calculated, if available.
+ * @nullable
+ */
+ readonly stats_calculated_at: string | null
+}
+
+export interface PaginatedDataDeletionRequestListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: DataDeletionRequestApi[]
+}
+
+/**
+ * Variables referenced by the HogQL query.
+ */
+export type DataDeletionRequestCreateApiVariables = {
+ [key: string]: {
+ code_name: string
+ isNull?: boolean | null
+ value?: unknown
+ variableId: string
+ }
+}
+
+export interface DataDeletionRequestCreateApi {
+ /** HogQL query that selects one event UUID column. */
+ query: string
+ /** Variables referenced by the HogQL query. */
+ variables?: DataDeletionRequestCreateApiVariables
+ /** Client-generated identifier that makes request submission idempotent. */
+ submission_id: string
+}
+
+export interface DataDeletionConflictApi {
+ /** Reason the deletion request could not be created in the current state. */
+ readonly detail: string
+}
+
+/**
+ * Variables referenced by the HogQL query.
+ */
+export type DataDeletionRequestInputApiVariables = {
+ [key: string]: {
+ code_name: string
+ isNull?: boolean | null
+ value?: unknown
+ variableId: string
+ }
+}
+
+export interface DataDeletionRequestInputApi {
+ /** HogQL query that selects one event UUID column. */
+ query: string
+ /** Variables referenced by the HogQL query. */
+ variables?: DataDeletionRequestInputApiVariables
+}
+
+export interface DataDeletionPreviewApi {
+ /** Number of event UUIDs selected when the preview ran. */
+ readonly count: number
+}
+
/**
* * `image/png` - image/png
* * `application/pdf` - application/pdf
@@ -5406,6 +5551,17 @@ export type OrganizationsProjectsEventIngestionRestrictionsListParams = {
search?: string
}
+export type DataDeletionRequestsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type ExportsListParams = {
/**
* Number of results to return per page.
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 9c6e8af16a25..5c82965e88e1 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -15,6 +15,11 @@ import type {
CIMDVerificationTokenCreateApi,
CIMDVerificationTokenWithValueApi,
CimdVerificationTokensListParams,
+ DataDeletionPreviewApi,
+ DataDeletionRequestApi,
+ DataDeletionRequestCreateApi,
+ DataDeletionRequestInputApi,
+ DataDeletionRequestsListParams,
DomainsListParams,
DomainsScimLogsRetrieveParams,
EnterprisePropertyDefinitionApi,
@@ -49,6 +54,7 @@ import type {
OrganizationsProjectsEventIngestionRestrictionsListParams,
OrganizationsProjectsListParams,
PaginatedCIMDVerificationTokenListApi,
+ PaginatedDataDeletionRequestListApi,
PaginatedEnterprisePropertyDefinitionListApi,
PaginatedExportedAssetListApi,
PaginatedFileSystemListApi,
@@ -1467,6 +1473,94 @@ export const dashboardsSharingRefreshCreate = async (
})
}
+export const getDataDeletionRequestsListUrl = (projectId: string, params?: DataDeletionRequestsListParams) => {
+ 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}/data_deletion_requests/?${stringifiedParams}`
+ : `/api/projects/${projectId}/data_deletion_requests/`
+}
+
+/**
+ * List self-service event deletion requests for this project.
+ */
+export const dataDeletionRequestsList = async (
+ projectId: string,
+ params?: DataDeletionRequestsListParams,
+ options?: RequestInit
+): Promise<PaginatedDataDeletionRequestListApi> => {
+ return apiMutator<PaginatedDataDeletionRequestListApi>(getDataDeletionRequestsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getDataDeletionRequestsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_deletion_requests/`
+}
+
+/**
+ * Submit a one-column HogQL query for event deletion.
+ */
+export const dataDeletionRequestsCreate = async (
+ projectId: string,
+ dataDeletionRequestCreateApi: DataDeletionRequestCreateApi,
+ options?: RequestInit
+): Promise<DataDeletionRequestApi> => {
+ return apiMutator<DataDeletionRequestApi>(getDataDeletionRequestsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(dataDeletionRequestCreateApi),
+ })
+}
+
+export const getDataDeletionRequestsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/data_deletion_requests/${id}/`
+}
+
+/**
+ * Get one self-service event deletion request for this project.
+ */
+export const dataDeletionRequestsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DataDeletionRequestApi> => {
+ return apiMutator<DataDeletionRequestApi>(getDataDeletionRequestsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getDataDeletionRequestsPreviewCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_deletion_requests/preview/`
+}
+
+/**
+ * Validate a one-column HogQL query and count the selected event UUIDs.
+ */
+export const dataDeletionRequestsPreviewCreate = async (
+ projectId: string,
+ dataDeletionRequestInputApi: DataDeletionRequestInputApi,
+ options?: RequestInit
+): Promise<DataDeletionPreviewApi> => {
+ return apiMutator<DataDeletionPreviewApi>(getDataDeletionRequestsPreviewCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(dataDeletionRequestInputApi),
+ })
+}
+
export const getExportsListUrl = (projectId: string, params?: ExportsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 11c6db357838..7c8cf391bf3d 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -662,6 +662,45 @@ export const DashboardsSharingRefreshCreateBody = /* @__PURE__ */ zod
})
.describe('Mixin for serializers to add user access control fields')
+/**
+ * Submit a one-column HogQL query for event deletion.
+ */
+export const DataDeletionRequestsCreateBody = /* @__PURE__ */ zod.object({
+ query: zod.string().describe('HogQL query that selects one event UUID column.'),
+ variables: zod
+ .record(
+ zod.string(),
+ zod.object({
+ code_name: zod.string(),
+ isNull: zod.union([zod.boolean(), zod.null()]).optional(),
+ value: zod.unknown().optional(),
+ variableId: zod.string(),
+ })
+ )
+ .optional()
+ .describe('Variables referenced by the HogQL query.'),
+ submission_id: zod.uuid().describe('Client-generated identifier that makes request submission idempotent.'),
+})
+
+/**
+ * Validate a one-column HogQL query and count the selected event UUIDs.
+ */
+export const DataDeletionRequestsPreviewCreateBody = /* @__PURE__ */ zod.object({
+ query: zod.string().describe('HogQL query that selects one event UUID column.'),
+ variables: zod
+ .record(
+ zod.string(),
+ zod.object({
+ code_name: zod.string(),
+ isNull: zod.union([zod.boolean(), zod.null()]).optional(),
+ value: zod.unknown().optional(),
+ variableId: zod.string(),
+ })
+ )
+ .optional()
+ .describe('Variables referenced by the HogQL query.'),
+})
+
export const ExportsCreateBody = /* @__PURE__ */ zod
.object({
dashboard: zod.number().nullish(),
diff --git a/posthog/api/data_deletion_request.py b/posthog/api/data_deletion_request.py
new file mode 100644
index 000000000000..e29cdfe0bdc3
--- /dev/null
+++ b/posthog/api/data_deletion_request.py
@@ -0,0 +1,257 @@
+from typing import Any, cast
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+from django.db.models import QuerySet
+
+from drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_view
+from rest_framework import mixins, serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import PermissionDenied, ValidationError
+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 posthog.schema import HogQLVariable
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.data_deletion import (
+ DataDeletionActiveRequestLimit,
+ DataDeletionSubmissionConflict,
+ create_event_deletion_request,
+ preview_event_deletion,
+ validate_payload_size,
+)
+from posthog.models import Team, User
+from posthog.models.data_deletion_request import DataDeletionRequest, RequestType
+from posthog.permissions import posthog_feature_flag_enabled
+from posthog.rate_limit import PersonalApiKeyOrUserRateThrottle
+
+SELF_SERVICE_DATA_DELETION_FLAG = "self-service-data-deletion"
+
+
+class DataDeletionTeamRateThrottle(PersonalApiKeyOrUserRateThrottle):
+ def get_cache_key(self, request: Request, view: APIView) -> str:
+ team_id = self.safely_get_team_id_from_view(view)
+ ident = team_id if team_id is not None else request.user.pk
+ return self.cache_format % {"scope": self.scope, "ident": ident}
+
+
+class DataDeletionCreateThrottle(DataDeletionTeamRateThrottle):
+ scope = "data_deletion_create"
+ rate = "10/hour"
+
+
+class DataDeletionPreviewBurstThrottle(DataDeletionTeamRateThrottle):
+ scope = "data_deletion_preview_burst"
+ rate = "5/minute"
+
+
+class DataDeletionPreviewSustainedThrottle(DataDeletionTeamRateThrottle):
+ scope = "data_deletion_preview_sustained"
+ rate = "30/hour"
+
+
+@extend_schema_field(
+ {
+ "type": "object",
+ "additionalProperties": HogQLVariable.model_json_schema(),
+ }
+)
+class HogQLVariablesField(serializers.JSONField):
+ pass
+
+
+class DataDeletionRequestInputSerializer(serializers.Serializer):
+ query = serializers.CharField(help_text="HogQL query that selects one event UUID column.")
+ variables = HogQLVariablesField(
+ default=dict,
+ help_text="Variables referenced by the HogQL query.",
+ )
+
+ def validate_variables(self, value: object) -> dict[str, object]:
+ if not isinstance(value, dict):
+ raise ValidationError("Query variables must be a JSON object.")
+ return value
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ try:
+ validate_payload_size(attrs["query"], attrs["variables"])
+ except DjangoValidationError as error:
+ raise ValidationError(error.message_dict) from error
+ return attrs
+
+
+class DataDeletionRequestCreateSerializer(DataDeletionRequestInputSerializer):
+ submission_id = serializers.UUIDField(
+ required=True,
+ help_text="Client-generated identifier that makes request submission idempotent.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ attrs = super().validate(attrs)
+ unexpected = set(self.initial_data) - set(self.fields)
+ if unexpected:
+ raise serializers.ValidationError(dict.fromkeys(unexpected, "This field is not accepted."))
+ return attrs
+
+
+class DataDeletionPreviewSerializer(serializers.Serializer):
+ count = serializers.IntegerField(
+ read_only=True,
+ help_text="Number of event UUIDs selected when the preview ran.",
+ )
+
+
+class DataDeletionConflictSerializer(serializers.Serializer):
+ detail = serializers.CharField(
+ read_only=True,
+ help_text="Reason the deletion request could not be created in the current state.",
+ )
+
+
+class DataDeletionRequestSerializer(serializers.ModelSerializer):
+ query = serializers.CharField(source="hogql_query", read_only=True, help_text="Submitted HogQL query snapshot.")
+ variables = HogQLVariablesField(
+ source="hogql_variables",
+ read_only=True,
+ help_text="Submitted HogQL variable snapshot.",
+ )
+ created_by_id = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="Identifier of the user who submitted the request.",
+ )
+
+ class Meta:
+ model = DataDeletionRequest
+ fields = [
+ "id",
+ "status",
+ "query",
+ "variables",
+ "submission_id",
+ "count",
+ "created_by_id",
+ "created_by_staff",
+ "created_at",
+ "updated_at",
+ "approved_at",
+ "stats_calculated_at",
+ ]
+ read_only_fields = fields
+ extra_kwargs = {
+ "id": {"help_text": "Deletion request identifier."},
+ "status": {"help_text": "Current deletion workflow status."},
+ "submission_id": {"help_text": "Client-generated idempotency identifier."},
+ "count": {"help_text": "Number of selected events, when calculated."},
+ "created_by_staff": {"help_text": "Whether the submitter was a PostHog staff user."},
+ "created_at": {"help_text": "Time when the request was submitted."},
+ "updated_at": {"help_text": "Time when the request last changed."},
+ "approved_at": {"help_text": "Time when the request was approved, if approved."},
+ "stats_calculated_at": {"help_text": "Time when selection statistics were calculated, if available."},
+ }
+
+
+@extend_schema_view(
+ list=extend_schema(description="List self-service event deletion requests for this project."),
+ retrieve=extend_schema(description="Get one self-service event deletion request for this project."),
+)
+@extend_schema(extensions={"x-product": "core"})
+class DataDeletionRequestViewSet(
+ TeamAndOrgViewSetMixin,
+ mixins.ListModelMixin,
+ mixins.RetrieveModelMixin,
+ viewsets.GenericViewSet,
+):
+ scope_object = "data_deletion"
+ requires_resource_level_access = True
+ queryset = DataDeletionRequest.objects.all()
+ serializer_class = DataDeletionRequestSerializer
+ http_method_names = ["get", "post", "head", "options"]
+
+ def get_throttles(self) -> list[BaseThrottle]:
+ if self.action == "create":
+ return [DataDeletionCreateThrottle()]
+ return super().get_throttles()
+
+ def initial(self, request: Request, *args: object, **kwargs: object) -> None:
+ super().initial(request, *args, **kwargs)
+ if not self_service_data_deletion_enabled(self.team):
+ raise PermissionDenied("Self-service data deletion is not enabled for this project.")
+
+ def safely_get_queryset(self, queryset: QuerySet[DataDeletionRequest]) -> QuerySet[DataDeletionRequest]:
+ return queryset.filter(request_type=RequestType.HOGQL_EVENT_REMOVAL)
+
+ @validated_request(
+ request_serializer=DataDeletionRequestCreateSerializer,
+ responses={
+ 200: DataDeletionRequestSerializer,
+ 201: DataDeletionRequestSerializer,
+ 409: DataDeletionConflictSerializer,
+ },
+ description="Submit a one-column HogQL query for event deletion.",
+ )
+ def create(self, request: ValidatedRequest, *args: object, **kwargs: object) -> Response:
+ data = request.validated_data
+ try:
+ deletion_request, created = create_event_deletion_request(
+ query=data["query"],
+ variables=data["variables"],
+ submission_id=data["submission_id"],
+ team=self.team,
+ user=cast(User, request.user),
+ )
+ except DjangoValidationError as error:
+ raise ValidationError(error.message_dict) from error
+ except DataDeletionSubmissionConflict:
+ return Response(
+ {"detail": "This submission ID is already used by a different deletion request."},
+ status=status.HTTP_409_CONFLICT,
+ )
+ except DataDeletionActiveRequestLimit:
+ return Response(
+ {"detail": "This project already has the maximum number of active deletion requests."},
+ status=status.HTTP_409_CONFLICT,
+ )
+ return Response(
+ DataDeletionRequestSerializer(deletion_request).data,
+ status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,
+ )
+
+ @validated_request(
+ request_serializer=DataDeletionRequestInputSerializer,
+ description="Validate a one-column HogQL query and count the selected event UUIDs.",
+ responses={200: DataDeletionPreviewSerializer},
+ )
+ @action(
+ methods=["POST"],
+ detail=False,
+ throttle_classes=[DataDeletionPreviewBurstThrottle, DataDeletionPreviewSustainedThrottle],
+ )
+ def preview(self, request: ValidatedRequest, **kwargs: object) -> Response:
+ data = request.validated_data
+ try:
+ count = preview_event_deletion(
+ query=data["query"],
+ variables=data["variables"],
+ team=self.team,
+ user=cast(User, request.user),
+ )
+ except DjangoValidationError as error:
+ raise ValidationError(error.message_dict) from error
+ return Response(DataDeletionPreviewSerializer({"count": count}).data)
+
+
+def self_service_data_deletion_enabled(team: Team) -> bool:
+ try:
+ return posthog_feature_flag_enabled(
+ SELF_SERVICE_DATA_DELETION_FLAG,
+ str(team.uuid),
+ organization_id=team.organization_id,
+ team_id=team.id,
+ only_evaluate_locally=True,
+ )
+ except Exception:
+ return False
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index 2b5f8ed906f7..c106ff3cbfd2 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -2,7 +2,15 @@ from rest_framework import decorators, exceptions
# Preload to work around circular imports in `ee.hogai.{core.agent_modes,chat_agent,tools}`.
import posthog.temporal.ai # noqa: F401
-from posthog.api import data_color_theme, metalytics, my_notifications, project, user_integration, user_push_token
+from posthog.api import (
+ data_color_theme,
+ data_deletion_request,
+ metalytics,
+ my_notifications,
+ project,
+ user_integration,
+ user_push_token,
+)
from posthog.api.csp_reporting import CSPReportingViewSet
from posthog.api.js_snippet import JsSnippetViewSet
from posthog.api.product_enablement import ProductEnablementViewSet
@@ -257,6 +265,12 @@ projects_router.register(
projects_router.register(r"tags", tagged_item.TaggedItemViewSet, "project_tags", ["project_id"])
projects_router.register(r"query", query.QueryViewSet, "project_query", ["team_id"])
+projects_router.register(
+ r"data_deletion_requests",
+ data_deletion_request.DataDeletionRequestViewSet,
+ "project_data_deletion_requests",
+ ["team_id"],
+)
# Organizations nested endpoints
diff --git a/posthog/api/test/test_data_deletion_request.py b/posthog/api/test/test_data_deletion_request.py
new file mode 100644
index 000000000000..f0b29cf37391
--- /dev/null
+++ b/posthog/api/test/test_data_deletion_request.py
@@ -0,0 +1,220 @@
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership, Team
+from posthog.models.data_deletion_request import DataDeletionRequest, ExecutionMode, RequestStatus, RequestType
+
+from products.access_control.backend.models import AccessControl
+
+FEATURE_FLAG = "posthog.api.data_deletion_request.self_service_data_deletion_enabled"
+COMPILE_QUERY = "posthog.data_deletion.compile_event_uuid_query"
+
+
+@patch(FEATURE_FLAG, return_value=True)
+class TestDataDeletionRequestAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save(update_fields=["level"])
+ self.url = f"/api/projects/{self.team.id}/data_deletion_requests"
+
+ @patch(COMPILE_QUERY)
+ def test_create_assigns_server_owned_fields_and_is_idempotent(self, compile_query, _feature_flag) -> None:
+ submission_id = uuid4()
+ payload = {
+ "query": "SELECT uuid FROM events WHERE event = 'checkout'",
+ "variables": {},
+ "submission_id": str(submission_id),
+ }
+
+ first = self.client.post(f"{self.url}/", payload, format="json")
+ second = self.client.post(f"{self.url}/", payload, format="json")
+ conflict = self.client.post(
+ f"{self.url}/",
+ {**payload, "query": "SELECT uuid FROM events WHERE event = 'refund'"},
+ format="json",
+ )
+
+ assert first.status_code == status.HTTP_201_CREATED, first.json()
+ assert second.status_code == status.HTTP_200_OK, second.json()
+ assert conflict.status_code == status.HTTP_409_CONFLICT, conflict.json()
+ assert second.json()["id"] == first.json()["id"]
+ request = DataDeletionRequest.objects.get(id=first.json()["id"])
+ assert request.team_id == self.team.id
+ assert request.created_by == self.user
+ assert request.created_by_staff is self.user.is_staff
+ assert request.request_type == RequestType.HOGQL_EVENT_REMOVAL
+ assert request.execution_mode == ExecutionMode.DEFERRED
+ assert request.status == RequestStatus.PENDING
+ assert request.requires_approval is True
+ assert DataDeletionRequest.objects.filter(team_id=self.team.id).count() == 1
+ compile_query.assert_called_once()
+
+ @patch(COMPILE_QUERY)
+ def test_create_rejects_requests_above_the_active_limit(self, compile_query, _feature_flag) -> None:
+ for _ in range(5):
+ DataDeletionRequest.objects.create(
+ team_id=self.team.id,
+ request_type=RequestType.HOGQL_EVENT_REMOVAL,
+ status=RequestStatus.PENDING,
+ submission_id=uuid4(),
+ )
+
+ response = self.client.post(
+ f"{self.url}/",
+ {
+ "query": "SELECT uuid FROM events",
+ "variables": {},
+ "submission_id": str(uuid4()),
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()
+ assert DataDeletionRequest.objects.filter(team_id=self.team.id).count() == 5
+ compile_query.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("status", RequestStatus.COMPLETED),
+ ("request_type", RequestType.PROPERTY_REMOVAL),
+ ("team_id", 123456),
+ ("execution_mode", ExecutionMode.IMMEDIATE),
+ ]
+ )
+ @patch(COMPILE_QUERY)
+ def test_create_rejects_server_owned_fields(
+ self,
+ field: str,
+ value: object,
+ compile_query: MagicMock,
+ _feature_flag: MagicMock,
+ ) -> None:
+ response = self.client.post(
+ f"{self.url}/",
+ {
+ "query": "SELECT uuid FROM events",
+ "variables": {},
+ "submission_id": str(uuid4()),
+ field: value,
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == field
+ assert response.json()["detail"] == "This field is not accepted."
+ assert DataDeletionRequest.objects.filter(team_id=self.team.id).count() == 0
+ compile_query.assert_not_called()
+
+ def test_list_and_detail_do_not_expose_other_projects(self, _feature_flag) -> None:
+ other_team = Team.objects.create(organization=self.organization)
+ visible = DataDeletionRequest.objects.create(
+ team_id=self.team.id,
+ request_type=RequestType.HOGQL_EVENT_REMOVAL,
+ execution_mode=ExecutionMode.DEFERRED,
+ hogql_query="SELECT uuid FROM events",
+ )
+ hidden = DataDeletionRequest.objects.create(
+ team_id=other_team.id,
+ request_type=RequestType.HOGQL_EVENT_REMOVAL,
+ execution_mode=ExecutionMode.DEFERRED,
+ hogql_query="SELECT uuid FROM events",
+ )
+
+ listing = self.client.get(f"{self.url}/")
+ hidden_detail = self.client.get(f"{self.url}/{hidden.id}/")
+
+ assert listing.status_code == status.HTTP_200_OK
+ assert [item["id"] for item in listing.json()["results"]] == [str(visible.id)]
+ assert hidden_detail.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_preview_rejects_non_object_variables(self, _feature_flag) -> None:
+ response = self.client.post(
+ f"{self.url}/preview/",
+ {"query": "SELECT uuid FROM events", "variables": []},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "variables"
+ assert response.json()["detail"] == "Query variables must be a JSON object."
+
+ @patch("posthog.api.data_deletion_request.preview_event_deletion", return_value=123)
+ def test_preview_returns_the_server_count(self, preview, _feature_flag) -> None:
+ response = self.client.post(
+ f"{self.url}/preview/",
+ {"query": "SELECT uuid FROM events", "variables": {}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"count": 123}
+ preview.assert_called_once()
+
+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
+ @patch("posthog.api.data_deletion_request.preview_event_deletion", return_value=1)
+ def test_preview_throttles_session_requests(self, _preview, _rate_limit, _feature_flag) -> None:
+ responses = [
+ self.client.post(
+ f"{self.url}/preview/",
+ {"query": "SELECT uuid FROM events", "variables": {}},
+ format="json",
+ )
+ for _ in range(6)
+ ]
+
+ assert [response.status_code for response in responses] == [
+ status.HTTP_200_OK,
+ status.HTTP_200_OK,
+ status.HTTP_200_OK,
+ status.HTTP_200_OK,
+ status.HTTP_200_OK,
+ status.HTTP_429_TOO_MANY_REQUESTS,
+ ]
+
+
+class TestDataDeletionRequestAPIAccess(APIBaseTest):
+ def test_feature_flag_gates_the_whole_surface(self) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save(update_fields=["level"])
+ url = f"/api/projects/{self.team.id}/data_deletion_requests"
+
+ with patch(FEATURE_FLAG, return_value=False):
+ assert self.client.get(f"{url}/").status_code == status.HTTP_403_FORBIDDEN
+ assert self.client.post(f"{url}/preview/", {}).status_code == status.HTTP_403_FORBIDDEN
+
+ def test_organization_member_has_no_deletion_access_by_default(self) -> None:
+ url = f"/api/projects/{self.team.id}/data_deletion_requests/"
+
+ with patch(FEATURE_FLAG, return_value=True):
+ response = self.client.get(url)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_organization_member_with_explicit_access_can_preview(self) -> None:
+ url = f"/api/projects/{self.team.id}/data_deletion_requests/preview/"
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ AccessControl.objects.create(
+ team=self.team,
+ resource="data_deletion",
+ access_level="editor",
+ organization_member=self.organization_membership,
+ )
+
+ with (
+ patch(FEATURE_FLAG, return_value=True),
+ patch("posthog.api.data_deletion_request.preview_event_deletion", return_value=1),
+ ):
+ response = self.client.post(url, {"query": "SELECT uuid FROM events"}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK
diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.py
index 46fc86e839b4..524b24d30d9d 100644
--- a/posthog/dags/data_deletion_requests.py
+++ b/posthog/dags/data_deletion_requests.py
@@ -5,13 +5,12 @@ from datetime import UTC, datetime, timedelta
from functools import partial
from django.conf import settings as django_settings
+from django.core.exceptions import ValidationError as DjangoValidationError
import dagster
import pydantic
from clickhouse_driver import Client
-from posthog.schema import HogQLVariable
-
# Pre-warm the HogQL → HogVM bytecode import chain at code-location load time. Compiling a
# predicate (process_property_removal_shard → compile_hogql_predicate) builds the HogQL
# database, whose virtual-field placeholder replacement lazily does
@@ -23,8 +22,6 @@ from posthog.schema import HogQLVariable
# packages already get cached this way; common.hogvm is the only fresh import on the predicate
# path, so it is the one that breaks without this.
import posthog.hogql.compiler.bytecode # noqa: F401
-from posthog.hogql import ast
-from posthog.hogql.query import HogQLQueryExecutor
from posthog.clickhouse.adhoc_events_deletion import ADHOC_EVENTS_DELETION_TABLE
from posthog.clickhouse.client import sync_execute
@@ -34,6 +31,7 @@ from posthog.clickhouse.events_json import UNPARSEABLE_PROPERTIES_KEY
from posthog.clickhouse.workload import Workload
from posthog.dags.common import JobOwners
from posthog.dags.deletes import deletes_job
+from posthog.data_deletion import compile_event_uuid_query
from posthog.models.data_deletion_request import (
AUTO_APPROVE_INTERVAL_MINUTES,
DataDeletionRequest,
@@ -73,8 +71,6 @@ from posthog.models.person.bulk_delete import (
resolve_persons_for_deletion,
)
-from products.access_control.backend.facade.user_access_control import UserAccessControl
-
from ee.clickhouse.materialized_columns.columns import MaterializedColumnDetails
OWNER_TAG = {"owner": JobOwners.TEAM_CLICKHOUSE.value}
@@ -525,26 +521,15 @@ class HogQLEventDeletionExecutor:
raise dagster.Failure("The request team or creator no longer exists.") from error
try:
- variables = {key: HogQLVariable.model_validate(value) for key, value in request.variables.items()}
- except pydantic.ValidationError as error:
- raise dagster.Failure("The request contains invalid HogQL variables.") from error
-
- compiler = HogQLQueryExecutor(
- query=request.query,
- team=team,
- user=user,
- user_access_control=UserAccessControl(user=user, team=team),
- variables=variables,
- workload=Workload.OFFLINE,
- ch_user=ClickHouseUser.DELETION_EXECUTOR,
- pretty=False,
- )
- selected = compiler.generate_clickhouse_subquery_sql()
- prepared_ast = compiler.clickhouse_prepared_ast
- if not isinstance(prepared_ast, (ast.SelectQuery, ast.SelectSetQuery)):
- raise dagster.Failure("The HogQL query must produce a result set.")
- if prepared_ast.type is None or len(prepared_ast.type.columns) != 1:
- raise dagster.Failure("The HogQL query must select exactly one event UUID column.")
+ selected = compile_event_uuid_query(
+ query=request.query,
+ variables=request.variables,
+ team=team,
+ user=user,
+ ch_user=ClickHouseUser.DELETION_EXECUTOR,
+ )
+ except DjangoValidationError as error:
+ raise dagster.Failure(str(error)) from error
database = django_settings.CLICKHOUSE_DATABASE
insert_sql = ( # nosemgrep: clickhouse-injection-taint
diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.py
index cc6141aa17c8..ef971d338b35 100644
--- a/posthog/dags/tests/test_data_deletion_requests.py
+++ b/posthog/dags/tests/test_data_deletion_requests.py
@@ -347,17 +347,24 @@ def test_hogql_event_deletion_executor_wraps_compiled_select_and_uses_dedicated_
@pytest.mark.django_db
-def test_hogql_event_deletion_executor_rejects_multiple_columns_before_insert(team, user):
+ ("query", "error"),
+ [
+ ("SELECT uuid, event FROM events", "exactly one event UUID column"),
+ ("SELECT event FROM events", "selected column must contain event UUIDs"),
+ ],
+)
+def test_hogql_event_deletion_executor_rejects_invalid_output_before_insert(team, user, query, error):
deletion_request = HogQLEventRemovalContext(
request_id=str(uuid4()),
team_id=team.pk,
created_by_id=user.pk,
- query="SELECT uuid, event FROM events",
+ query=query,
variables={},
)
with patch("posthog.dags.data_deletion_requests.sync_execute") as execute:
- with pytest.raises(dagster.Failure, match="exactly one event UUID column"):
+ with pytest.raises(dagster.Failure, match=error):
HogQLEventDeletionExecutor(deletion_request).execute()
execute.assert_not_called()
diff --git a/posthog/data_deletion.py b/posthog/data_deletion.py
new file mode 100644
index 000000000000..756956cab4b1
--- /dev/null
+++ b/posthog/data_deletion.py
@@ -0,0 +1,158 @@
+import json
+from collections.abc import Mapping
+from uuid import UUID
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+from django.db import connection, transaction
+
+import pydantic
+
+from posthog.schema import HogQLVariable
+
+from posthog.hogql import ast
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.query import EmbeddedClickHouseQuery, HogQLQueryExecutor
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.clickhouse.workload import Workload
+from posthog.models import Team, User
+from posthog.models.data_deletion_request import DataDeletionRequest, ExecutionMode, RequestStatus, RequestType
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl, UserAccessControlError
+
+MAX_QUERY_BYTES = 100_000
+MAX_VARIABLES_BYTES = 100_000
+MAX_ACTIVE_REQUESTS_PER_TEAM = 5
+ACTIVE_REQUEST_STATUSES = (
+ RequestStatus.PENDING,
+ RequestStatus.APPROVED,
+ RequestStatus.IN_PROGRESS,
+ RequestStatus.QUEUED,
+)
+
+
+class DataDeletionSubmissionConflict(Exception):
+ pass
+
+
+class DataDeletionActiveRequestLimit(Exception):
+ pass
+
+
+def validate_payload_size(query: str, variables: dict[str, object]) -> None:
+ if len(query.encode("utf-8")) > MAX_QUERY_BYTES:
+ raise DjangoValidationError({"query": f"The query must be smaller than {MAX_QUERY_BYTES} bytes."})
+ variables_bytes = len(json.dumps(variables, separators=(",", ":")).encode("utf-8"))
+ if variables_bytes > MAX_VARIABLES_BYTES:
+ raise DjangoValidationError(
+ {"variables": f"The query variables must be smaller than {MAX_VARIABLES_BYTES} bytes."}
+ )
+
+
+def compile_event_uuid_query(
+ *,
+ query: str,
+ variables: Mapping[str, object],
+ team: Team,
+ user: User,
+ ch_user: ClickHouseUser = ClickHouseUser.DEFAULT,
+) -> EmbeddedClickHouseQuery:
+ try:
+ parsed_variables = {key: HogQLVariable.model_validate(value) for key, value in variables.items()}
+ except pydantic.ValidationError as error:
+ raise DjangoValidationError({"variables": "The query variables are invalid."}) from error
+
+ compiler = HogQLQueryExecutor(
+ query=query,
+ team=team,
+ user=user,
+ user_access_control=UserAccessControl(user=user, team=team),
+ variables=parsed_variables,
+ workload=Workload.OFFLINE,
+ ch_user=ch_user,
+ limit_context=None,
+ pretty=False,
+ )
+ try:
+ selected = compiler.generate_clickhouse_subquery_sql()
+ except (ExposedHogQLError, UserAccessControlError) as error:
+ raise DjangoValidationError({"query": str(error)}) from error
+ prepared_ast = compiler.clickhouse_prepared_ast
+ if not isinstance(prepared_ast, (ast.SelectQuery, ast.SelectSetQuery)) or prepared_ast.type is None:
+ raise DjangoValidationError({"query": "The HogQL query must return a result set."})
+ if len(prepared_ast.type.columns) != 1:
+ raise DjangoValidationError({"query": "The HogQL query must select exactly one event UUID column."})
+
+ output_type = next(iter(prepared_ast.type.columns.values())).resolve_constant_type(selected.context)
+ if not isinstance(output_type, ast.UUIDType):
+ raise DjangoValidationError({"query": "The selected column must contain event UUIDs."})
+ return selected
+
+
+def preview_event_deletion(*, query: str, variables: dict[str, object], team: Team, user: User) -> int:
+ validate_payload_size(query, variables)
+ selected = compile_event_uuid_query(query=query, variables=variables, team=team, user=user)
+ count_sql = f"SELECT count() FROM ({selected.sql}) AS selected" # nosemgrep: clickhouse-injection-taint
+ result = sync_execute(
+ count_sql,
+ selected.context.values,
+ workload=Workload.OFFLINE,
+ team_id=team.id,
+ readonly=True,
+ settings=selected.settings,
+ external_tables=list(selected.context.external_tables.values()) or None,
+ )
+ return int(result[0][0]) if result else 0
+
+
+def create_event_deletion_request(
+ *,
+ query: str,
+ variables: dict[str, object],
+ submission_id: UUID,
+ team: Team,
+ user: User,
+) -> tuple[DataDeletionRequest, bool]:
+ validate_payload_size(query, variables)
+ with transaction.atomic():
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"data-deletion:{team.id}"])
+
+ existing = DataDeletionRequest.objects.filter(team_id=team.id, submission_id=submission_id).first()
+ if existing is not None:
+ if (
+ existing.request_type != RequestType.HOGQL_EVENT_REMOVAL
+ or existing.hogql_query != query
+ or existing.hogql_variables != variables
+ or existing.created_by_id != user.id
+ ):
+ raise DataDeletionSubmissionConflict
+ return existing, False
+
+ active_count = DataDeletionRequest.objects.filter(
+ team_id=team.id,
+ request_type=RequestType.HOGQL_EVENT_REMOVAL,
+ status__in=ACTIVE_REQUEST_STATUSES,
+ ).count()
+ if active_count >= MAX_ACTIVE_REQUESTS_PER_TEAM:
+ raise DataDeletionActiveRequestLimit
+
+ compile_event_uuid_query(query=query, variables=variables, team=team, user=user)
+
+ deletion_request = DataDeletionRequest(
+ team_id=team.id,
+ request_type=RequestType.HOGQL_EVENT_REMOVAL,
+ hogql_query=query,
+ hogql_variables=variables,
+ submission_id=submission_id,
+ created_by=user,
+ created_by_staff=user.is_staff,
+ criteria_updated_by=user,
+ status=RequestStatus.PENDING,
+ requires_approval=True,
+ execution_mode=ExecutionMode.DEFERRED,
+ )
+ deletion_request.full_clean()
+ deletion_request.save()
+ return deletion_request, True
diff --git a/posthog/migrations/1384_add_data_deletion_submission_id.py b/posthog/migrations/1384_add_data_deletion_submission_id.py
new file mode 100644
index 000000000000..434193e108ad
--- /dev/null
+++ b/posthog/migrations/1384_add_data_deletion_submission_id.py
@@ -0,0 +1,17 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("posthog", "1383_taggeditem_untrack_legacy_keys")]
+
+ operations = [
+ migrations.AddField(
+ model_name="datadeletionrequest",
+ name="submission_id",
+ field=models.UUIDField(
+ blank=True,
+ help_text="Client-generated identifier used to deduplicate self-service submissions.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/1385_add_data_deletion_submission_id_constraint.py b/posthog/migrations/1385_add_data_deletion_submission_id_constraint.py
new file mode 100644
index 000000000000..445423b010b2
--- /dev/null
+++ b/posthog/migrations/1385_add_data_deletion_submission_id_constraint.py
@@ -0,0 +1,32 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [("posthog", "1384_add_data_deletion_submission_id")]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddConstraint(
+ model_name="datadeletionrequest",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(submission_id__isnull=False),
+ fields=("team_id", "submission_id"),
+ name="ddr_team_submission_id_uniq",
+ ),
+ )
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="ddr_team_submission_id_uniq",
+ table_name="posthog_datadeletionrequest",
+ columns="(team_id, submission_id) WHERE submission_id IS NOT NULL",
+ unique=True,
+ )
+ ],
+ )
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 7de68b9bd074..3d350e9bd6d6 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1383_taggeditem_untrack_legacy_keys
+1385_add_data_deletion_submission_id_constraint
diff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.py
index e40b66093115..be66f3cfbc2d 100644
--- a/posthog/models/data_deletion_request.py
+++ b/posthog/models/data_deletion_request.py
@@ -288,6 +288,11 @@ class DataDeletionRequest(UUIDModel):
db_default={},
help_text="Variables stored with the HogQL query snapshot.",
)
+ submission_id = models.UUIDField(
+ null=True,
+ blank=True,
+ help_text="Client-generated identifier used to deduplicate self-service submissions.",
+ )
properties = ArrayField(
models.CharField(max_length=1024),
blank=True,
@@ -442,6 +447,13 @@ class DataDeletionRequest(UUIDModel):
class Meta:
ordering = ["-created_at"]
indexes = [models.Index(fields=["team_id", "-created_at"], name="ddr_team_created_at_idx")]
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team_id", "submission_id"],
+ condition=models.Q(submission_id__isnull=False),
+ name="ddr_team_submission_id_uniq",
+ )
+ ]
def __str__(self) -> str:
return f"DataDeletionRequest({self.request_type}, team={self.team_id}, status={self.status})"
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 13d5dfc00958..afc2818ea52a 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -64,6 +64,18 @@ tools:
dashboards-sharing-refresh-create:
operation: dashboards_sharing_refresh_create
enabled: false
+ data-deletion-requests-create:
+ operation: data_deletion_requests_create
+ enabled: false
+ data-deletion-requests-list:
+ operation: data_deletion_requests_list
+ enabled: false
+ data-deletion-requests-preview-create:
+ operation: data_deletion_requests_preview_create
+ enabled: false
+ data-deletion-requests-retrieve:
+ operation: data_deletion_requests_retrieve
+ enabled: false
delete-secret-token-backup-partial-update:
operation: organizations_projects_delete_secret_token_backup_partial_update
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1661f9563c33..de38e6b9e2ca 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25144,6 +25144,137 @@ export namespace Schemas {
readonly created_by: UserBasic;
}
+ export interface DataDeletionConflict {
+ /** Reason the deletion request could not be created in the current state. */
+ readonly detail: string;
+ }
+
+ export interface DataDeletionPreview {
+ /** Number of event UUIDs selected when the preview ran. */
+ readonly count: number;
+ }
+
+ /**
+ * Submitted HogQL variable snapshot.
+ */
+ export type DataDeletionRequestVariables = {[key: string]: {
+ code_name: string;
+ isNull?: boolean | null;
+ value?: unknown;
+ variableId: string;
+ }};
+
+ /**
+ * * `draft` - Draft
+ * * `pending` - Pending
+ * * `approved` - Approved
+ * * `in_progress` - In Progress
+ * * `queued` - Queued
+ * * `completed` - Completed
+ * * `failed` - Failed
+ */
+ export type RequestStatusEnum = typeof RequestStatusEnum[keyof typeof RequestStatusEnum];
+
+
+ export const RequestStatusEnum = {
+ Draft: 'draft',
+ Pending: 'pending',
+ Approved: 'approved',
+ InProgress: 'in_progress',
+ Queued: 'queued',
+ Completed: 'completed',
+ Failed: 'failed',
+ } as const;
+
+ export interface DataDeletionRequest {
+ /** Deletion request identifier. */
+ readonly id: string;
+ /** Current deletion workflow status.
+ *
+ * * `draft` - Draft
+ * * `pending` - Pending
+ * * `approved` - Approved
+ * * `in_progress` - In Progress
+ * * `queued` - Queued
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ readonly status: RequestStatusEnum;
+ /** Submitted HogQL query snapshot. */
+ readonly query: string;
+ /** Submitted HogQL variable snapshot. */
+ readonly variables: DataDeletionRequestVariables;
+ /**
+ * Client-generated idempotency identifier.
+ * @nullable
+ */
+ readonly submission_id: string | null;
+ /**
+ * Number of selected events, when calculated.
+ * @nullable
+ */
+ readonly count: number | null;
+ /**
+ * Identifier of the user who submitted the request.
+ * @nullable
+ */
+ readonly created_by_id: number | null;
+ /**
+ * Whether the submitter was a PostHog staff user.
+ * @nullable
+ */
+ readonly created_by_staff: boolean | null;
+ /** Time when the request was submitted. */
+ readonly created_at: string;
+ /** Time when the request last changed. */
+ readonly updated_at: string;
+ /**
+ * Time when the request was approved, if approved.
+ * @nullable
+ */
+ readonly approved_at: string | null;
+ /**
+ * Time when selection statistics were calculated, if available.
+ * @nullable
+ */
+ readonly stats_calculated_at: string | null;
+ }
+
+ /**
+ * Variables referenced by the HogQL query.
+ */
+ export type DataDeletionRequestCreateVariables = {[key: string]: {
+ code_name: string;
+ isNull?: boolean | null;
+ value?: unknown;
+ variableId: string;
+ }};
+
+ export interface DataDeletionRequestCreate {
+ /** HogQL query that selects one event UUID column. */
+ query: string;
+ /** Variables referenced by the HogQL query. */
+ variables?: DataDeletionRequestCreateVariables;
+ /** Client-generated identifier that makes request submission idempotent. */
+ submission_id: string;
+ }
+
+ /**
+ * Variables referenced by the HogQL query.
+ */
+ export type DataDeletionRequestInputVariables = {[key: string]: {
+ code_name: string;
+ isNull?: boolean | null;
+ value?: unknown;
+ variableId: string;
+ }};
+
+ export interface DataDeletionRequestInput {
+ /** HogQL query that selects one event UUID column. */
+ query: string;
+ /** Variables referenced by the HogQL query. */
+ variables?: DataDeletionRequestInputVariables;
+ }
+
/**
* * `never` - never
* * `live` - live
@@ -62816,6 +62947,15 @@ export namespace Schemas {
results: DataColorTheme[];
}
+ export interface PaginatedDataDeletionRequestList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: DataDeletionRequest[];
+ }
+
export interface PaginatedDataModelingJobList {
count: number;
/** @nullable */
@@ -107646,6 +107786,17 @@ export namespace Schemas {
offset?: number;
};
+ export type DataDeletionRequestsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type DataModelingDagsListParams = {
/**
* Number of results to return per page.