: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
fix(clickhouse): delete from events_json one partition at a time (#114600)
Rory Shanks2cfb683a2415
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.pyindex c1f620e09cdc..ae99cd723fbf 100644--- a/posthog/dags/deletes.py+++ b/posthog/dags/deletes.py@@ -44,8 +44,10 @@ from posthog.models.deletion_targets import (EVENTS_TARGETS,PERSONAL_DATA_TARGETS,DeletionTarget,+ TargetPlacement,_any_node_has,resolve_placements,+ shards_by_partition,surviving_rows_sql,sweep_clusters,)@@ -172,15 +174,38 @@ def _start_of_month_after(partition: int) -> datetime:# 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(- (dictHas(%(pending_deletes_dictionary)s, (team_id, %(person_deletion_type)s, person_id))+_PERSON_ARM = """(dictHas(%(pending_deletes_dictionary)s, (team_id, %(person_deletion_type)s, person_id))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))))-)"""+ AND (inserted_at IS NULL OR inserted_at <= dictGet(%(pending_deletes_dictionary)s, 'created_at', (team_id, %(person_deletion_type)s, person_id))))"""+_TEAM_ARM = "(dictHas(%(pending_deletes_dictionary)s, (team_id, %(team_deletion_type)s, team_id)))"+_EVENT_ARM = "(dictHas(%(pending_deletes_dictionary)s, (team_id, %(event_deletion_type)s, uuid)))"+_ADHOC_ARM = """(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))))"""+++def _any_of(*arms: str) -> str:+ return "or(\n " + ",\n ".join(arms) + "\n)"+++_DELETE_PREDICATE = _any_of(_PERSON_ARM, _TEAM_ARM, _EVENT_ARM, _ADHOC_ARM)++# sharded_events_json writes deletes as patch parts, which suit the few rows a person, event or+# adhoc deletion names. The team_id sets come from the dictionaries and lead the sorting key, so the+# read skips the granules of every team with nothing to delete.+_PATCH_PART_DELETE_PREDICATE = (+ _any_of(_PERSON_ARM, _EVENT_ARM, _ADHOC_ARM)+ + """+ AND (team_id IN (SELECT DISTINCT team_id FROM dictionary(%(pending_deletes_dictionary)s) WHERE deletion_type IN (%(person_deletion_type)s, %(event_deletion_type)s))+ OR team_id IN (SELECT team_id FROM dictionary(%(adhoc_event_deletes_dictionary)s)))"""+)++# A team deletion removes every row the team has, which as patch parts would store one patch row per+# deleted row until merges fold them in. A mutation rewrites the affected parts instead.+_TEAM_DELETE_PREDICATE = (+ _TEAM_ARM+ + """+ AND team_id IN (SELECT team_id FROM dictionary(%(pending_deletes_dictionary)s) WHERE deletion_type = %(team_deletion_type)s)"""+)# Embedding documents are keyed by the id of the thing they describe, and an Event deletion's key is@@ -644,6 +669,51 @@ def load_and_verify_adhoc_event_deletes_dictionary(return dictionary+def _delete_with_patch_parts(+ placement: TargetPlacement,+ parameters: dict[str, str | int],+ reuse_floor: datetime,+ by_shard: dict[int, list[MutationWaiter]],+) -> None:+ """Delete from a patch-part target one partition at a time, and team deletions as a mutation.++ A lightweight delete whose WHERE cannot be pruned holds a block number open in every partition+ until it finishes, which stalls merges across the table. One statement per partition, sent only to+ the shards that hold it, keeps that to a single partition. Each statement has finished writing its+ patch part when it returns, so only the team mutation leaves anything to wait on.+ """+ for partition_id, shards in sorted(shards_by_partition(placement).items()):+ runner = LightweightDeleteMutationRunner(+ table=placement.target.data_table,+ predicate=_PATCH_PART_DELETE_PREDICATE,+ parameters=parameters,+ partition=partition_id,+ patch_parts=True,+ )+ placement.cluster.map_any_host_in_shards(dict.fromkeys(shards, runner)).result()++ [[pending_team_deletes]] = placement.cluster.any_host(+ Query(+ "SELECT count() FROM dictionary(%(pending_deletes_dictionary)s) WHERE deletion_type = %(team_deletion_type)s",+ parameters,+ )+ ).result()+ if not pending_team_deletes:+ return++ team_runner = LightweightDeleteMutationRunner(+ table=placement.target.data_table,+ predicate=_TEAM_DELETE_PREDICATE,+ parameters=parameters,+ reuse_since=reuse_floor,+ # The session can default DELETE to patch parts, so the mutation mode is named here.+ settings={"lightweight_delete_mode": "alter_update"},+ )+ for host, mutation in placement.cluster.map_one_host_per_shard(team_runner).result().items():+ if host.shard_num is not None:+ by_shard.setdefault(host.shard_num, []).append(mutation)++@dagster.opdef delete_events(context: dagster.OpExecutionContext,@@ -695,31 +765,29 @@ def delete_events(# Every target this run sweeps must get the delete, or rows survive on the one that missed it.placements = resolve_placements(cluster, _targets_named(swept_targets))reuse_floor = _mutation_reuse_floor(cluster)- delete_mutation_runners = [- (- placement,- LightweightDeleteMutationRunner(- table=placement.target.data_table,- predicate=_DELETE_PREDICATE,- parameters=_delete_predicate_params(- load_and_verify_deletes_dictionary, load_and_verify_adhoc_event_deletes_dictionary- ),- reuse_since=reuse_floor,- patch_parts=placement.target.uses_patch_parts,- ),- )- for placement in placements- ]+ parameters = _delete_predicate_params(+ load_and_verify_deletes_dictionary, load_and_verify_adhoc_event_deletes_dictionary+ )waiters: dict[tuple[str, NodeRole], dict[int, list[MutationWaiter]]] = {}- for placement, delete_mutation_runner in delete_mutation_runners:+ for placement in placements:+ key = (placement.cluster.data_cluster_name, placement.cluster.shard_role)+ by_shard = waiters.setdefault(key, {})+ if placement.target.uses_patch_parts:+ _delete_with_patch_parts(placement, parameters, reuse_floor, by_shard)+ continue+ runner = LightweightDeleteMutationRunner(+ table=placement.target.data_table,+ predicate=_DELETE_PREDICATE,+ parameters=parameters,+ reuse_since=reuse_floor,+ )# placement.cluster, not the job's handle: the dictionary the predicate joins was created# on every cluster here, but the storage table only exists on this one.- for host, mutation in placement.cluster.map_one_host_per_shard(delete_mutation_runner).result().items():+ for host, mutation in placement.cluster.map_one_host_per_shard(runner).result().items():if host.shard_num is not None:- key = (placement.cluster.data_cluster_name, placement.cluster.shard_role)- by_shard = waiters.setdefault(key, {})by_shard.setdefault(host.shard_num, []).append(mutation)+ waiters = {key: by_shard for key, by_shard in waiters.items() if by_shard}cluster_mutations: ClusterShardMutations = {key: {shard_num: MutationWaiters(waiters=shard_waiters) for shard_num, shard_waiters in by_shard.items()}diff --git a/posthog/dags/person_overrides.py b/posthog/dags/person_overrides.pyindex 4d820c359791..4ccbc6f8d8f3 100644--- a/posthog/dags/person_overrides.py+++ b/posthog/dags/person_overrides.py@@ -9,7 +9,7 @@ from clickhouse_driver import Clientfrom posthog import settingsfrom posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds-from posthog.clickhouse.cluster import ClickhouseCluster, MutationWaiter, Query, wait_for_mutations_on_shards+from posthog.clickhouse.cluster import ClickhouseCluster, MutationWaiter, wait_for_mutations_on_shardsfrom posthog.dags.common import JobOwnersfrom posthog.dags.common.overrides_manager import OverridesSnapshotDictionary, OverridesSnapshotTablefrom posthog.dags.common.staged_dictionary import (@@ -18,7 +18,13 @@ from posthog.dags.common.staged_dictionary import (load_and_verify_on_every_cluster,)from posthog.dataclasses import frozen-from posthog.models.deletion_targets import SQUASH_TARGETS, TargetPlacement, resolve_placements, sweep_clusters+from posthog.models.deletion_targets import (+ SQUASH_TARGETS,+ TargetPlacement,+ resolve_placements,+ shards_by_partition,+ sweep_clusters,+)from posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE@@ -299,7 +305,7 @@ def run_person_id_update_mutations(# statement per partition keeps both to a single partition, so the other partitions keep merging.# The patch part is written before enqueue_on_shards returns, so these run in series.for placement in patch_part_placements:- for partition_id, shards in sorted(_shards_by_partition(placement).items()):+ for partition_id, shards in sorted(shards_by_partition(placement).items()):runner = dictionary.update_mutation_runner_for(placement.target.data_table, partition_id=partition_id)runner.patch_parts = Truerunner.enqueue_on_shards(placement.cluster, shards)@@ -311,28 +317,6 @@ def run_person_id_update_mutations(return dictionary-def _shards_by_partition(placement: TargetPlacement) -> dict[str, set[int]]:- """Every data partition of the target's table, mapped to the shards that hold it.-- Every replica is read because a partition that one replica has not fetched yet still holds rows- that the squash must rewrite.- """- query = Query(- """- SELECT DISTINCT partition_id- FROM system.parts- WHERE database = %(database)s AND table = %(table)s AND active AND NOT startsWith(partition_id, 'patch-')- """,- {"database": settings.CLICKHOUSE_DATABASE, "table": placement.target.data_table},- )- shards_by_partition: dict[str, set[int]] = {}- for host, rows in placement.cluster.map_all_hosts(query).result().items():- assert host.shard_num is not None- for (partition_id,) in rows:- shards_by_partition.setdefault(partition_id, set()).add(host.shard_num)- return shards_by_partition--@dagster.opdef start_overrides_delete_mutations(cluster: dagster.ResourceParam[ClickhouseCluster],diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.pyindex c9633f54a1cc..8614d03451a8 100644--- a/posthog/dags/tests/test_deletes.py+++ b/posthog/dags/tests/test_deletes.py@@ -33,6 +33,7 @@ from posthog.dags.deletes import (_count_unswept_rows,_delete_predicate_params,cleanup_old_events_by_partition,+ delete_events,deletes_job,ensure_no_concurrent_deletes_run,manual_deletes_job,@@ -42,12 +43,13 @@ from posthog.dags.deletes import (plan_old_events_cleanup,resolve_sweep_targets,run_deletes_after_manual_trigger,+ wait_for_delete_mutations_in_shards,)from posthog.dags.person_overrides import squash_person_overridesfrom posthog.dags.tests.conftest import insert_flag_evaluationsfrom posthog.models.async_deletion import AsyncDeletion, DeletionTypefrom posthog.models.deletion_targets import DEFAULT_DELETION_TARGETS, EVENTS, PERSONAL_DATA_TARGETS, TargetPlacement-from posthog.models.event.sql import EVENTS_DATA_TABLE+from posthog.models.event.sql import EVENTS_DATA_TABLE, EVENTS_JSON_DATA_TABLEfrom posthog.models.events_retention_config import OrganizationEventsRetentionConfig, TeamEventsRetentionConfigfrom posthog.models.organization import Organizationfrom posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE@@ -1093,6 +1095,76 @@ def test_a_target_on_another_cluster_is_also_counted_on_its_storage_table(clustecluster.any_host(table.drop).result()+def test_events_json_deletes_reach_every_partition_for_person_and_team_deletions(cluster: ClickhouseCluster):+ # sharded_events_json deletes person rows one partition at a time with patch parts, and team rows+ # with a separate mutation. A partition the loop misses, or a team arm left out of both, keeps+ # rows the request is about to be marked verified for.+ person_team, deleted_team = 424250, 424251+ person_uuid, kept_person_uuid = UUID(int=21), UUID(int=22)+ created_at = datetime(2026, 8, 28, 10, 0, 0)++ table = PendingDeletesTable(timestamp=created_at)+ dictionary = PendingDeletesDictionary(source=table)+ adhoc = AdhocEventDeletesDictionary(source=AdhocEventDeletesTable())++ def insert_deletions(client: Client) -> None:+ client.execute(+ table.populate_query,+ [+ {+ "id": id,+ "deletion_type": int(deletion_type),+ "key": key,+ "group_type_index": None,+ "created_at": created_at,+ "delete_verified_at": None,+ "created_by_id": None,+ "team_id": team_id,+ }+ for id, deletion_type, key, team_id in [+ (1, DeletionType.Person, str(person_uuid), person_team),+ (2, DeletionType.Team, str(deleted_team), deleted_team),+ ]+ ],+ )++ kept = UUID(int=2003)+ rows = [+ (UUID(int=2001), person_team, person_uuid, created_at - relativedelta(months=1)),+ (UUID(int=2002), person_team, person_uuid, created_at - timedelta(hours=1)),+ (kept, person_team, kept_person_uuid, created_at - timedelta(hours=1)),+ (UUID(int=2004), deleted_team, person_uuid, created_at - relativedelta(months=1)),+ (UUID(int=2005), deleted_team, kept_person_uuid, created_at - timedelta(hours=1)),+ ]++ try:+ cluster.map_one_host_per_shard(Query(f"TRUNCATE TABLE {EVENTS_JSON_DATA_TABLE}")).result()+ cluster.any_host(+ Query(+ f"INSERT INTO {EVENTS_JSON_DATA_TABLE} (uuid, team_id, event, distinct_id, person_id, timestamp, inserted_at) VALUES",+ [(uuid, team_id, "$pageview", "d", person_id, ts, ts) for uuid, team_id, person_id, ts in rows],+ )+ ).result()+ cluster.any_host(table.create).result()+ cluster.any_host(insert_deletions).result()+ cluster.any_host(partial(dictionary.create, shards=1, max_execution_time=0, max_memory_usage=0)).result()+ cluster.any_host(dictionary.load).result()+ cluster.any_host(partial(adhoc.create, shards=1, max_execution_time=0, max_memory_usage=0)).result()+ cluster.any_host(adhoc.load).result()++ context = build_op_context()+ delete_mutations = delete_events(context, cluster, dictionary, adhoc, [EVENTS_JSON_DATA_TABLE])+ wait_for_delete_mutations_in_shards(context, cluster, delete_mutations)++ for surviving in cluster.map_all_hosts(Query(f"SELECT uuid FROM {EVENTS_JSON_DATA_TABLE}")).result().values():+ assert [row[0] for row in surviving] == [kept]+ finally:+ cluster.any_host(dictionary.drop).result()+ cluster.any_host(adhoc.drop).result()+ cluster.any_host(table.drop).result()++@pytest.mark.django_dbdef test_a_skipped_target_keeps_its_rows_while_the_rest_are_swept(cluster: ClickhouseCluster):# Seven ops resolve the sweep, and each one that misses the resolved list puts the run back todiff --git a/posthog/models/deletion_targets.py b/posthog/models/deletion_targets.pyindex 03ac042e3211..e94caf82b78e 100644--- a/posthog/models/deletion_targets.py+++ b/posthog/models/deletion_targets.py@@ -179,6 +179,28 @@ class TargetPlacement:cluster: ClickhouseCluster+def shards_by_partition(placement: TargetPlacement) -> dict[str, set[int]]:+ """Every data partition of the target's table, mapped to the shards that hold it.++ Every replica is read because a partition that one replica has not fetched yet still holds rows+ that a sweep must reach.+ """+ query = Query(+ """+ SELECT DISTINCT partition_id+ FROM system.parts+ WHERE database = %(database)s AND table = %(table)s AND active AND NOT startsWith(partition_id, 'patch-')+ """,+ {"database": settings.CLICKHOUSE_DATABASE, "table": placement.target.data_table},+ )+ shards_by_partition: dict[str, set[int]] = {}+ for host, rows in placement.cluster.map_all_hosts(query).result().items():+ assert host.shard_num is not None+ for (partition_id,) in rows:+ shards_by_partition.setdefault(partition_id, set()).add(host.shard_num)+ return shards_by_partition++EVENTS = DeletionTarget(data_table=EVENTS_DATA_TABLE(),read_table="events",