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.

fix(clickhouse): prevent duplicate events in property-removal deletion job (#70413)

Paweł Szczurbbbcc1d586e8
diff --git a/posthog/admin/admins/data_deletion_request_admin.py b/posthog/admin/admins/data_deletion_request_admin.py
index b4e6a4234842..d243436e4f6d 100644
--- a/posthog/admin/admins/data_deletion_request_admin.py
+++ b/posthog/admin/admins/data_deletion_request_admin.py
@@ -603,6 +603,9 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):
obj.min_timestamp = None
obj.max_timestamp = None
obj.stats_calculated_at = None
+ # Rows cleaned under the old criteria are ordinary candidates for the new ones —
+ # a stale marker would make the copy pass skip them as "already cleaned".
+ obj.property_removal_marker = None
if obj.status != RequestStatus.DRAFT:
obj.status = RequestStatus.DRAFT
messages.warning(request, "Deletion criteria were changed — status has been reset to draft.")
diff --git a/posthog/admin/test_data_deletion_request_admin.py b/posthog/admin/test_data_deletion_request_admin.py
index c4adab66f10a..1126100b53ce 100644
--- a/posthog/admin/test_data_deletion_request_admin.py
+++ b/posthog/admin/test_data_deletion_request_admin.py
@@ -9,6 +9,7 @@ from django.contrib.auth.models import Group
from django.contrib.messages import get_messages
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test import RequestFactory, override_settings
+from django.utils import timezone
from parameterized import parameterized
@@ -445,6 +446,21 @@ class TestDataDeletionRequestAdminSaveModel(BaseTest):
self.assertEqual(obj.properties, ["$ip"])
self.assertEqual(obj.person_properties, ["email"])
+ def test_criteria_change_clears_property_removal_marker(self):
+ obj = DataDeletionRequest.objects.create(
+ team_id=self.team.id,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=["$ip"],
+ start_time=datetime.now() - timedelta(days=7),
+ end_time=datetime.now(),
+ status=RequestStatus.PENDING,
+ property_removal_marker=timezone.now(),
+ )
+ self._call_save(obj, changed_data=["properties"])
+ obj.refresh_from_db()
+ self.assertIsNone(obj.property_removal_marker)
+
@freeze_time("2025-01-15 12:00:00")
class TestDataDeletionRequestModelValidation(BaseTest):
diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.py
index 23a86d2dcf27..6b6b10620ba2 100644
--- a/posthog/dags/data_deletion_requests.py
+++ b/posthog/dags/data_deletion_requests.py
@@ -1,7 +1,7 @@
import time
from collections.abc import Callable
from dataclasses import dataclass, field
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from django.conf import settings as django_settings
@@ -64,8 +64,9 @@ class DeletionRequestContext:
execution_mode: str = ExecutionMode.IMMEDIATE.value
delete_all_events: bool = False
hogql_predicate: str = ""
- # Set by process_property_removal_per_shard; cleaned re-inserts get this exact value stamped
- # onto inserted_at so the same op's delete pass can exclude them via inserted_at < marker.
+ # Set by load_property_removal_request from the persisted request field; cleaned re-inserts
+ # get this exact value stamped onto inserted_at so the delete pass can exclude them via
+ # inserted_at < marker, and re-runs recognize rows already cleaned by earlier attempts.
inserted_at_marker: datetime | None = None
@@ -167,6 +168,7 @@ def _property_removal_where(
person_mat_cols: list[tuple[str, bool]] | None = None,
inserted_at_max: str | None = None,
hogql_compiled: tuple[str, dict] | None = None,
+ exclude_cleaned_from: str | None = None,
) -> tuple[str, dict]:
"""Full WHERE predicate + params for property-removal queries.
@@ -174,7 +176,9 @@ def _property_removal_where(
originals afterward. The presence check (JSON ``properties`` and/or
``person_properties`` plus DEFAULT materialized columns) MUST match between
the two passes — drift causes either data loss (delete > copy) or duplication
- (copy > delete).
+ (copy > delete). For the same reason both passes MUST pass the identical
+ ``inserted_at_max``: a row ingested after the marker that only the copy pass
+ sees gets a cleaned twin whose original is never deleted.
Honors the optional ``hogql_predicate`` on the request the same way
``_event_removal_where`` does, so an operator can scope a property removal
@@ -187,10 +191,15 @@ def _property_removal_where(
when the worker holds a different DB connection from the test/request
transaction.
- The delete pass additionally passes ``inserted_at_max``: cleaned re-inserts
- are stamped with that exact value, so ``inserted_at < marker`` skips them.
- Legacy rows may have ``inserted_at IS NULL`` and are still originals to
- delete — the NULL branch keeps them in scope.
+ ``inserted_at_max`` bounds both passes: cleaned re-inserts are stamped with
+ that exact value, so ``inserted_at < marker`` skips them. Legacy rows may
+ have ``inserted_at IS NULL`` and are still originals to delete — the NULL
+ branch keeps them in scope.
+
+ ``exclude_cleaned_from`` (a fully-qualified table name, copy pass only)
+ additionally skips rows whose uuid already has a cleaned twin stamped with
+ the marker, so however many times the job re-runs, at most one cleaned copy
+ of each original ever exists. Requires ``inserted_at_max``.
"""
presence_clauses: list[str] = []
if ctx.properties:
@@ -230,6 +239,14 @@ def _property_removal_where(
# same truncation in the mutation, so both sides must use the cast.
parts.append("AND (inserted_at IS NULL OR inserted_at < toDateTime64(%(inserted_at_max)s, 6, 'UTC'))")
params["inserted_at_max"] = inserted_at_max
+ if exclude_cleaned_from is not None:
+ if inserted_at_max is None:
+ raise ValueError("exclude_cleaned_from requires inserted_at_max (the cleaned-rows marker)")
+ parts.append(
+ f"AND uuid NOT IN (SELECT uuid FROM {exclude_cleaned_from} "
+ "WHERE team_id = %(team_id)s AND timestamp >= %(start_time)s AND timestamp < %(end_time)s "
+ "AND inserted_at = toDateTime64(%(inserted_at_max)s, 6, 'UTC'))"
+ )
return " ".join(p for p in parts if p), params
@@ -474,6 +491,7 @@ def load_property_removal_request(
) -> DeletionRequestContext:
"""Load and validate a property removal request, transition to IN_PROGRESS."""
from django.db import transaction
+ from django.utils import timezone
with transaction.atomic():
request = (
@@ -499,6 +517,12 @@ def load_property_removal_request(
_record_execution_attempt(request)
+ # Set once and reused verbatim by every retry: all attempts must agree on which
+ # inserted_at value identifies cleaned re-inserts, or re-runs duplicate them.
+ if request.property_removal_marker is None:
+ request.property_removal_marker = timezone.now()
+ request.save(update_fields=["property_removal_marker", "updated_at"])
+
events_desc = "<all events>" if request.delete_all_events else f"{request.events}"
context.log.info(
f"Processing property removal {request.pk}: "
@@ -532,6 +556,7 @@ def load_property_removal_request(
person_properties=person_properties,
delete_all_events=request.delete_all_events,
hogql_predicate=request.hogql_predicate or "",
+ inserted_at_marker=request.property_removal_marker,
)
@@ -548,12 +573,14 @@ def process_property_removal_per_shard(
1. Discover affected DEFAULT materialized columns for both ``properties``
and ``person_properties``.
2. Create the temp table.
- 3. Copy matching events from sharded_events into temp. Presence check covers
- JSON ``properties`` and/or ``person_properties`` AND their materialized
- columns — a row can carry the value in the column alone, and ``SELECT *``
- would otherwise leave it behind.
+ 3. Copy matching events that were ingested before the marker and do not
+ already have a cleaned twin from sharded_events into temp. Presence check
+ covers JSON ``properties`` and/or ``person_properties`` AND their
+ materialized columns — a row can carry the value in the column alone, and
+ ``SELECT *`` would otherwise leave it behind.
4. Mutate the temp table: drop JSON keys from each targeted column, reset
- materialized columns to their defaults, stamp ``inserted_at = marker``.
+ materialized columns to their defaults, stamp ``inserted_at = marker``
+ and bump ``_timestamp`` (the ReplacingMergeTree version) to the marker.
5. Verify no target presence remains in temp (JSON or materialized columns).
6. Re-insert cleaned events into sharded_events.
7. Lightweight-delete the originals from sharded_events. Same presence check
@@ -561,24 +588,25 @@ def process_property_removal_per_shard(
cleaned re-inserts (stamped with that exact marker) are skipped.
8. Drop the temp table.
- Steps 3 and 7 use the same predicate (modulo the ``inserted_at`` clause on
- delete), generated by ``_property_removal_where`` from the same per-shard
- ``mat_cols`` / ``person_mat_cols`` lists, so they cannot drift.
+ Steps 3 and 7 use the same predicate with the identical ``inserted_at_max``
+ (modulo the anti-join on copy), generated by ``_property_removal_where`` from
+ the same per-shard ``mat_cols`` / ``person_mat_cols`` lists, so they cannot
+ drift. The marker is persisted on the request by the load op, so every retry
+ agrees on which rows are already cleaned and never re-inserts a second twin.
"""
- from django.utils import timezone
-
source = EVENTS_DATA_TABLE()
temp = _temp_table_name(deletion_request.team_id, deletion_request.request_id)
db = django_settings.CLICKHOUSE_DATABASE
properties = deletion_request.properties
person_properties = deletion_request.person_properties
- marker = timezone.now()
- deletion_request.inserted_at_marker = marker
+ marker = deletion_request.inserted_at_marker
+ if marker is None:
+ raise dagster.Failure(description="property_removal_marker missing; load_property_removal_request must set it")
# Format the marker as a string with microseconds — clickhouse-driver serializes Python
# datetime values with second precision, which causes the cleaned re-inserts to be stamped
# with a truncated inserted_at and the originals-delete predicate to mismatch by sub-second
# offsets. Passing as ISO string and casting in SQL preserves the full precision.
- marker_str = marker.strftime("%Y-%m-%d %H:%M:%S.%f")
+ marker_str = marker.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S.%f")
# HogQL compilation reaches into the Django ORM (Team lookup); compile once on the main
# thread before dispatching per-shard work, otherwise the worker thread's DB connection
# may not see the request/test transaction.
@@ -618,7 +646,9 @@ def process_property_removal_per_shard(
deletion_request,
mat_cols=affected_mat_cols,
person_mat_cols=affected_person_mat_cols,
+ inserted_at_max=marker_str,
hogql_compiled=hogql_compiled,
+ exclude_cleaned_from=f"{db}.{source}",
)
execute("truncate-temp", f"TRUNCATE TABLE IF EXISTS {db}.{temp}")
execute(
@@ -640,6 +670,15 @@ def process_property_removal_per_shard(
# Cast to DateTime64(6) so microseconds survive the parameter binding —
# mirrors the cast in the delete predicate so both sides agree on the marker.
update_parts.append("inserted_at = toDateTime64(%(inserted_at_marker)s, 6, 'UTC')")
+ # Bump the ReplacingMergeTree version (ver=_timestamp): the cleaned row shares its
+ # original's sorting key AND (via SELECT *) its version, so a background merge would
+ # keep an arbitrary one of the pair. With the marker as version, merges
+ # deterministically prefer the cleaned row and identical cleaned twins collapse.
+ # +1 second because _timestamp is second-precision while the copy/delete bound
+ # (inserted_at < marker) is microsecond-precision: an original ingested within the
+ # marker's second is in scope but shares its truncated second — the version must be
+ # STRICTLY greater or the merge tie stays arbitrary for exactly those rows.
+ update_parts.append("_timestamp = toDateTime(toDateTime64(%(inserted_at_marker)s, 6, 'UTC')) + 1")
for col_name, is_nullable in affected_mat_cols + affected_person_mat_cols:
default = "NULL" if is_nullable else "''"
update_parts.append(f"`{col_name}` = {default}")
@@ -729,6 +768,85 @@ def process_property_removal_per_shard(
return deletion_request
[email protected](tags=OWNER_TAG)
+def verify_property_removal(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ deletion_request: DeletionRequestContext,
+) -> DeletionRequestContext:
+ """Fail the run when property removal left originals behind or duplicated cleaned rows.
+
+ Two checks over the distributed ``events`` table:
+ - remaining: rows still matching the full removal predicate (same builder and
+ ``inserted_at_max`` bound as the copy/delete passes, so post-marker ingestion
+ cannot wedge verification). Non-zero means an original survived.
+ - duplicates: uuids appearing more than once among marker-stamped rows. Non-zero
+ means a cleaned re-insert was duplicated.
+ """
+ marker = deletion_request.inserted_at_marker
+ if marker is None:
+ raise dagster.Failure(description="property_removal_marker missing; load_property_removal_request must set it")
+ marker_str = marker.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S.%f")
+ hogql_compiled = compile_hogql_predicate(deletion_request)
+ properties = deletion_request.properties
+ person_properties = deletion_request.person_properties
+
+ def check(client: Client) -> tuple[int, int]:
+ mat_cols = (
+ _get_affected_mat_columns(client, "events", properties, table_column="properties") if properties else []
+ )
+ person_mat_cols = (
+ _get_affected_mat_columns(client, "events", person_properties, table_column="person_properties")
+ if person_properties
+ else []
+ )
+ predicate, params = _property_removal_where(
+ deletion_request,
+ mat_cols=mat_cols,
+ person_mat_cols=person_mat_cols,
+ inserted_at_max=marker_str,
+ hogql_compiled=hogql_compiled,
+ )
+ remaining = client.execute(
+ f"SELECT count() FROM events WHERE {predicate} AND _row_exists = 1",
+ params,
+ settings={"max_execution_time": 1800},
+ )[0][0]
+ duplicates = client.execute(
+ "SELECT count() FROM ("
+ "SELECT uuid FROM events "
+ "WHERE team_id = %(team_id)s AND timestamp >= %(start_time)s AND timestamp < %(end_time)s "
+ "AND inserted_at = toDateTime64(%(marker)s, 6, 'UTC') AND _row_exists = 1 "
+ "GROUP BY uuid HAVING count() > 1)",
+ {
+ "team_id": deletion_request.team_id,
+ "start_time": deletion_request.start_time,
+ "end_time": deletion_request.end_time,
+ "marker": marker_str,
+ },
+ settings={"max_execution_time": 1800},
+ )[0][0]
+ return remaining, duplicates
+
+ remaining, duplicates = cluster.any_host(check).result()
+ context.add_output_metadata(
+ {
+ "remaining_originals": dagster.MetadataValue.int(remaining),
+ "duplicated_cleaned_uuids": dagster.MetadataValue.int(duplicates),
+ }
+ )
+ if remaining or duplicates:
+ raise dagster.Failure(
+ description=(
+ f"Property removal verification failed for request {deletion_request.request_id}: "
+ f"{remaining} events still match the removal predicate, "
+ f"{duplicates} cleaned uuids are duplicated. Investigate before re-approving."
+ )
+ )
+ context.log.info("Property removal verified: no residual originals, no duplicated cleaned rows.")
+ return deletion_request
+
+
# ---------------------------------------------------------------------------
# Person removal ops
# ---------------------------------------------------------------------------
@@ -1052,9 +1170,11 @@ def data_deletion_request_event_removal():
@dagster.job(tags=OWNER_TAG, hooks={mark_deletion_failed})
def data_deletion_request_property_removal():
"""Execute an approved property removal request: per shard, copy events, drop properties,
- re-insert, delete originals, drop temp."""
+ re-insert, delete originals, drop temp — then verify completeness and uniqueness before
+ finalizing."""
request = load_property_removal_request()
request = process_property_removal_per_shard(request)
+ request = verify_property_removal(request)
finalize_deletion_request(request)
diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.py
index 8b132d18d4d5..83263380e73c 100644
--- a/posthog/dags/tests/test_data_deletion_requests.py
+++ b/posthog/dags/tests/test_data_deletion_requests.py
@@ -1,6 +1,6 @@
import json
from dataclasses import replace
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from functools import partial
from uuid import uuid4
@@ -12,7 +12,7 @@ from clickhouse_driver import Client
from dagster import build_op_context
from posthog.clickhouse.adhoc_events_deletion import ADHOC_EVENTS_DELETION_TABLE
-from posthog.clickhouse.cluster import ClickhouseCluster
+from posthog.clickhouse.cluster import ClickhouseCluster, LightweightDeleteMutationRunner
from posthog.dags.data_deletion_requests import (
DataDeletionRequestConfig,
DeletionRequestContext,
@@ -671,6 +671,29 @@ def test_load_property_removal_request_rejects_empty_properties():
load_property_removal_request(context, config)
+def test_load_property_removal_request_persists_marker_across_attempts():
+ request = DataDeletionRequest.objects.create(
+ team_id=PROP_TEAM_ID,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=["$ip"],
+ start_time=datetime.now() - timedelta(days=7),
+ end_time=datetime.now(),
+ status=RequestStatus.APPROVED,
+ )
+ config = DataDeletionRequestConfig(request_id=str(request.pk))
+
+ first = load_property_removal_request(build_op_context(), config)
+ request.refresh_from_db()
+ assert request.property_removal_marker is not None
+ assert first.inserted_at_marker == request.property_removal_marker
+
+ DataDeletionRequest.objects.filter(pk=request.pk).update(status=RequestStatus.APPROVED)
+ second = load_property_removal_request(build_op_context(), config)
+ assert second.inserted_at_marker == first.inserted_at_marker
+
+
def _insert_events_with_person_properties(events: list[tuple], client: Client) -> None:
"""Insert events with (team_id, event, uuid, timestamp, person_properties_json)."""
client.execute(
@@ -1453,6 +1476,151 @@ def test_full_job_property_removal_clears_materialized_columns(
cluster.any_host(partial(_drop_default_mat_columns, col_defs)).result()
+def _insert_events_with_properties_and_inserted_at(events: list[tuple], client: Client) -> None:
+ # writable_events does not expose inserted_at, so write the shard-local table directly.
+ client.execute(
+ "INSERT INTO sharded_events (team_id, event, uuid, distinct_id, timestamp, properties, inserted_at) VALUES",
+ events,
+ )
+
+
+def _count_marker_rows(team_id: int, marker: datetime, client: Client) -> tuple[int, int]:
+ marker_str = marker.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S.%f")
+ row = client.execute(
+ "SELECT countIf(_timestamp = toDateTime(toDateTime64(%(marker)s, 6, 'UTC')) + 1), count() "
+ "FROM events "
+ "WHERE team_id = %(team_id)s AND inserted_at = toDateTime64(%(marker)s, 6, 'UTC')",
+ {"team_id": team_id, "marker": marker_str},
+ )
+ return row[0][0], row[0][1]
+
+
+def test_full_job_property_removal_leaves_events_ingested_after_marker_untouched(cluster: ClickhouseCluster):
+ from django.utils import timezone
+
+ marker = timezone.now()
+ now = datetime.now()
+ props = json.dumps({"secret": "value", "keep": "yes"})
+ in_scope = [
+ (PROP_TEAM_ID, "$pageview", uuid4(), "user-1", now - timedelta(hours=i + 1), props, marker - timedelta(hours=1))
+ for i in range(5)
+ ]
+ late = [
+ (PROP_TEAM_ID, "$pageview", uuid4(), "user-1", now - timedelta(hours=1), props, marker + timedelta(hours=1))
+ ]
+ cluster.any_host(partial(_insert_events_with_properties_and_inserted_at, in_scope + late)).result()
+
+ request = DataDeletionRequest.objects.create(
+ team_id=PROP_TEAM_ID,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=["secret"],
+ start_time=now - timedelta(days=7),
+ end_time=now + timedelta(minutes=1),
+ status=RequestStatus.APPROVED,
+ property_removal_marker=marker,
+ )
+ result = data_deletion_request_property_removal.execute_in_process(
+ run_config={"ops": {"load_property_removal_request": {"config": {"request_id": str(request.pk)}}}},
+ resources={"cluster": cluster},
+ )
+ assert result.success
+
+ # No duplicates: 5 cleaned + 1 late original, nothing else.
+ assert cluster.any_host(partial(_count_events_by_name, PROP_TEAM_ID, "$pageview")).result() == 6
+ all_props = cluster.any_host(partial(_get_properties, PROP_TEAM_ID, "$pageview")).result()
+ assert sum(1 for p in all_props if "secret" in p) == 1 # only the late arrival keeps it
+
+
+def test_full_job_property_removal_rerun_after_delete_failure_does_not_duplicate(cluster: ClickhouseCluster):
+ now = datetime.now()
+ props = json.dumps({"secret": "value", "keep": "yes"})
+ events = [(PROP_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i + 1), props) for i in range(20)]
+ cluster.any_host(partial(_insert_events_with_properties, events)).result()
+
+ request = DataDeletionRequest.objects.create(
+ team_id=PROP_TEAM_ID,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=["secret"],
+ start_time=now - timedelta(days=7),
+ end_time=now + timedelta(minutes=1),
+ status=RequestStatus.APPROVED,
+ )
+ run_config = {"ops": {"load_property_removal_request": {"config": {"request_id": str(request.pk)}}}}
+
+ # Attempt 1 dies after cleaned rows were re-inserted but before originals are deleted.
+ with patch.object(LightweightDeleteMutationRunner, "__call__", side_effect=Exception("delete-originals failed")):
+ failed = data_deletion_request_property_removal.execute_in_process(
+ run_config=run_config, resources={"cluster": cluster}, raise_on_error=False
+ )
+ assert not failed.success
+ assert cluster.any_host(partial(_count_events_by_name, PROP_TEAM_ID, "$pageview")).result() == 40
+
+ request.refresh_from_db()
+ assert request.status == RequestStatus.FAILED
+ marker = request.property_removal_marker
+ assert marker is not None
+
+ DataDeletionRequest.objects.filter(pk=request.pk).update(status=RequestStatus.APPROVED)
+ rerun = data_deletion_request_property_removal.execute_in_process(
+ run_config=run_config, resources={"cluster": cluster}
+ )
+ assert rerun.success
+
+ assert cluster.any_host(partial(_count_events_by_name, PROP_TEAM_ID, "$pageview")).result() == 20
+ for row_props in cluster.any_host(partial(_get_properties, PROP_TEAM_ID, "$pageview")).result():
+ assert "secret" not in row_props
+ assert "keep" in row_props
+ # Cleaned rows carry the persisted marker on inserted_at AND the bumped _timestamp version,
+ # so a replacing merge deterministically keeps them over any residual original.
+ stamped, total = cluster.any_host(partial(_count_marker_rows, PROP_TEAM_ID, marker)).result()
+ assert total == 20
+ assert stamped == 20
+
+
+def test_full_job_property_removal_fails_on_residual_duplicates(cluster: ClickhouseCluster):
+ from django.utils import timezone
+
+ marker = timezone.now() - timedelta(minutes=5)
+ now = datetime.now()
+ dup_uuid = uuid4()
+ clean = json.dumps({"keep": "yes"})
+ dirty = json.dumps({"secret": "value", "keep": "yes"})
+ # Two cleaned twins of one uuid from a hypothetically-broken earlier attempt. All three rows
+ # carry different distinct_ids (distinct sorting keys) so a background replacing merge cannot
+ # collapse any of them mid-test — byte-identical twins self-heal within seconds, un-seeding
+ # the corruption before verification gets to observe it.
+ rows = [
+ (PROP_TEAM_ID, "$pageview", dup_uuid, "user-0", now - timedelta(hours=1), dirty, marker - timedelta(hours=1)),
+ (PROP_TEAM_ID, "$pageview", dup_uuid, "user-1", now - timedelta(hours=1), clean, marker),
+ (PROP_TEAM_ID, "$pageview", dup_uuid, "user-2", now - timedelta(hours=1), clean, marker),
+ ]
+ cluster.any_host(partial(_insert_events_with_properties_and_inserted_at, rows)).result()
+
+ request = DataDeletionRequest.objects.create(
+ team_id=PROP_TEAM_ID,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=["secret"],
+ start_time=now - timedelta(days=7),
+ end_time=now + timedelta(minutes=1),
+ status=RequestStatus.APPROVED,
+ property_removal_marker=marker,
+ )
+ result = data_deletion_request_property_removal.execute_in_process(
+ run_config={"ops": {"load_property_removal_request": {"config": {"request_id": str(request.pk)}}}},
+ resources={"cluster": cluster},
+ raise_on_error=False,
+ )
+ assert not result.success
+ request.refresh_from_db()
+ assert request.status == RequestStatus.FAILED
+
+
@pytest.mark.django_db
def test_load_person_removal_request_transitions_to_in_progress():
request = DataDeletionRequest.objects.create(
diff --git a/posthog/migrations/1252_datadeletionrequest_property_removal_marker.py b/posthog/migrations/1252_datadeletionrequest_property_removal_marker.py
new file mode 100644
index 000000000000..70a4321e6049
--- /dev/null
+++ b/posthog/migrations/1252_datadeletionrequest_property_removal_marker.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.14 on 2026-07-13 10:54
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1251_alter_integration_kind"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="datadeletionrequest",
+ name="property_removal_marker",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="inserted_at/_timestamp stamp applied to cleaned re-inserts of this property_removal request. Set once on the first execution attempt and reused by every retry so re-runs recognize already-cleaned rows and never insert a second copy. Cleared when deletion criteria change.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index ca1f440a2569..c4e1282ca1e0 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1251_alter_integration_kind
+1252_datadeletionrequest_property_removal_marker
diff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.py
index cee42257cc9b..6bc81e7c80b2 100644
--- a/posthog/models/data_deletion_request.py
+++ b/posthog/models/data_deletion_request.py
@@ -369,6 +369,13 @@ class DataDeletionRequest(UUIDModel):
blank=True,
help_text="When execution was most recently attempted (updated on every APPROVED → IN_PROGRESS transition).",
)
+ property_removal_marker = models.DateTimeField(
+ null=True,
+ blank=True,
+ help_text="inserted_at/_timestamp stamp applied to cleaned re-inserts of this property_removal "
+ "request. Set once on the first execution attempt and reused by every retry so re-runs recognize "
+ "already-cleaned rows and never insert a second copy. Cleared when deletion criteria change.",
+ )
# The team_id this request was loaded from the DB with (None until loaded). Set by from_db so
# clean() can reject retargeting an existing request at a different team. Not a model field.