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(deletions): let deletes_job sweep a table on another cluster (#89118)

Paweł Szczur4d43e46fb740
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.md
index 496354758f9d..ccf08ebe997d 100644
--- a/docs/internal/clickhouse-deletion-coverage.md
+++ b/docs/internal/clickhouse-deletion-coverage.md
@@ -54,12 +54,27 @@ Sweeps that iterate placements dispatch each target over `placement.cluster.shar
- `delete_person_events_op`
- `execute_event_deletion`, immediate mode
+- `deletes_job` → `delete_events`, which also has to put its dictionaries on the second cluster; see below
The rest are bound to a single handle and refuse rather than skip when a target has moved off it (`dispatchable_here`, `UnreachableTargetError`):
- Property removal. Its staging table is host-local and its fan-out is one op per shard of one cluster.
- The deferred queue fill. Both halves of its `INSERT` are host-local: the source table it reads and the `adhoc_events_deletion` queue it writes.
-- `deletes_job`. Its mutation predicate joins a pending-deletes dictionary that would have to be bootstrapped on the second cluster first — created, populated from Postgres, replicated, loaded and checksum-verified.
+
+### Getting the dictionaries onto the second cluster
+
+`delete_events` does not name the rows it removes. Its predicate joins two dictionaries, `pending_deletes_<timestamp>_dictionary` and `adhoc_events_deletion_dictionary`, so a mutation cannot run anywhere those are absent.
+
+Both reach every host of one cluster because their source table is replicated, and replication is exactly what a cluster boundary stops: a cluster with its own Keeper can never join that replica set.
+`adhoc_events_deletion` compounds it, being migration-managed and present only on the main cluster.
+
+So the rows are staged instead. One Parquet object per dictionary per run, written by the cluster itself with `INSERT INTO FUNCTION s3(...)`, and every host on the other cluster loads it through `SOURCE(CLICKHOUSE(QUERY 'SELECT ... FROM s3(...)'))`.
+ClickHouse has no S3 dictionary source, but that source runs its query locally, and the query can read anything the server can.
+
+- Nothing changes on a deployment where every target sits on the cluster the job connects to. The handle in hand is probed first, and no object is written.
+- The source tables stay where they are. `pending_deletes_<timestamp>` also carries the Postgres `AsyncDeletion` row ids that `mark_deletions_verified` reads back, and those never enter a dictionary.
+- `load_and_verify_deletes_dictionary` loads on every host of every cluster and fails the run unless all of them checksum alike. That is what catches a stale or missing object: without it the mutation there joins an empty dictionary, deletes nothing, and reports success.
+- Retention belongs to the bucket lifecycle policy, set through `DELETES_DICTIONARY_S3_*`. Nothing deletes the objects.
## Covered tables
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.py
index 58b4da4b1abe..f6c752e3b175 100644
--- a/posthog/dags/deletes.py
+++ b/posthog/dags/deletes.py
@@ -27,8 +27,9 @@ from posthog.clickhouse.cluster import (
from posthog.clickhouse.plugin_log_entries import PLUGIN_LOG_ENTRIES_TABLE
from posthog.dags.common import JobOwners
from posthog.dags.person_overrides import squash_person_overrides
+from posthog.dataclasses import frozen
from posthog.models.async_deletion import AsyncDeletion, DeletionType
-from posthog.models.deletion_targets import personal_data_tables
+from posthog.models.deletion_targets import resolve_placements, sweep_clusters
from posthog.models.event.deletion import events_data_tables
from posthog.models.event.sql import EVENTS_DATA_TABLE
from posthog.models.group.sql import GROUPS_TABLE
@@ -106,6 +107,10 @@ class MonthlyCleanupConfig(dagster.Config):
ShardMutations = dict[int, MutationWaiters]
+# Shard numbers are per cluster, so a sweep spanning two of them cannot key its waiters by shard
+# alone. Keyed by cluster name rather than by handle: the handle is recovered with
+# ClickhouseCluster.sibling, which is memoized, and a name survives the op boundary.
+ClusterShardMutations = dict[str, ShardMutations]
@dataclass
@@ -226,7 +231,58 @@ class AdhocEventDeletesTable(Table):
client.execute(f"OPTIMIZE TABLE {self.qualified_name} FINAL")
-@dataclass
+def _dictionary_s3_args(key: str, structure: str) -> str:
+ """Argument list for a ClickHouse ``s3(...)`` call over a staged dictionary payload.
+
+ Credentials are emitted only where an endpoint is configured, which is local, dev and test
+ object storage. On prod the endpoint is empty and the cluster reaches the bucket through its
+ attached IAM role, so no secret is ever interpolated into SQL.
+ """
+ path = f"{settings.DELETES_DICTIONARY_S3_PREFIX}/{key}"
+ endpoint = settings.DELETES_DICTIONARY_S3_ENDPOINT
+ if endpoint:
+ url = f"{endpoint}/{settings.DELETES_DICTIONARY_S3_BUCKET}/{path}"
+ creds = f"'{settings.OBJECT_STORAGE_ACCESS_KEY_ID}', '{settings.OBJECT_STORAGE_SECRET_ACCESS_KEY}', "
+ else:
+ bucket = settings.DELETES_DICTIONARY_S3_BUCKET
+ url = f"https://{bucket}.s3.{settings.DELETES_DICTIONARY_S3_REGION}.amazonaws.com/{path}"
+ creds = ""
+ # The structure sits inside a single-quoted SQL literal, so escape the quotes in a type like
+ # DateTime64(6, 'UTC') or they terminate the literal early.
+ escaped = " ".join(structure.split()).replace("'", "\\'")
+ return f"'{url}', {creds}'Parquet', '{escaped}'"
+
+
+@dataclass(frozen=True, kw_only=True)
+class StagedDictionary:
+ """A dictionary's rows copied to one Parquet object, for clusters that share no Keeper.
+
+ A dictionary's source table reaches every host of one cluster by replication, and replication
+ is exactly what a cluster boundary stops: a cluster with its own Keeper can never join that
+ replica set. An object each host reads for itself crosses the boundary instead, and both sides
+ load identical bytes, which is what makes comparing their checksums meaningful.
+ """
+
+ key: str
+ columns: str
+ structure: str
+
+ @property
+ def __args(self) -> str:
+ return _dictionary_s3_args(self.key, self.structure)
+
+ @property
+ def query(self) -> str:
+ """The dictionary SOURCE query, for hosts that cannot see the source table."""
+ return f"SELECT {self.columns} FROM s3({self.__args})"
+
+ def export(self, client: Client, source_query: str) -> None:
+ # Truncate rather than append: a retried run has to leave the object holding this run's
+ # rows alone, or the two clusters load different data and the checksum gate fails.
+ client.execute(f"INSERT INTO FUNCTION s3({self.__args}) {source_query} SETTINGS s3_truncate_on_insert=1")
+
+
+@frozen
class Dictionary(abc.ABC):
source: Table
@@ -244,9 +300,44 @@ class Dictionary(abc.ABC):
raise NotImplementedError()
@abc.abstractmethod
- def create(self, client: Client, shards: int, max_execution_time: int, max_memory_usage: int) -> None:
+ def create(
+ self,
+ client: Client,
+ shards: int,
+ max_execution_time: int,
+ max_memory_usage: int,
+ query: str | None = None,
+ ) -> None:
+ """``query`` overrides the SOURCE query, for a host that cannot see the source table."""
raise NotImplementedError()
+ @abc.abstractmethod
+ def staged(self) -> StagedDictionary:
+ """Where this dictionary's rows go so another cluster can load them; see StagedDictionary.
+
+ Keyed by the dictionary's own name, never by anything per-run. A dictionary outlives the
+ run that created it, and CREATE ... IF NOT EXISTS keys on that same name, so a per-run key
+ would leave the earlier definition pointing at an object no later run writes.
+ """
+ raise NotImplementedError()
+
+ def recreate(
+ self,
+ client: Client,
+ shards: int,
+ max_execution_time: int,
+ max_memory_usage: int,
+ query: str | None = None,
+ ) -> None:
+ """Replace the dictionary, so no definition an earlier run left behind can survive.
+
+ CREATE ... IF NOT EXISTS keeps the existing source, which is right where that source is the
+ replicated table and wrong where it is a staged object whose query can change between
+ deploys.
+ """
+ self.drop(client)
+ self.create(client, shards, max_execution_time, max_memory_usage, query)
+
def exists(self, client: Client) -> bool:
results = client.execute(
"SELECT count() FROM system.dictionaries WHERE database = %(database)s AND name = %(name)s",
@@ -292,7 +383,7 @@ class Dictionary(abc.ABC):
raise NotImplementedError()
-@dataclass
+@frozen
class PendingDeletesDictionary(Dictionary):
source: PendingDeletesTable
@@ -300,7 +391,21 @@ class PendingDeletesDictionary(Dictionary):
def query(self) -> str:
return f"SELECT team_id, deletion_type, key, created_at FROM {self.source.qualified_name}"
- def create(self, client: Client, shards: int, max_execution_time: int, max_memory_usage: int) -> None:
+ def staged(self) -> StagedDictionary:
+ return StagedDictionary(
+ key=f"{self.name}.parquet",
+ columns="team_id, deletion_type, key, created_at",
+ structure="team_id Int64, deletion_type UInt8, key String, created_at DateTime",
+ )
+
+ def create(
+ self,
+ client: Client,
+ shards: int,
+ max_execution_time: int,
+ max_memory_usage: int,
+ query: str | None = None,
+ ) -> None:
client.execute(
f"""
CREATE DICTIONARY IF NOT EXISTS {self.qualified_name} (
@@ -319,7 +424,7 @@ class PendingDeletesDictionary(Dictionary):
"database": settings.CLICKHOUSE_DATABASE,
"user": settings.CLICKHOUSE_USER,
"password": settings.CLICKHOUSE_PASSWORD,
- "query": self.query,
+ "query": query or self.query,
},
)
@@ -334,7 +439,7 @@ class PendingDeletesDictionary(Dictionary):
return checksum
-@dataclass
+@frozen
class AdhocEventDeletesDictionary(Dictionary):
source: AdhocEventDeletesTable
@@ -342,7 +447,21 @@ class AdhocEventDeletesDictionary(Dictionary):
def query(self) -> str:
return f"SELECT team_id, uuid, created_at FROM {self.source.qualified_name} WHERE (team_id, uuid) not in (SELECT team_id, uuid FROM {self.source.qualified_name} WHERE is_deleted = 1)"
- def create(self, client: Client, shards: int, max_execution_time: int, max_memory_usage: int) -> None:
+ def staged(self) -> StagedDictionary:
+ return StagedDictionary(
+ key=f"{self.name}.parquet",
+ columns="team_id, uuid, created_at",
+ structure="team_id Int64, uuid UUID, created_at DateTime64(6, 'UTC')",
+ )
+
+ def create(
+ self,
+ client: Client,
+ shards: int,
+ max_execution_time: int,
+ max_memory_usage: int,
+ query: str | None = None,
+ ) -> None:
client.execute(
f"""
CREATE DICTIONARY IF NOT EXISTS {self.qualified_name} (
@@ -360,7 +479,7 @@ class AdhocEventDeletesDictionary(Dictionary):
"database": settings.CLICKHOUSE_DATABASE,
"user": settings.CLICKHOUSE_USER,
"password": settings.CLICKHOUSE_PASSWORD,
- "query": self.query,
+ "query": query or self.query,
},
)
@@ -457,8 +576,68 @@ def load_pending_deletions(
return create_pending_deletions_table
+def _create_dictionary_everywhere(
+ context: dagster.OpExecutionContext,
+ cluster: ClickhouseCluster,
+ config: DeleteConfig,
+ dictionary: Dictionary,
+) -> None:
+ """Create ``dictionary`` on every cluster the delete mutations will run on.
+
+ The handle in hand reads its own replicated source table. A cluster that shares no Keeper with
+ it cannot see that table at all, so the rows are staged to S3 first and every host there loads
+ the object for itself.
+ """
+ create = partial(
+ dictionary.create,
+ shards=config.shards,
+ max_execution_time=config.max_execution_time,
+ max_memory_usage=config.max_memory_usage,
+ )
+ cluster.map_all_hosts(create).result()
+
+ siblings = [handle for handle in sweep_clusters(cluster) if handle is not cluster]
+ if not siblings:
+ return
+
+ staged = dictionary.staged()
+ cluster.any_host_by_role(partial(staged.export, source_query=dictionary.query), NodeRole.DATA).result()
+ recreate = partial(
+ dictionary.recreate,
+ shards=config.shards,
+ max_execution_time=config.max_execution_time,
+ max_memory_usage=config.max_memory_usage,
+ query=staged.query,
+ )
+ for sibling in siblings:
+ sibling.map_all_hosts(recreate).result()
+
+ context.log.info(
+ f"Staged {dictionary.name} to {staged.key} for {[sibling.data_cluster_name for sibling in siblings]}"
+ )
+
+
+def _load_and_verify_everywhere(cluster: ClickhouseCluster, dictionary: Dictionary) -> None:
+ """Load ``dictionary`` on every host of every cluster, and prove they all hold the same rows.
+
+ Comparing checksums across clusters is what catches a stale or missing staged object. Without
+ it the mutation there runs against an empty dictionary, deletes nothing, and reports success.
+ """
+ by_cluster: dict[str, set[int]] = {}
+ for handle in sweep_clusters(cluster):
+ results = handle.map_all_hosts(dictionary.load, concurrency=1).result()
+ by_cluster[handle.data_cluster_name] = set(results.values())
+
+ if len({checksum for checksums in by_cluster.values() for checksum in checksums}) != 1:
+ raise dagster.Failure(
+ description=f"{dictionary.name} does not hold the same rows on every host: "
+ + ", ".join(f"{name}={sorted(checksums)}" for name, checksums in by_cluster.items())
+ )
+
+
@dagster.op
def create_deletes_dict(
+ context: dagster.OpExecutionContext,
load_pending_deletions: PendingDeletesTable,
config: DeleteConfig,
cluster: dagster.ResourceParam[ClickhouseCluster],
@@ -475,14 +654,7 @@ def create_deletes_dict(
source=load_pending_deletions,
)
- cluster.map_all_hosts(
- partial(
- del_dict.create,
- shards=config.shards,
- max_execution_time=config.max_execution_time,
- max_memory_usage=config.max_memory_usage,
- )
- ).result()
+ _create_dictionary_everywhere(context, cluster, config, del_dict)
return del_dict
@@ -506,14 +678,7 @@ def create_adhoc_event_deletes_dict(
source=adhoc_event_deletions,
)
- cluster.map_all_hosts(
- partial(
- del_dict.create,
- shards=config.shards,
- max_execution_time=config.max_execution_time,
- max_memory_usage=config.max_memory_usage,
- )
- ).result()
+ _create_dictionary_everywhere(context, cluster, config, del_dict)
# The dictionary holds identical data on every host, so count the loaded ids on a single
# data node (verifying replica identity is the job of load_and_verify_adhoc_event_deletes_dictionary).
@@ -538,9 +703,8 @@ def load_and_verify_deletes_dictionary(
cluster: dagster.ResourceParam[ClickhouseCluster],
dictionary: PendingDeletesDictionary,
) -> PendingDeletesDictionary:
- """Load the dictionary data on all hosts in the cluster, and ensure all hosts have identical data."""
- checksums = cluster.map_all_hosts(dictionary.load, concurrency=1).result()
- assert len(set(checksums.values())) == 1
+ """Load the dictionary on every host of every cluster the mutations run on, and verify it."""
+ _load_and_verify_everywhere(cluster, dictionary)
return dictionary
@@ -549,9 +713,8 @@ def load_and_verify_adhoc_event_deletes_dictionary(
cluster: dagster.ResourceParam[ClickhouseCluster],
dictionary: AdhocEventDeletesDictionary,
) -> AdhocEventDeletesDictionary:
- """Load the dictionary data on all hosts in the cluster, and ensure all hosts have identical data."""
- checksums = cluster.map_all_hosts(dictionary.load, concurrency=1).result()
- assert len(set(checksums.values())) == 1
+ """Load the dictionary on every host of every cluster the mutations run on, and verify it."""
+ _load_and_verify_everywhere(cluster, dictionary)
return dictionary
@@ -561,8 +724,8 @@ def delete_events(
cluster: dagster.ResourceParam[ClickhouseCluster],
load_and_verify_deletes_dictionary: PendingDeletesDictionary,
load_and_verify_adhoc_event_deletes_dictionary: AdhocEventDeletesDictionary,
-) -> tuple[PendingDeletesDictionary, ShardMutations]:
- """Delete events from sharded_events table for pending deletions."""
+) -> tuple[PendingDeletesDictionary, ClusterShardMutations]:
+ """Delete events from every personal-data table, on whichever cluster stores each one."""
def count_pending_deletes(client: Client) -> int:
result = client.execute(
@@ -605,35 +768,44 @@ def delete_events(
# Every registered target must get this delete, or rows survive on the table that got skipped.
# The predicate below reads only team_id, person_id, timestamp and uuid, which every target
# declares, so it applies unchanged to all of them.
+ placements = resolve_placements(cluster)
delete_mutation_runners = [
- LightweightDeleteMutationRunner(
- table=table,
- predicate="""or(
+ (
+ placement,
+ LightweightDeleteMutationRunner(
+ table=placement.target.data_table,
+ predicate="""or(
(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))),
(dictHas(%(pending_deletes_dictionary)s, (team_id, %(team_deletion_type)s, team_id))),
(dictHas(%(adhoc_event_deletes_dictionary)s, (team_id, uuid)))
)
""",
- parameters={
- "pending_deletes_dictionary": load_and_verify_deletes_dictionary.qualified_name,
- "person_deletion_type": DeletionType.Person,
- "team_deletion_type": DeletionType.Team,
- "adhoc_event_deletes_dictionary": load_and_verify_adhoc_event_deletes_dictionary.qualified_name,
- },
+ parameters={
+ "pending_deletes_dictionary": load_and_verify_deletes_dictionary.qualified_name,
+ "person_deletion_type": DeletionType.Person,
+ "team_deletion_type": DeletionType.Team,
+ "adhoc_event_deletes_dictionary": load_and_verify_adhoc_event_deletes_dictionary.qualified_name,
+ },
+ ),
)
- for table in personal_data_tables(cluster)
+ for placement in placements
]
- shard_waiters: dict[int, list[MutationWaiter]] = {}
- for delete_mutation_runner in delete_mutation_runners:
- for host, mutation in cluster.map_one_host_per_shard(delete_mutation_runner).result().items():
+ waiters: dict[str, dict[int, list[MutationWaiter]]] = {}
+ for placement, delete_mutation_runner in delete_mutation_runners:
+ # 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():
if host.shard_num is not None:
- shard_waiters.setdefault(host.shard_num, []).append(mutation)
- shard_mutations: ShardMutations = {
- shard_num: MutationWaiters(waiters=waiters) for shard_num, waiters in shard_waiters.items()
+ by_shard = waiters.setdefault(placement.cluster.data_cluster_name, {})
+ by_shard.setdefault(host.shard_num, []).append(mutation)
+
+ cluster_mutations: ClusterShardMutations = {
+ name: {shard_num: MutationWaiters(waiters=shard_waiters) for shard_num, shard_waiters in by_shard.items()}
+ for name, by_shard in waiters.items()
}
- return (load_and_verify_deletes_dictionary, shard_mutations)
+ return (load_and_verify_deletes_dictionary, cluster_mutations)
def delete_team_data(
@@ -713,11 +885,13 @@ def delete_team_data_from(
def wait_for_delete_mutations_in_shards(
context: dagster.OpExecutionContext,
cluster: dagster.ResourceParam[ClickhouseCluster],
- delete_mutations: tuple[PendingDeletesDictionary, ShardMutations],
+ delete_mutations: tuple[PendingDeletesDictionary, ClusterShardMutations],
) -> PendingDeletesDictionary:
- pending_deletes_dict, shard_mutations = delete_mutations
+ pending_deletes_dict, cluster_mutations = delete_mutations
- cluster.map_all_hosts_in_shards({shard: mutation.wait for shard, mutation in shard_mutations.items()}).result()
+ for cluster_name, shard_mutations in cluster_mutations.items():
+ handle = cluster.sibling(cluster_name)
+ handle.map_all_hosts_in_shards({shard: mutation.wait for shard, mutation in shard_mutations.items()}).result()
return pending_deletes_dict
@@ -783,11 +957,13 @@ def cleanup_delete_assets(
dagster.get_dagster_logger().info("Skipping cleanup as cleanup is disabled")
return True
- # Must drop dict first
- cluster.map_all_hosts(resources.pending_deletions_dictionary.drop).result()
- cluster.map_all_hosts(resources.pending_deletions_dictionary.source.drop).result()
+ # Must drop dict first. Every cluster the mutations ran on carries a copy of each dictionary;
+ # only the job's own cluster carries the source table the staged object was exported from.
+ for handle in sweep_clusters(cluster):
+ handle.map_all_hosts(resources.pending_deletions_dictionary.drop).result()
+ handle.map_all_hosts(resources.adhoc_event_deletes_dictionary.drop).result()
- cluster.map_all_hosts(resources.adhoc_event_deletes_dictionary.drop).result()
+ cluster.map_all_hosts(resources.pending_deletions_dictionary.source.drop).result()
cluster.any_host_by_role(
resources.adhoc_event_deletes_dictionary.source.optimize, NodeRole.DATA, Workload.ONLINE
).result()
diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.py
index 898afb355489..c19f705af501 100644
--- a/posthog/dags/tests/test_deletes.py
+++ b/posthog/dags/tests/test_deletes.py
@@ -15,6 +15,7 @@ from posthog.dags.deletes import (
MonthlyCleanupConfig,
PendingDeletesDictionary,
PendingDeletesTable,
+ StagedDictionary,
cleanup_old_events_by_partition,
deletes_job,
find_partitions_to_cleanup,
@@ -675,3 +676,108 @@ def test_monthly_old_events_cleanup_job(cluster: ClickhouseCluster):
events_after = cluster.any_host(count_all_events).result()
assert events_after == len(recent_events)
+
+
+def _insert_pending_deletes(table: PendingDeletesTable, client: Client, count: int = 5, first_id: int = 0) -> None:
+ client.execute(
+ table.populate_query,
+ [
+ {
+ "id": i,
+ "deletion_type": int(DeletionType.Person),
+ "key": str(UUID(int=i)),
+ "group_type_index": None,
+ "created_at": datetime(2026, 8, 26, 10, 11, 12),
+ "delete_verified_at": None,
+ "created_by_id": None,
+ "team_id": 99999,
+ }
+ for i in range(first_id, first_id + count)
+ ],
+ )
+
+
+def test_a_staged_dictionary_holds_the_same_rows_as_the_source_table(cluster: ClickhouseCluster):
+ # A cluster with its own Keeper can never join the source table's replica set, so it loads the
+ # dictionary from a staged object instead, and the run is gated on both sides checksumming
+ # alike. That gate only means something if the staged copy round-trips every column exactly:
+ # a type Parquet does not preserve would make two correct clusters look like they disagree.
+ table = PendingDeletesTable(timestamp=datetime(2026, 8, 26, 10, 11, 12))
+ dictionary = PendingDeletesDictionary(source=table)
+ create = partial(dictionary.create, shards=1, max_execution_time=0, max_memory_usage=0)
+ recreate = partial(dictionary.recreate, shards=1, max_execution_time=0, max_memory_usage=0)
+
+ try:
+ cluster.any_host(table.create).result()
+ cluster.any_host(partial(_insert_pending_deletes, table)).result()
+
+ cluster.any_host(create).result()
+ from_source_table = cluster.any_host(dictionary.load).result()
+
+ staged = dictionary.staged()
+ cluster.any_host(partial(staged.export, source_query=dictionary.query)).result()
+ cluster.any_host(partial(recreate, query=staged.query)).result()
+ from_staged_object = cluster.any_host(dictionary.load).result()
+
+ assert from_staged_object == from_source_table
+ finally:
+ cluster.any_host(dictionary.drop).result()
+ cluster.any_host(table.drop).result()
+
+
+def test_staged_dictionary_escapes_quotes_inside_a_column_type() -> None:
+ # DateTime64(6, 'UTC') carries single quotes, and the structure is itself a quoted SQL literal,
+ # so an unescaped copy terminates the literal early and the s3() call fails to parse.
+ staged = StagedDictionary(
+ key="run/adhoc.parquet",
+ columns="team_id, uuid, created_at",
+ structure="team_id Int64, uuid UUID, created_at DateTime64(6, 'UTC')",
+ )
+ assert "DateTime64(6, \\'UTC\\')" in staged.query
+
+
+ "dictionary",
+ [
+ PendingDeletesDictionary(source=PendingDeletesTable(timestamp=datetime(2026, 8, 26, 10, 11, 12))),
+ AdhocEventDeletesDictionary(source=AdhocEventDeletesTable()),
+ ],
+ ids=["pending_deletes", "adhoc_event_deletes"],
+)
+def test_a_staged_dictionary_is_keyed_by_the_dictionary_name(dictionary) -> None:
+ # CREATE ... IF NOT EXISTS keys on the dictionary name, and a dictionary outlives the run that
+ # created it. Keying the object per run instead leaves that definition naming an object no
+ # later run writes, so a cluster loading from S3 serves the first run's rows for ever.
+ assert dictionary.staged().key == f"{dictionary.name}.parquet"
+
+
+def test_a_rerun_stages_over_the_previous_runs_object(cluster: ClickhouseCluster):
+ # Every run writes the same key, so the export has to replace the object rather than add to it.
+ # An append leaves both runs' rows behind, and the cluster loading from S3 then holds rows the
+ # cluster reading the source table does not.
+ table = PendingDeletesTable(timestamp=datetime(2026, 8, 26, 10, 11, 13))
+ dictionary = PendingDeletesDictionary(source=table)
+ recreate = partial(dictionary.recreate, shards=1, max_execution_time=0, max_memory_usage=0)
+ staged = dictionary.staged()
+
+ try:
+ cluster.any_host(table.create).result()
+ cluster.any_host(partial(_insert_pending_deletes, table, count=5)).result()
+ cluster.any_host(partial(staged.export, source_query=dictionary.query)).result()
+
+ cluster.any_host(table.truncate).result()
+ cluster.any_host(partial(_insert_pending_deletes, table, count=2, first_id=100)).result()
+ cluster.any_host(partial(staged.export, source_query=dictionary.query)).result()
+
+ cluster.any_host(partial(recreate, query=staged.query)).result()
+ from_staged_object = cluster.any_host(dictionary.load).result()
+
+ cluster.any_host(partial(recreate)).result()
+ from_source_table = cluster.any_host(dictionary.load).result()
+
+ assert from_staged_object == from_source_table
+ finally:
+ cluster.any_host(dictionary.drop).result()
+ cluster.any_host(table.drop).result()
diff --git a/posthog/models/deletion_targets.py b/posthog/models/deletion_targets.py
index 910ffdd6ca12..f2178718d52e 100644
--- a/posthog/models/deletion_targets.py
+++ b/posthog/models/deletion_targets.py
@@ -310,6 +310,22 @@ def resolve_placements(
return [placement for placement in placements if placement is not None]
+def sweep_clusters(
+ cluster: ClickhouseCluster, targets: Sequence[DeletionTarget] = PERSONAL_DATA_TARGETS
+) -> list[ClickhouseCluster]:
+ """Every distinct cluster a sweep over ``targets`` dispatches to, the handle in hand first.
+
+ A mutation predicate that joins a dictionary needs that dictionary present on every cluster the
+ mutation runs on, which is what this enumerates. The handle in hand is always included: sweeps
+ over the replicated, non-sharded tables run there whatever the targets resolve to.
+ """
+ clusters = [cluster]
+ for placement in resolve_placements(cluster, targets):
+ if not any(placement.cluster is known for known in clusters):
+ clusters.append(placement.cluster)
+ return clusters
+
+
def resolve_targets_here(
cluster: ClickhouseCluster, targets: Sequence[DeletionTarget] = PERSONAL_DATA_TARGETS
) -> list[DeletionTarget]:
diff --git a/posthog/models/test/test_deletion_targets.py b/posthog/models/test/test_deletion_targets.py
index 2919045ca0d2..0c277258526b 100644
--- a/posthog/models/test/test_deletion_targets.py
+++ b/posthog/models/test/test_deletion_targets.py
@@ -7,7 +7,13 @@ from unittest.mock import Mock, patch
from django.test import override_settings
from posthog.clickhouse.cluster import ClickhouseCluster, HostInfo
-from posthog.models.deletion_targets import DeletionTarget, UnreachableTargetError, dispatchable_here, placement_for
+from posthog.models.deletion_targets import (
+ DeletionTarget,
+ UnreachableTargetError,
+ dispatchable_here,
+ placement_for,
+ sweep_clusters,
+)
# One data node each, so a table present on one cluster and absent from the other is the only
# difference between them. That is the topology the placement resolution exists for and the one no
@@ -78,3 +84,22 @@ def test_dispatchable_here_refuses_a_target_another_cluster_carries() -> None:
with _cluster_with({"data1": set(), "events1": {"sharded_events_json"}}) as cluster:
with pytest.raises(UnreachableTargetError):
dispatchable_here(cluster, _OFF_CLUSTER_TARGET)
+
+
+@override_settings(CLICKHOUSE_EVENTS_CLUSTER="events")
+def test_sweep_clusters_lists_every_cluster_a_mutation_runs_on() -> None:
+ # The delete predicate joins a dictionary, so the dictionary has to exist on each cluster this
+ # returns. Missing one there means the mutation runs against nothing and reports success.
+ with _cluster_with({"data1": set(), "events1": {"sharded_events_json"}}) as cluster:
+ clusters = sweep_clusters(cluster, [_OFF_CLUSTER_TARGET])
+
+ assert [handle.data_cluster_name for handle in clusters] == ["posthog", "events"]
+ assert clusters[0] is cluster
+
+
+@override_settings(CLICKHOUSE_EVENTS_CLUSTER="events")
+def test_sweep_clusters_does_not_repeat_the_handle_in_hand() -> None:
+ # Building the dictionary twice on one cluster is wasted work, and every sweep keyed off this
+ # list would run its mutations twice.
+ with _cluster_with({"data1": {"sharded_events_json"}, "events1": {"sharded_events_json"}}) as cluster:
+ assert sweep_clusters(cluster, [_OFF_CLUSTER_TARGET]) == [cluster]
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.py
index 2cd73729dfc7..939d6aa7cbfa 100644
--- a/posthog/settings/object_storage.py
+++ b/posthog/settings/object_storage.py
@@ -134,3 +134,24 @@ if TEST or DEBUG:
)
else:
IDENTITY_MATCHING_S3_ENDPOINT = os.getenv("IDENTITY_MATCHING_S3_ENDPOINT", "") or None
+
+# Deletion dictionary staging (posthog/dags/deletes.py). The pending-deletion and queued-uuid
+# dictionaries reach every host of the main cluster because their source table is replicated, and
+# replication is exactly what stops at a cluster boundary: a cluster with its own Keeper can never
+# join that replica set. So when a deletion target's storage lives on another cluster, deletes_job
+# stages the dictionary rows here as Parquet and each host there loads the same object for itself.
+# Written and read by the ClickHouse cluster via `INSERT INTO FUNCTION s3(...)` / `s3(...)`, so
+# only the cluster needs bucket access; the Dagster process never touches boto3. Nothing deletes
+# these objects, so infra must expire the prefix through the bucket lifecycle policy. They hold
+# team ids and the person uuids already recorded on the Postgres AsyncDeletion rows.
+DELETES_DICTIONARY_S3_BUCKET = os.getenv("DELETES_DICTIONARY_S3_BUCKET") or OBJECT_STORAGE_BUCKET
+DELETES_DICTIONARY_S3_PREFIX = os.getenv("DELETES_DICTIONARY_S3_PREFIX", "deletes_dictionaries")
+DELETES_DICTIONARY_S3_REGION = os.getenv("DELETES_DICTIONARY_S3_REGION") or OBJECT_STORAGE_REGION
+# Must be an endpoint the ClickHouse cluster can reach, which is not always OBJECT_STORAGE_ENDPOINT;
+# see the IDENTITY_MATCHING_S3_ENDPOINT note above for why localhost breaks under TEST.
+if TEST or DEBUG:
+ DELETES_DICTIONARY_S3_ENDPOINT: Optional[str] = (
+ os.getenv("DELETES_DICTIONARY_S3_ENDPOINT", "http://objectstorage:19000") or None
+ )
+else:
+ DELETES_DICTIONARY_S3_ENDPOINT = os.getenv("DELETES_DICTIONARY_S3_ENDPOINT", "") or None