:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(clickhouse): drain event deletions queued in postgres into the adhoc sweep (#101472)
Tue Haulund976afed79fbb
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex 72adef2f47e2..7ef2946b9549 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -12,14 +12,18 @@ It is a property of every table that stores rows attributable to a person.| ------------------------ | -------------------------------- | -------------------------------------------------- || Person deletion (async) | `deletes_job` → `delete_events` | `team_id`, `person_id`, `timestamp`, `inserted_at` || Team deletion | `deletes_job` → `delete_events` | `team_id` |+| Event deletion (async) | `deletes_job` → `delete_events` | `team_id`, `uuid` || Queued uuid drain | `deletes_job` → `delete_events` | `team_id`, `uuid`, `inserted_at` || Person removal request | `delete_person_events_op` | `team_id`, `person_id`, `timestamp` || Event removal request | `execute_event_deletion` | `team_id`, `timestamp`, `event`, + HogQL || Property removal request | `process_property_removal_shard` | `properties`, `person_properties`, + HogQL |-The first four use only columns every target declares, so they apply unchanged to any registered table.+The first five use only columns every target declares, so they apply unchanged to any registered table.The last two need more, which is what the capability fields on `DeletionTarget` express.+The event arm deletes one row by `(team_id, uuid)` from an `AsyncDeletion` row of type `Event`, which any Postgres writer can queue in the same transaction as its own delete.+Replay Vision writes those rows: the recording-api inserts one per `$recording_observed` event in the same statement that deletes the recording's observations, so the queue entry and the observation delete commit together.+Team deletion for tables that are replicated rather than sharded runs through a separate per-table loop (`delete_team_data_from`), which dispatches to a single host.A sharded table must not be registered there — it would sweep one shard.The team arm inside `delete_events` covers sharded tables.diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.pyindex acab993cca43..ae32c0e4239b 100644--- a/posthog/dags/deletes.py+++ b/posthog/dags/deletes.py@@ -134,6 +134,9 @@ class MonthlyCleanupConfig(dagster.Config):# backdated events for a pending deletion fail verification for every tenant, and inserted_at is# stamped server-side (writable_events does not even expose the column), so the bound cannot be# forged the way the event timestamp can. NULL inserted_at predates the column and always counts.+# The event arm stays unbounded too: it names one uuid, so nothing can keep arriving under it, and a+# bound would skip a row that was still in the ingestion pipeline when the request was made and then+# mark the request verified with that row left behind.# The team arm stays unbounded: ingestion for a deleted team stops with its token, so late rows# there are pipeline stragglers the next run converges on, not a sustained obligation._DELETE_PREDICATE = """or(@@ -141,6 +144,7 @@ _DELETE_PREDICATE = """or(AND timestamp <= dictGet(%(pending_deletes_dictionary)s, 'created_at', (team_id, %(person_deletion_type)s, person_id))AND (inserted_at IS NULL OR inserted_at <= dictGet(%(pending_deletes_dictionary)s, 'created_at', (team_id, %(person_deletion_type)s, person_id)))),(dictHas(%(pending_deletes_dictionary)s, (team_id, %(team_deletion_type)s, team_id))),+ (dictHas(%(pending_deletes_dictionary)s, (team_id, %(event_deletion_type)s, uuid))),(dictHas(%(adhoc_event_deletes_dictionary)s, (team_id, uuid))AND (inserted_at IS NULL OR inserted_at <= dictGet(%(adhoc_event_deletes_dictionary)s, 'created_at', (team_id, uuid)))))"""@@ -425,7 +429,8 @@ def load_pending_deletions(pending_deletions = AsyncDeletion.objects.filter(Q(deletion_type=DeletionType.Person, created_at__lte=create_pending_deletions_table.timestamp)- | Q(deletion_type=DeletionType.Team),+ | Q(deletion_type=DeletionType.Team)+ | Q(deletion_type=DeletionType.Event),delete_verified_at__isnull=True,)if create_pending_deletions_table.team_id:@@ -577,7 +582,7 @@ def delete_events(f"""SELECT count()FROM {load_and_verify_deletes_dictionary.qualified_name}- WHERE deletion_type IN ({DeletionType.Person}, {DeletionType.Team})+ WHERE deletion_type IN ({DeletionType.Person}, {DeletionType.Team}, {DeletionType.Event})""")return result[0][0] if result else 0@@ -763,6 +768,7 @@ def _delete_predicate_params("pending_deletes_dictionary": pending_deletes_dictionary.qualified_name,"person_deletion_type": DeletionType.Person,"team_deletion_type": DeletionType.Team,+ "event_deletion_type": DeletionType.Event,"adhoc_event_deletes_dictionary": adhoc_event_deletes_dictionary.qualified_name,}diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.pyindex 8be9f8841b9e..3bfaabdaca84 100644--- a/posthog/dags/tests/test_deletes.py+++ b/posthog/dags/tests/test_deletes.py@@ -500,6 +500,36 @@ def test_full_job_adhoc_event_deletes(cluster: ClickhouseCluster):assert not any(cluster.map_all_hosts(deletes_dict.exists).result().values())+def test_full_job_deletes_events_queued_in_postgres(cluster: ClickhouseCluster):+ timestamp = (datetime.now() + timedelta(days=31)).replace(microsecond=0)+ events = [(9000 + i, f"distinct_id_{i}", UUID(int=9000 + i), timestamp) for i in range(20)]+ queued, kept = events[:5], events[5:]++ def insert_events(client: Client) -> None:+ client.execute("INSERT INTO writable_events (team_id, distinct_id, uuid, timestamp) VALUES", events)++ def surviving_uuids(client: Client) -> set[UUID]:+ result = client.execute("SELECT uuid FROM writable_events WHERE team_id >= 9000 AND team_id < 9020")+ return {row[0] for row in result} if isinstance(result, list) else set()++ cluster.any_host(insert_events).result()+ for team_id, _, uuid, _ in queued:+ deletion = AsyncDeletion.objects.create(team_id=team_id, deletion_type=DeletionType.Event, key=str(uuid))+ # The sweep only covers rows ingested before the request, so the request has to postdate the insert.+ deletion.created_at = timestamp+ deletion.save()++ deletes_job.execute_in_process(+ run_config={"ops": {"create_pending_deletions_table": {"config": {"timestamp": timestamp.isoformat()}}}},+ resources={"cluster": cluster},+ )++ surviving = cluster.any_host(surviving_uuids).result()+ assert surviving == {event[2] for event in kept}+ assert not AsyncDeletion.objects.filter(deletion_type=DeletionType.Event, delete_verified_at__isnull=True).exists()++@pytest.mark.django_dbdef test_find_partitions_to_cleanup(cluster: ClickhouseCluster):from dagster import build_op_contextdiff --git a/posthog/migrations/1361_asyncdeletion_event_deletion_type.py b/posthog/migrations/1361_asyncdeletion_event_deletion_type.pynew file mode 100644index 000000000000..5ce1fda4c268--- /dev/null+++ b/posthog/migrations/1361_asyncdeletion_event_deletion_type.py@@ -0,0 +1,24 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1360_validate_taggeditem_experiment_fk"),+ ]++ operations = [+ migrations.AlterField(+ model_name="asyncdeletion",+ name="deletion_type",+ field=models.PositiveSmallIntegerField(+ choices=[+ (0, "Team"),+ (1, "Person"),+ (2, "Group"),+ (3, "Cohort Stale"),+ (4, "Cohort Full"),+ (5, "Event"),+ ]+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 67dbc96e29a6..71e6596b2989 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1360_validate_taggeditem_experiment_fk+1361_asyncdeletion_event_deletion_typediff --git a/posthog/models/async_deletion/async_deletion.py b/posthog/models/async_deletion/async_deletion.pyindex 5c63ad994dfa..2024fc924ac0 100644--- a/posthog/models/async_deletion/async_deletion.py+++ b/posthog/models/async_deletion/async_deletion.py@@ -7,6 +7,8 @@ class DeletionType(models.IntegerChoices):Group = 2Cohort_stale = 3Cohort_full = 4+ # One event, keyed by its uuid; drained into `adhoc_events_deletion` by the Dagster deletes job.+ Event = 5# This model represents deletions that should delete (other, unrelated) data asyncdiff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex 766832b1338c..042db1ea0bd8 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -481,6 +481,8 @@ async def _run_mission(# Attribute every scanner generation to Replay Vision in LLM analytics so costs and traces roll up to the product.client = genai.AsyncClient(api_key=api_key,+ # Privacy mode keeps the recording's content out of the internal project, where it could not be deleted with the recording.+ posthog_privacy_mode=True,posthog_properties={"ai_product": "replay_vision","feature": "scanner",