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): person drop in Dagster (#56912)

Paweł Szczur0923ea900a47
diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.py
index 4e21791b1125..e36b23e99980 100644
--- a/posthog/dags/data_deletion_requests.py
+++ b/posthog/dags/data_deletion_requests.py
@@ -28,6 +28,11 @@ from posthog.models.data_deletion_request import (
jsonhas_expr,
)
from posthog.models.event.sql import EVENTS_DATA_TABLE
+from posthog.models.person.bulk_delete import (
+ delete_persons_profile,
+ queue_person_recording_deletion,
+ resolve_persons_for_deletion,
+)
from ee.clickhouse.materialized_columns.columns import MaterializedColumnDetails
@@ -51,6 +56,19 @@ class DeletionRequestContext:
hogql_predicate: str = ""
+@dataclass
+class PersonRemovalContext:
+ request_id: str
+ team_id: int
+ person_uuids: list[str]
+ person_distinct_ids: list[str]
+ drop_profiles: bool
+ drop_events: bool
+ drop_recordings: bool
+ start_time: datetime | None = None
+ end_time: datetime | None = None
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -527,6 +545,208 @@ def cleanup_temp_tables(
return deletion_request
+# ---------------------------------------------------------------------------
+# Person removal ops
+# ---------------------------------------------------------------------------
+
+
[email protected](tags=OWNER_TAG)
+def load_person_removal_request(
+ context: dagster.OpExecutionContext,
+ config: DataDeletionRequestConfig,
+) -> PersonRemovalContext:
+ """Load and validate a person_removal request, transition to IN_PROGRESS."""
+ from django.db import transaction
+
+ with transaction.atomic():
+ request = (
+ DataDeletionRequest.objects.select_for_update()
+ .filter(
+ pk=config.request_id,
+ status=RequestStatus.APPROVED,
+ request_type=RequestType.PERSON_REMOVAL,
+ )
+ .first()
+ )
+
+ if not request:
+ raise dagster.Failure(
+ f"Request {config.request_id} is not an approved person_removal request.",
+ )
+
+ # Defense-in-depth: model.clean() enforces this, but a corrupt row would silently lose
+ # one of the selectors in resolve_persons_for_deletion (which uses if/elif).
+ if request.person_uuids and request.person_distinct_ids:
+ raise dagster.Failure(
+ f"Request {config.request_id} has both person_uuids and person_distinct_ids set; "
+ "they are mutually exclusive."
+ )
+
+ request.status = RequestStatus.IN_PROGRESS
+ request.save(update_fields=["status", "updated_at"])
+
+ # The fields are nullable on the model (NULL for non-person_removal rows), but
+ # PersonRemovalContext and the downstream `if not drop_x` consumers want plain bools.
+ # model.clean() guarantees at least one is True for person_removal requests.
+ drop_profiles = bool(request.person_drop_profiles)
+ drop_events = bool(request.person_drop_events)
+ drop_recordings = bool(request.person_drop_recordings)
+
+ context.log.info(
+ f"Processing person_removal request {request.pk}: "
+ f"team_id={request.team_id}, "
+ f"uuids={len(request.person_uuids)}, distinct_ids={len(request.person_distinct_ids)}, "
+ f"drop_profiles={drop_profiles}, "
+ f"drop_events={drop_events}, "
+ f"drop_recordings={drop_recordings}"
+ )
+ context.add_output_metadata(
+ {
+ "team_id": dagster.MetadataValue.int(request.team_id),
+ "uuid_count": dagster.MetadataValue.int(len(request.person_uuids)),
+ "distinct_id_count": dagster.MetadataValue.int(len(request.person_distinct_ids)),
+ "drop_profiles": dagster.MetadataValue.bool(drop_profiles),
+ "drop_events": dagster.MetadataValue.bool(drop_events),
+ "drop_recordings": dagster.MetadataValue.bool(drop_recordings),
+ }
+ )
+
+ return PersonRemovalContext(
+ request_id=str(request.pk),
+ team_id=request.team_id,
+ person_uuids=[str(u) for u in request.person_uuids],
+ person_distinct_ids=list(request.person_distinct_ids),
+ drop_profiles=drop_profiles,
+ drop_events=drop_events,
+ drop_recordings=drop_recordings,
+ start_time=request.start_time,
+ end_time=request.end_time,
+ )
+
+
+def _person_event_predicate(ctx: PersonRemovalContext) -> tuple[str, dict]:
+ """Build WHERE predicate + params for events linked to the targeted persons."""
+ parts = ["team_id = %(team_id)s AND person_id IN %(person_ids)s"]
+ params: dict = {"team_id": ctx.team_id, "person_ids": ctx.person_uuids}
+ if ctx.start_time is not None and ctx.end_time is not None:
+ parts.append("AND timestamp >= %(start_time)s AND timestamp < %(end_time)s")
+ params["start_time"] = ctx.start_time
+ params["end_time"] = ctx.end_time
+ return " ".join(parts), params
+
+
[email protected](tags=OWNER_TAG)
+def delete_person_events_op(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ person_removal: PersonRemovalContext,
+) -> PersonRemovalContext:
+ """Per-shard lightweight delete of events for the targeted persons."""
+ if not person_removal.drop_events:
+ context.log.info("drop_events=False, skipping event deletion")
+ return person_removal
+ # The CH events table is keyed by person_id (UUID), so resolve distinct_ids → uuids when
+ # the request was submitted by distinct_id. Selectors are mutually exclusive (enforced in
+ # DataDeletionRequest._clean_person_removal and re-checked in load_person_removal_request).
+ if person_removal.person_distinct_ids:
+ persons = resolve_persons_for_deletion(
+ person_removal.team_id,
+ uuids=None,
+ distinct_ids=person_removal.person_distinct_ids,
+ )
+ person_removal.person_uuids = [str(p.uuid) for p in persons]
+ if not person_removal.person_uuids:
+ context.log.info("No persons resolved; nothing to delete")
+ return person_removal
+
+ table = EVENTS_DATA_TABLE()
+ predicate, params = _person_event_predicate(person_removal)
+ shards = sorted(cluster.shards)
+ context.log.info(f"Deleting events for {len(person_removal.person_uuids)} persons across {len(shards)} shards")
+
+ for idx, shard_num in enumerate(shards, 1):
+ context.log.info(f"Processing shard {shard_num} ({idx}/{len(shards)})")
+ shard_start = time.monotonic()
+ runner = LightweightDeleteMutationRunner(
+ table=table,
+ predicate=predicate,
+ parameters=params,
+ settings={"lightweight_deletes_sync": 0},
+ )
+ shard_result = cluster.map_any_host_in_shards({shard_num: runner}).result()
+ _host, waiter = next(iter(shard_result.items()))
+ cluster.map_all_hosts_in_shard(shard_num, waiter.wait).result()
+ context.log.info(f"Shard {shard_num} complete in {time.monotonic() - shard_start:.1f}s")
+
+ context.add_output_metadata({"shards_processed": dagster.MetadataValue.int(len(shards))})
+ return person_removal
+
+
[email protected](tags=OWNER_TAG)
+def delete_person_recordings_op(
+ context: dagster.OpExecutionContext,
+ person_removal: PersonRemovalContext,
+) -> PersonRemovalContext:
+ """Queue recording deletion via Temporal for the targeted persons."""
+ if not person_removal.drop_recordings:
+ context.log.info("drop_recordings=False, skipping recording deletion")
+ return person_removal
+
+ persons = resolve_persons_for_deletion(
+ person_removal.team_id,
+ uuids=person_removal.person_uuids or None,
+ distinct_ids=person_removal.person_distinct_ids or None,
+ )
+ if not persons:
+ context.log.info("No persons resolved; nothing to delete")
+ return person_removal
+
+ queue_person_recording_deletion(person_removal.team_id, persons, actor=None)
+ context.add_output_metadata({"recording_workflows": dagster.MetadataValue.int(len(persons))})
+ return person_removal
+
+
[email protected](tags=OWNER_TAG)
+def delete_person_profiles_op(
+ context: dagster.OpExecutionContext,
+ person_removal: PersonRemovalContext,
+) -> PersonRemovalContext:
+ """Tombstone Person rows in CH and delete from Postgres, last.
+
+ On per-person failures, errors are recorded in op metadata and the request is allowed to
+ transition to COMPLETED — Postgres rows remain for the failed UUIDs and the operator can
+ submit a follow-up request for them. This mirrors the best-effort semantics of the
+ `POST /api/projects/:id/persons/bulk_delete/` endpoint and avoids flipping the whole
+ request to FAILED after upstream events/recordings ops have already done their work.
+ """
+ if not person_removal.drop_profiles:
+ context.log.info("drop_profiles=False, skipping profile deletion")
+ return person_removal
+
+ persons = resolve_persons_for_deletion(
+ person_removal.team_id,
+ uuids=person_removal.person_uuids or None,
+ distinct_ids=person_removal.person_distinct_ids or None,
+ )
+ if not persons:
+ context.log.info("No persons resolved; nothing to delete")
+ return person_removal
+
+ result = delete_persons_profile(person_removal.team_id, persons, actor=None)
+ metadata: dict[str, dagster.MetadataValue] = {
+ "deleted_count": dagster.MetadataValue.int(result.deleted_count),
+ "errors": dagster.MetadataValue.int(len(result.errors)),
+ }
+ if result.errors:
+ context.log.warning(
+ f"Person profile deletion had {len(result.errors)} per-person failures; "
+ f"Postgres rows remain for failed UUIDs and can be retried via a follow-up request"
+ )
+ metadata["error_uuids"] = dagster.MetadataValue.text(", ".join(str(u) for u in result.errors))
+ context.add_output_metadata(metadata)
+ return person_removal
+
+
# ---------------------------------------------------------------------------
# Shared ops
# ---------------------------------------------------------------------------
@@ -556,6 +776,22 @@ def finalize_deletion_request(
context.log.info(f"Deletion request {deletion_request.request_id} marked as {next_status.value}.")
[email protected](tags=OWNER_TAG)
+def finalize_person_removal(
+ context: dagster.OpExecutionContext,
+ person_removal: PersonRemovalContext,
+) -> None:
+ """Mark a person_removal request as COMPLETED."""
+ from django.utils import timezone
+
+ DataDeletionRequest.objects.filter(
+ pk=person_removal.request_id,
+ status=RequestStatus.IN_PROGRESS,
+ ).update(status=RequestStatus.COMPLETED, updated_at=timezone.now())
+
+ context.log.info(f"Person removal request {person_removal.request_id} marked as completed.")
+
+
@dagster.failure_hook()
def mark_deletion_failed(context: dagster.HookContext) -> None:
"""Mark the deletion request as failed if any op fails."""
@@ -570,10 +806,12 @@ def mark_deletion_failed(context: dagster.HookContext) -> None:
return
ops_config = run_config.get("ops", {})
- # Check both job types
- request_id = ops_config.get("load_deletion_request", {}).get("config", {}).get("request_id") or ops_config.get(
- "load_property_removal_request", {}
- ).get("config", {}).get("request_id")
+ # Check all job types
+ request_id = (
+ ops_config.get("load_deletion_request", {}).get("config", {}).get("request_id")
+ or ops_config.get("load_property_removal_request", {}).get("config", {}).get("request_id")
+ or ops_config.get("load_person_removal_request", {}).get("config", {}).get("request_id")
+ )
if not request_id:
return
@@ -628,6 +866,20 @@ def data_deletion_request_property_removal():
finalize_deletion_request(request)
[email protected](tags=OWNER_TAG, hooks={mark_deletion_failed})
+def data_deletion_request_person_removal():
+ """Execute an approved person_removal request: events → recordings → profiles.
+
+ Profiles are deleted last so that earlier ops can still resolve person UUIDs and
+ distinct_ids from the Postgres Person row while running.
+ """
+ request = load_person_removal_request()
+ request = delete_person_events_op(request)
+ request = delete_person_recordings_op(request)
+ request = delete_person_profiles_op(request)
+ finalize_person_removal(request)
+
+
# ---------------------------------------------------------------------------
# Pickup sensor: scans for APPROVED requests and launches jobs (max 1 at a time)
# ---------------------------------------------------------------------------
@@ -635,11 +887,16 @@ def data_deletion_request_property_removal():
_DELETION_JOB_NAMES = [
data_deletion_request_event_removal.name,
data_deletion_request_property_removal.name,
+ data_deletion_request_person_removal.name,
]
@dagster.sensor(
- jobs=[data_deletion_request_event_removal, data_deletion_request_property_removal],
+ jobs=[
+ data_deletion_request_event_removal,
+ data_deletion_request_property_removal,
+ data_deletion_request_person_removal,
+ ],
minimum_interval_seconds=600,
default_status=dagster.DefaultSensorStatus.STOPPED,
)
@@ -670,11 +927,11 @@ def data_deletion_request_pickup_sensor(context: dagster.SensorEvaluationContext
return dagster.SkipReason("No approved deletion requests to process.")
if next_request.request_type == RequestType.EVENT_REMOVAL:
- job = data_deletion_request_event_removal
- load_op = "load_deletion_request"
+ job, load_op = data_deletion_request_event_removal, "load_deletion_request"
elif next_request.request_type == RequestType.PROPERTY_REMOVAL:
- job = data_deletion_request_property_removal
- load_op = "load_property_removal_request"
+ job, load_op = data_deletion_request_property_removal, "load_property_removal_request"
+ elif next_request.request_type == RequestType.PERSON_REMOVAL:
+ job, load_op = data_deletion_request_person_removal, "load_person_removal_request"
else:
return dagster.SkipReason(f"Unknown request_type for request {next_request.pk}: {next_request.request_type}")
diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.py
index 519ad5c67665..e4d0f3ddf2e9 100644
--- a/posthog/dags/tests/test_data_deletion_requests.py
+++ b/posthog/dags/tests/test_data_deletion_requests.py
@@ -4,7 +4,9 @@ from functools import partial
from uuid import uuid4
import pytest
+from unittest.mock import patch
+import dagster
from clickhouse_driver import Client
from dagster import build_op_context
@@ -13,14 +15,22 @@ from posthog.clickhouse.cluster import ClickhouseCluster
from posthog.dags.data_deletion_requests import (
DataDeletionRequestConfig,
DeletionRequestContext,
+ PersonRemovalContext,
data_deletion_request_event_removal,
+ data_deletion_request_person_removal,
+ data_deletion_request_pickup_sensor,
data_deletion_request_property_removal,
+ delete_person_events_op,
+ delete_person_profiles_op,
+ delete_person_recordings_op,
execute_event_deletion,
finalize_deletion_request,
load_deletion_request,
+ load_person_removal_request,
load_property_removal_request,
)
from posthog.models.data_deletion_request import DataDeletionRequest, ExecutionMode, RequestStatus, RequestType
+from posthog.models.person import Person
TEAM_ID = 99999
@@ -48,6 +58,25 @@ def _count_events_by_name(team_id: int, event_name: str, client: Client) -> int:
return result[0][0]
+def _insert_events_with_person(events: list[tuple], client: Client) -> None:
+ client.execute(
+ "INSERT INTO writable_events (team_id, event, uuid, timestamp, person_id) VALUES",
+ events,
+ )
+
+
+def _count_events_for_person(team_id: int, person_uuid: str, client: Client) -> int:
+ result = client.execute(
+ "SELECT count() FROM writable_events WHERE team_id = %(team_id)s AND person_id = %(p)s",
+ {"team_id": team_id, "p": person_uuid},
+ )
+ return result[0][0]
+
+
+def _truncate_writable_events(client: Client) -> None:
+ client.execute("TRUNCATE TABLE IF EXISTS sharded_events")
+
+
def _truncate_adhoc_events_deletion(client: Client) -> None:
client.execute(f"TRUNCATE TABLE IF EXISTS {ADHOC_EVENTS_DELETION_TABLE}")
@@ -881,3 +910,297 @@ def test_full_job_property_removal_clears_materialized_columns(
assert request.status == RequestStatus.COMPLETED
finally:
cluster.any_host(partial(_drop_default_mat_columns, col_defs)).result()
+
+
+def test_load_person_removal_request_transitions_to_in_progress():
+ request = DataDeletionRequest.objects.create(
+ team_id=TEAM_ID,
+ request_type=RequestType.PERSON_REMOVAL,
+ person_uuids=[str(uuid4())],
+ person_drop_profiles=True,
+ person_drop_events=True,
+ person_drop_recordings=False,
+ status=RequestStatus.APPROVED,
+ )
+ config = DataDeletionRequestConfig(request_id=str(request.pk))
+ ctx = build_op_context()
+
+ result = load_person_removal_request(ctx, config)
+
+ assert result.team_id == TEAM_ID
+ assert result.drop_profiles is True
+ assert result.drop_events is True
+ assert result.drop_recordings is False
+ request.refresh_from_db()
+ assert request.status == RequestStatus.IN_PROGRESS
+
+
+def test_load_person_removal_rejects_both_selectors():
+ # Belt-and-suspenders: model.clean() enforces mutual exclusion at the API boundary, but if
+ # a row is created bypassing clean() (e.g. raw SQL or .objects.create), the dagster job must
+ # still refuse to run because resolve_persons_for_deletion's elif would silently drop one set.
+ request = DataDeletionRequest.objects.create(
+ team_id=TEAM_ID,
+ request_type=RequestType.PERSON_REMOVAL,
+ person_uuids=[str(uuid4())],
+ person_distinct_ids=["did-1"],
+ person_drop_profiles=True,
+ person_drop_events=False,
+ person_drop_recordings=False,
+ status=RequestStatus.APPROVED,
+ )
+ config = DataDeletionRequestConfig(request_id=str(request.pk))
+ with pytest.raises(Exception, match="mutually exclusive"):
+ load_person_removal_request(build_op_context(), config)
+
+
+def test_load_person_removal_rejects_wrong_type():
+ request = DataDeletionRequest.objects.create(
+ team_id=TEAM_ID,
+ request_type=RequestType.EVENT_REMOVAL,
+ events=["$pageview"],
+ start_time=datetime.now() - timedelta(days=1),
+ end_time=datetime.now(),
+ status=RequestStatus.APPROVED,
+ )
+ config = DataDeletionRequestConfig(request_id=str(request.pk))
+ with pytest.raises(Exception, match="not an approved person_removal request"):
+ load_person_removal_request(build_op_context(), config)
+
+
+def test_delete_person_events_op_runs_lightweight_delete_per_shard(cluster: ClickhouseCluster):
+ person_uuid = str(uuid4())
+ other_uuid = str(uuid4())
+ now = datetime.now()
+
+ cluster.any_host(_truncate_writable_events).result()
+ cluster.any_host(
+ partial(
+ _insert_events_with_person,
+ [
+ (TEAM_ID, "$pageview", str(uuid4()), now, person_uuid),
+ (TEAM_ID, "$pageview", str(uuid4()), now, other_uuid),
+ ],
+ )
+ ).result()
+
+ ctx = PersonRemovalContext(
+ request_id=str(uuid4()),
+ team_id=TEAM_ID,
+ person_uuids=[person_uuid],
+ person_distinct_ids=[],
+ drop_profiles=False,
+ drop_events=True,
+ drop_recordings=False,
+ )
+
+ delete_person_events_op(build_op_context(), cluster, ctx)
+
+ assert cluster.any_host(partial(_count_events_for_person, TEAM_ID, person_uuid)).result() == 0
+ assert cluster.any_host(partial(_count_events_for_person, TEAM_ID, other_uuid)).result() == 1
+
+
+def test_delete_person_events_op_noop_when_disabled(cluster: ClickhouseCluster):
+ ctx = PersonRemovalContext(
+ request_id=str(uuid4()),
+ team_id=TEAM_ID,
+ person_uuids=[str(uuid4())],
+ person_distinct_ids=[],
+ drop_profiles=False,
+ drop_events=False,
+ drop_recordings=False,
+ )
+ delete_person_events_op(build_op_context(), cluster, ctx)
+
+
+def test_delete_person_events_op_resolves_distinct_ids_to_uuids(cluster: ClickhouseCluster):
+ # When the request was submitted by distinct_id, the events op must resolve to UUIDs
+ # because the CH events table is keyed by person_id (UUID).
+ p = Person.objects.create(team_id=TEAM_ID, uuid=uuid4(), distinct_ids=["distinct-only"])
+ bystander_uuid = str(uuid4())
+ now = datetime.now()
+
+ cluster.any_host(_truncate_writable_events).result()
+ cluster.any_host(
+ partial(
+ _insert_events_with_person,
+ [
+ (TEAM_ID, "$pageview", str(uuid4()), now, str(p.uuid)),
+ (TEAM_ID, "$pageview", str(uuid4()), now, bystander_uuid),
+ ],
+ )
+ ).result()
+
+ ctx = PersonRemovalContext(
+ request_id=str(uuid4()),
+ team_id=TEAM_ID,
+ person_uuids=[],
+ person_distinct_ids=["distinct-only"],
+ drop_profiles=False,
+ drop_events=True,
+ drop_recordings=False,
+ )
+
+ delete_person_events_op(build_op_context(), cluster, ctx)
+
+ assert cluster.any_host(partial(_count_events_for_person, TEAM_ID, str(p.uuid))).result() == 0
+ assert cluster.any_host(partial(_count_events_for_person, TEAM_ID, bystander_uuid)).result() == 1
+
+
+def test_delete_person_recordings_op_calls_helper_when_enabled():
+ p_uuid = str(uuid4())
+ Person.objects.create(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])
+ ctx = PersonRemovalContext(
+ request_id=str(uuid4()),
+ team_id=TEAM_ID,
+ person_uuids=[p_uuid],
+ person_distinct_ids=[],
+ drop_profiles=False,
+ drop_events=False,
+ drop_recordings=True,
+ )
+ with patch("posthog.dags.data_deletion_requests.queue_person_recording_deletion") as queue:
+ delete_person_recordings_op(build_op_context(), ctx)
+ queue.assert_called_once()
+ kwargs = queue.call_args.kwargs
+ assert kwargs["actor"] is None # no DRF user in Dagster
+
+
+def test_delete_person_recordings_op_noop_when_disabled():
+ ctx = PersonRemovalContext(
+ request_id=str(uuid4()),
+ team_id=TEAM_ID,
+ person_uuids=[str(uuid4())],
+ person_distinct_ids=[],
+ drop_profiles=False,
+ drop_events=False,
+ drop_recordings=False,
+ )
+ with patch("posthog.dags.data_deletion_requests.queue_person_recording_deletion") as queue:
+ delete_person_recordings_op(build_op_context(), ctx)
+ queue.assert_not_called()
+
+
+def test_delete_person_profiles_op_calls_helper_when_enabled():
+ p_uuid = str(uuid4())
+ Person.objects.create(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])
+ ctx = PersonRemovalContext(
+ request_id=str(uuid4()),
+ team_id=TEAM_ID,
+ person_uuids=[p_uuid],
+ person_distinct_ids=[],
+ drop_profiles=True,
+ drop_events=False,
+ drop_recordings=False,
+ )
+ with patch("posthog.dags.data_deletion_requests.delete_persons_profile") as deleter:
+ deleter.return_value = type("R", (), {"deleted_count": 1, "errors": []})()
+ delete_person_profiles_op(build_op_context(), ctx)
+ deleter.assert_called_once()
+
+
+def test_delete_person_profiles_op_noop_when_disabled():
+ ctx = PersonRemovalContext(
+ request_id=str(uuid4()),
+ team_id=TEAM_ID,
+ person_uuids=[str(uuid4())],
+ person_distinct_ids=[],
+ drop_profiles=False,
+ drop_events=False,
+ drop_recordings=False,
+ )
+ with patch("posthog.dags.data_deletion_requests.delete_persons_profile") as deleter:
+ delete_person_profiles_op(build_op_context(), ctx)
+ deleter.assert_not_called()
+
+
+def test_delete_person_profiles_op_records_per_person_errors_in_metadata():
+ # Best-effort semantics: per-person failures are recorded in op metadata and surfaced via
+ # logs, but the op returns normally so the request can finalize to COMPLETED and the
+ # operator can issue a follow-up request for the failed UUIDs.
+ p_uuid = str(uuid4())
+ Person.objects.create(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])
+ ctx = PersonRemovalContext(
+ request_id=str(uuid4()),
+ team_id=TEAM_ID,
+ person_uuids=[p_uuid],
+ person_distinct_ids=[],
+ drop_profiles=True,
+ drop_events=False,
+ drop_recordings=False,
+ )
+ op_context = build_op_context()
+ with patch("posthog.dags.data_deletion_requests.delete_persons_profile") as deleter:
+ deleter.return_value = type("R", (), {"deleted_count": 0, "errors": [p_uuid]})()
+ with patch.object(op_context.log, "warning") as warn:
+ result = delete_person_profiles_op(op_context, ctx)
+
+ # No raise — best-effort, returns the context.
+ assert result is ctx
+ # The op surfaced the failure via a warning log so operators can find the failed UUIDs.
+ assert warn.called
+ warn_message = warn.call_args.args[0] if warn.call_args.args else ""
+ assert "1 per-person failures" in warn_message
+
+
+def test_data_deletion_request_person_removal_lifecycle(cluster: ClickhouseCluster):
+ p_uuid = str(uuid4())
+ Person.objects.create(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])
+ request = DataDeletionRequest.objects.create(
+ team_id=TEAM_ID,
+ request_type=RequestType.PERSON_REMOVAL,
+ person_uuids=[p_uuid],
+ person_drop_profiles=True,
+ person_drop_events=True,
+ person_drop_recordings=False,
+ status=RequestStatus.APPROVED,
+ )
+
+ with (
+ patch("posthog.dags.data_deletion_requests.delete_persons_profile") as profile,
+ patch("posthog.dags.data_deletion_requests.queue_person_recording_deletion"),
+ ):
+ profile.return_value = type("R", (), {"deleted_count": 1, "errors": []})()
+ result = data_deletion_request_person_removal.execute_in_process(
+ run_config={
+ "ops": {
+ "load_person_removal_request": {"config": {"request_id": str(request.pk)}},
+ },
+ },
+ resources={"cluster": cluster},
+ )
+
+ assert result.success
+ request.refresh_from_db()
+ assert request.status == RequestStatus.COMPLETED
+
+
+def test_pickup_sensor_routes_person_removal_request():
+ request = DataDeletionRequest.objects.create(
+ team_id=TEAM_ID,
+ request_type=RequestType.PERSON_REMOVAL,
+ person_uuids=[str(uuid4())],
+ person_drop_profiles=True,
+ status=RequestStatus.APPROVED,
+ approved_at=datetime.now(),
+ )
+ instance = dagster.DagsterInstance.ephemeral()
+ ctx = dagster.build_sensor_context(instance=instance)
+ result = data_deletion_request_pickup_sensor(ctx)
+ assert isinstance(result, dagster.RunRequest)
+ assert result.job_name == "data_deletion_request_person_removal"
+ assert "load_person_removal_request" in result.run_config["ops"]
+ assert str(request.pk) == result.run_key
diff --git a/posthog/migrations/1139_alter_datadeletionrequest_person_distinct_ids_and_more.py b/posthog/migrations/1139_alter_datadeletionrequest_person_distinct_ids_and_more.py
new file mode 100644
index 000000000000..e23a99f3acb0
--- /dev/null
+++ b/posthog/migrations/1139_alter_datadeletionrequest_person_distinct_ids_and_more.py
@@ -0,0 +1,35 @@
+# Generated by Django 5.2.13 on 2026-04-30 10:12
+
+import django.contrib.postgres.fields
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1138_onboarding_delegated_to_invite_index"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="datadeletionrequest",
+ name="person_distinct_ids",
+ field=django.contrib.postgres.fields.ArrayField(
+ base_field=models.CharField(max_length=400),
+ blank=True,
+ default=list,
+ help_text="Person distinct IDs to target. Mutually exclusive with person_uuids; max 1000.",
+ size=None,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="datadeletionrequest",
+ name="person_uuids",
+ field=django.contrib.postgres.fields.ArrayField(
+ base_field=models.UUIDField(),
+ blank=True,
+ default=list,
+ help_text="Person UUIDs to target. Mutually exclusive with person_distinct_ids; max 1000.",
+ size=None,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index b22b360447cd..156dc310e7fe 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1138_onboarding_delegated_to_invite_index
+1139_alter_datadeletionrequest_person_distinct_ids_and_more
diff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.py
index 4cceb6379175..32b744996aec 100644
--- a/posthog/models/data_deletion_request.py
+++ b/posthog/models/data_deletion_request.py
@@ -150,13 +150,13 @@ class DataDeletionRequest(UUIDModel):
models.UUIDField(),
blank=True,
default=list,
- help_text="Person UUIDs to target. Combined with person_distinct_ids; total ≤ 1000.",
+ help_text="Person UUIDs to target. Mutually exclusive with person_distinct_ids; max 1000.",
)
person_distinct_ids = ArrayField(
models.CharField(max_length=400),
blank=True,
default=list,
- help_text="Person distinct IDs to target. Combined with person_uuids; total ≤ 1000.",
+ help_text="Person distinct IDs to target. Mutually exclusive with person_uuids; max 1000.",
)
person_drop_profiles = models.BooleanField(
null=True,
@@ -285,11 +285,13 @@ class DataDeletionRequest(UUIDModel):
raise ValidationError({"start_time": "start_time must be before end_time."})
def _clean_person_removal(self) -> None:
+ if self.person_uuids and self.person_distinct_ids:
+ raise ValidationError({"person_uuids": "Provide either person_uuids or person_distinct_ids, not both."})
total = len(self.person_uuids) + len(self.person_distinct_ids)
if total == 0:
raise ValidationError({"person_uuids": "Provide at least one person_uuid or person_distinct_id."})
if total > 1000:
- raise ValidationError({"person_uuids": "Combined person_uuids + person_distinct_ids must be ≤ 1000."})
+ raise ValidationError({"person_uuids": "person_uuids or person_distinct_ids must be ≤ 1000."})
if not (self.person_drop_profiles or self.person_drop_events or self.person_drop_recordings):
raise ValidationError(
{"person_drop_profiles": "At least one of person_drop_profiles / events / recordings must be true."}
diff --git a/posthog/models/test/test_data_deletion_request.py b/posthog/models/test/test_data_deletion_request.py
index 76f3554338a7..b36bf8febbb2 100644
--- a/posthog/models/test/test_data_deletion_request.py
+++ b/posthog/models/test/test_data_deletion_request.py
@@ -218,6 +218,12 @@ def test_person_removal_caps_total_selectors_at_1000():
request.clean()
+def test_person_removal_rejects_both_selectors():
+ request = DataDeletionRequest(**_person_kwargs(person_uuids=[str(uuid_lib.uuid4())], person_distinct_ids=["did-1"]))
+ with pytest.raises(ValidationError, match="not both"):
+ request.clean()
+
+
@pytest.mark.parametrize(
"overrides, match",
[