: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(deletions): let the squash rewrite person_id on another cluster (#89842)
Paweł Szczur029222570b9e
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex ccf08ebe997d..b382a4424f81 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -74,7 +74,12 @@ ClickHouse has no S3 dictionary source, but that source runs its query locally,- 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.+- Retention belongs to the bucket lifecycle policy, set through `DICTIONARY_STAGING_S3_*`. Nothing deletes the objects.++The same staging carries the person-overrides squash, which is not a deletion but has the identical problem.+`squash_person_overrides` rewrites `person_id` on `sharded_events` and `sharded_events_json` through a mutation that joins a snapshot dictionary, then deletes the overrides it just applied.+Skipping the second table there is worse than under-deleting: the overrides that record the correct `person_id` are gone in the next op, so the divergence is permanent.+`posthog/dags/common/staged_dictionary.py` holds the piece both jobs share.## Covered tablesdiff --git a/posthog/dags/common/overrides_manager.py b/posthog/dags/common/overrides_manager.pyindex e8286f174b4b..f545d69c0eb1 100644--- a/posthog/dags/common/overrides_manager.py+++ b/posthog/dags/common/overrides_manager.py@@ -8,6 +8,8 @@ from clickhouse_driver import Clientfrom posthog import settingsfrom posthog.clickhouse.cluster import AlterTableMutationRunner, LightweightDeleteMutationRunner+from posthog.dags.common.staged_dictionary import StagedDictionary+from posthog.dataclasses import frozenif TYPE_CHECKING:pass@@ -60,7 +62,7 @@ class OverridesSnapshotTable(ABC):TOverridesSnapshotTable = TypeVar("TOverridesSnapshotTable", bound=OverridesSnapshotTable)-@dataclass+@frozenclass OverridesSnapshotDictionary(ABC, Generic[TOverridesSnapshotTable]):source: TOverridesSnapshotTable@@ -73,9 +75,38 @@ class OverridesSnapshotDictionary(ABC, Generic[TOverridesSnapshotTable]):return f"{settings.CLICKHOUSE_DATABASE}.{self.name}"@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, for a host that cannot see the snapshot table."""+ raise NotImplementedError()++ @abstractmethod+ def staged(self) -> StagedDictionary:+ """Where this dictionary's rows go so another cluster can load them.++ Keyed by the dictionary's own name, never by anything per-run, because CREATE ... IF NOT+ EXISTS keys on that same name and a dictionary outlives the run that created it.+ """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."""+ 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",diff --git a/posthog/dags/common/staged_dictionary.py b/posthog/dags/common/staged_dictionary.pynew file mode 100644index 000000000000..d1e8270aea04--- /dev/null+++ b/posthog/dags/common/staged_dictionary.py@@ -0,0 +1,161 @@+"""Staging a ClickHouse dictionary's rows through S3, for a cluster that cannot see its source.++A dictionary's source table reaches every host of one cluster because it is replicated, and+replication is exactly what a cluster boundary stops: a cluster with its own Keeper can never join+that replica set. Any mutation whose predicate joins a dictionary therefore cannot run on such a+cluster until the dictionary is there too.++ClickHouse has no S3 dictionary source, but ``SOURCE(CLICKHOUSE(...))`` runs its query on the local+host and that query can read anything the server can. So the rows go to one Parquet object and every+host on the other cluster loads it for itself, which also means both sides load identical bytes and+comparing their checksums means something.+"""++from collections.abc import Sequence+from functools import partial+from typing import Protocol++from django.conf import settings++import dagster+from clickhouse_driver import Client++from posthog.clickhouse.client.connection import NodeRole+from posthog.clickhouse.cluster import ClickhouseCluster+from posthog.dataclasses import frozen+++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.DICTIONARY_STAGING_S3_PREFIX}/{key}"+ endpoint = settings.DICTIONARY_STAGING_S3_ENDPOINT+ if endpoint:+ url = f"{endpoint}/{settings.DICTIONARY_STAGING_S3_BUCKET}/{path}"+ creds = f"'{settings.OBJECT_STORAGE_ACCESS_KEY_ID}', '{settings.OBJECT_STORAGE_SECRET_ACCESS_KEY}', "+ else:+ bucket = settings.DICTIONARY_STAGING_S3_BUCKET+ url = f"https://{bucket}.s3.{settings.DICTIONARY_STAGING_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}'"+++@frozen+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")+++class StageableDictionary(Protocol):+ """The part of a dictionary that staging needs, shared by the two dictionary hierarchies."""++ @property+ def name(self) -> str: ...++ @property+ def query(self) -> str: ...++ def staged(self) -> StagedDictionary: ...++ def create(+ self, client: Client, shards: int, max_execution_time: int, max_memory_usage: int, query: str | None = None+ ) -> None: ...++ def recreate(+ self, client: Client, shards: int, max_execution_time: int, max_memory_usage: int, query: str | None = None+ ) -> None: ...++ def load(self, client: Client): ...+++def create_on_every_cluster(+ context: dagster.OpExecutionContext,+ clusters: Sequence[ClickhouseCluster],+ dictionary: StageableDictionary,+ *,+ shards: int,+ max_execution_time: int,+ max_memory_usage: int,+) -> None:+ """Create ``dictionary`` on every cluster a mutation joining it will run on.++ ``clusters`` leads with the handle that can see the source table; the rest read a staged object,+ because they share no Keeper with it and so never receive the replicated table.+ """+ first, *rest = clusters+ first.map_all_hosts(+ partial(+ dictionary.create,+ shards=shards,+ max_execution_time=max_execution_time,+ max_memory_usage=max_memory_usage,+ )+ ).result()+ if not rest:+ return++ staged = dictionary.staged()+ first.any_host_by_role(partial(staged.export, source_query=dictionary.query), NodeRole.DATA).result()+ for cluster in rest:+ cluster.map_all_hosts(+ partial(+ dictionary.recreate,+ shards=shards,+ max_execution_time=max_execution_time,+ max_memory_usage=max_memory_usage,+ query=staged.query,+ )+ ).result()++ context.log.info(f"Staged {dictionary.name} to {staged.key} for {[c.data_cluster_name for c in rest]}")+++def load_and_verify_on_every_cluster(clusters: Sequence[ClickhouseCluster], dictionary: StageableDictionary) -> None:+ """Load ``dictionary`` everywhere, and prove every host holds the same rows.++ Comparing checksums across clusters is what catches a stale or missing staged object. Without it+ the mutation there joins an empty dictionary, changes nothing, and reports success.++ Loading is serialized per cluster because it can consume a lot of CPU and memory, and running it+ on every host at once raises load across the whole cluster rather than spreading it.+ """+ by_cluster: dict[str, set[int]] = {}+ for cluster in clusters:+ results = cluster.map_all_hosts(dictionary.load, concurrency=1).result()+ by_cluster[cluster.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())+ )diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.pyindex f6c752e3b175..bc04f3233e8d 100644--- a/posthog/dags/deletes.py+++ b/posthog/dags/deletes.py@@ -3,7 +3,6 @@ import timeimport uuidfrom dataclasses import dataclassfrom datetime import datetime-from functools import partialfrom django.conf import settingsfrom django.db.models import Q@@ -26,6 +25,11 @@ from posthog.clickhouse.cluster import ()from posthog.clickhouse.plugin_log_entries import PLUGIN_LOG_ENTRIES_TABLEfrom posthog.dags.common import JobOwners+from posthog.dags.common.staged_dictionary import (+ StagedDictionary,+ create_on_every_cluster,+ load_and_verify_on_every_cluster,+)from posthog.dags.person_overrides import squash_person_overridesfrom posthog.dataclasses import frozenfrom posthog.models.async_deletion import AsyncDeletion, DeletionType@@ -231,57 +235,6 @@ class AdhocEventDeletesTable(Table):client.execute(f"OPTIMIZE TABLE {self.qualified_name} FINAL")-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")--@frozenclass Dictionary(abc.ABC):source: Table@@ -576,65 +529,6 @@ 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.opdef create_deletes_dict(context: dagster.OpExecutionContext,@@ -654,7 +548,14 @@ def create_deletes_dict(source=load_pending_deletions,)- _create_dictionary_everywhere(context, cluster, config, del_dict)+ create_on_every_cluster(+ context,+ sweep_clusters(cluster),+ del_dict,+ shards=config.shards,+ max_execution_time=config.max_execution_time,+ max_memory_usage=config.max_memory_usage,+ )return del_dict@@ -678,7 +579,14 @@ def create_adhoc_event_deletes_dict(source=adhoc_event_deletions,)- _create_dictionary_everywhere(context, cluster, config, del_dict)+ create_on_every_cluster(+ context,+ sweep_clusters(cluster),+ del_dict,+ shards=config.shards,+ max_execution_time=config.max_execution_time,+ max_memory_usage=config.max_memory_usage,+ )# 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).@@ -704,7 +612,7 @@ def load_and_verify_deletes_dictionary(dictionary: PendingDeletesDictionary,) -> PendingDeletesDictionary:"""Load the dictionary on every host of every cluster the mutations run on, and verify it."""- _load_and_verify_everywhere(cluster, dictionary)+ load_and_verify_on_every_cluster(sweep_clusters(cluster), dictionary)return dictionary@@ -714,7 +622,7 @@ def load_and_verify_adhoc_event_deletes_dictionary(dictionary: AdhocEventDeletesDictionary,) -> AdhocEventDeletesDictionary:"""Load the dictionary on every host of every cluster the mutations run on, and verify it."""- _load_and_verify_everywhere(cluster, dictionary)+ load_and_verify_on_every_cluster(sweep_clusters(cluster), dictionary)return dictionarydiff --git a/posthog/dags/person_overrides.py b/posthog/dags/person_overrides.pyindex cc5a76347658..2c1a62b51004 100644--- a/posthog/dags/person_overrides.py+++ b/posthog/dags/person_overrides.py@@ -11,11 +11,25 @@ from posthog import settingsfrom posthog.clickhouse.cluster import AlterTableMutationRunner, ClickhouseCluster, MutationWaiterfrom posthog.dags.common import JobOwnersfrom posthog.dags.common.overrides_manager import OverridesSnapshotDictionary, OverridesSnapshotTable-from posthog.models.event.deletion import cluster_has_events_json_table+from posthog.dags.common.staged_dictionary import (+ StagedDictionary,+ create_on_every_cluster,+ load_and_verify_on_every_cluster,+)+from posthog.dataclasses import frozen+from posthog.models.deletion_targets import EVENTS_JSON, EVENTS_TARGETS, placement_for, sweep_clustersfrom posthog.models.event.sql import EVENTS_DATA_TABLE, EVENTS_JSON_DATA_TABLEfrom posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE+def _squash_clusters(cluster: ClickhouseCluster) -> list[ClickhouseCluster]:+ """Every cluster the person_id rewrite dispatches to, the handle in hand first.++ The rewrite joins the snapshot dictionary, so the dictionary has to exist on each of them.+ """+ return sweep_clusters(cluster, EVENTS_TARGETS)++@dataclassclass PersonOverridesSnapshotTable(OverridesSnapshotTable):id: uuid.UUID@@ -58,11 +72,32 @@ class PersonOverridesSnapshotTable(OverridesSnapshotTable):)-@dataclass+@frozenclass PersonOverridesSnapshotDictionary(OverridesSnapshotDictionary):source: PersonOverridesSnapshotTable- 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, distinct_id, person_id, version",+ structure="team_id Int64, distinct_id String, person_id UUID, version Int64",+ )++ @property+ def query(self) -> str:+ return f"SELECT team_id, distinct_id, person_id, version FROM {self.source.qualified_name}"++ def create(+ self,+ client: Client,+ shards: int,+ max_execution_time: int,+ max_memory_usage: int,+ query: str | None = None,+ ) -> None:+ # A host that cannot see the snapshot table reads the staged object instead, which is a+ # query rather than a table name.+ source = "QUERY %(query)s" if query else "TABLE %(table)s"client.execute(f"""CREATE DICTIONARY IF NOT EXISTS {self.qualified_name} (@@ -72,7 +107,7 @@ class PersonOverridesSnapshotDictionary(OverridesSnapshotDictionary):version Int64)PRIMARY KEY team_id, distinct_id- SOURCE(CLICKHOUSE(DB %(database)s TABLE %(table)s USER %(user)s PASSWORD %(password)s))+ SOURCE(CLICKHOUSE(DB %(database)s {source} USER %(user)s PASSWORD %(password)s))LAYOUT(COMPLEX_KEY_HASHED(SHARDS {shards}))LIFETIME(0)SETTINGS(max_execution_time={max_execution_time}, max_memory_usage={max_memory_usage})@@ -80,6 +115,7 @@ class PersonOverridesSnapshotDictionary(OverridesSnapshotDictionary):{"database": settings.CLICKHOUSE_DATABASE,"table": self.source.name,+ "query": query,"user": settings.CLICKHOUSE_USER,"password": settings.CLICKHOUSE_PASSWORD,},@@ -200,20 +236,21 @@ class SnapshotDictionaryConfig(dagster.Config):@dagster.opdef create_snapshot_dictionary(+ context: dagster.OpExecutionContext,cluster: dagster.ResourceParam[ClickhouseCluster],config: SnapshotDictionaryConfig,table: PersonOverridesSnapshotTable,) -> PersonOverridesSnapshotDictionary:- """Create the snapshot dictionary (from the snapshot table data) on all hosts in the cluster."""- dictionary = PersonOverridesSnapshotDictionary(table)- cluster.map_all_hosts(- partial(- dictionary.create,- shards=config.shards,- max_execution_time=config.max_execution_time,- max_memory_usage=config.max_memory_usage,- )- ).result()+ """Create the snapshot dictionary on every cluster the person_id rewrite will run on."""+ dictionary = PersonOverridesSnapshotDictionary(source=table)+ create_on_every_cluster(+ context,+ _squash_clusters(cluster),+ dictionary,+ shards=config.shards,+ max_execution_time=config.max_execution_time,+ max_memory_usage=config.max_memory_usage,+ )return dictionary@@ -231,7 +268,7 @@ def get_existing_dictionary_for_run_id(This does not create the dictionary or ensure that it or any of its dependencies exist."""table = PersonOverridesSnapshotTable(uuid.UUID(config.id))- return PersonOverridesSnapshotDictionary(table)+ return PersonOverridesSnapshotDictionary(source=table)@dagster.op@@ -239,12 +276,8 @@ def load_and_verify_snapshot_dictionary(cluster: dagster.ResourceParam[ClickhouseCluster],dictionary: PersonOverridesSnapshotDictionary,) -> PersonOverridesSnapshotDictionary:- """Load the dictionary data on all hosts in the cluster, and ensure all hosts have identical data."""- # Loading and verifying the dictionary can consume a lot of CPU and memory, so we limit the amount of parallel- # queries to avoid substantial load increases on all hosts in the cluster at the same time, and instead try to- # spread the load out more evenly and gracefully.- 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 it will be joined on, and verify it."""+ load_and_verify_on_every_cluster(_squash_clusters(cluster), dictionary)return dictionary@@ -257,8 +290,13 @@ def run_person_id_update_mutations(dictionary: PersonOverridesSnapshotDictionary,) -> PersonOverridesSnapshotDictionary:dictionary.update_mutation_runner.run_on_shards(cluster)- if cluster_has_events_json_table(cluster):- dictionary.events_json_update_mutation_runner.run_on_shards(cluster)++ # sharded_events_json may be stored on another cluster, whose shards only its own handle+ # enumerates. Skipping it would leave those rows on a person_id this run just squashed away,+ # and the overrides that record the correct one are deleted immediately after.+ placement = placement_for(cluster, EVENTS_JSON)+ if placement is not None:+ dictionary.events_json_update_mutation_runner.run_on_shards(placement.cluster)return dictionary@@ -291,8 +329,9 @@ def drop_snapshot_dictionary(cluster: dagster.ResourceParam[ClickhouseCluster],dictionary: PersonOverridesSnapshotDictionary,) -> PersonOverridesSnapshotTable:- """Drop the snapshot dictionary on all hosts."""- cluster.map_all_hosts(dictionary.drop).result()+ """Drop the snapshot dictionary on all hosts of every cluster it was created on."""+ for handle in _squash_clusters(cluster):+ handle.map_all_hosts(dictionary.drop).result()return dictionary.sourcediff --git a/posthog/dags/tests/test_person_overrides.py b/posthog/dags/tests/test_person_overrides.pyindex e41287b4e62d..0345b90cd57c 100644--- a/posthog/dags/tests/test_person_overrides.py+++ b/posthog/dags/tests/test_person_overrides.py@@ -1,6 +1,13 @@+import uuid as uuid_modulefrom datetime import datetime, timedelta+from functools import partialfrom uuid import UUID+import pytest+from unittest.mock import patch++from django.conf import settings as django_settings+import dagsterfrom clickhouse_driver import Client@@ -13,9 +20,11 @@ from posthog.dags.person_overrides import (cleanup_orphaned_person_overrides_snapshot,get_existing_dictionary_for_run_id,populate_snapshot_table,+ run_person_id_update_mutations,squash_person_overrides,wait_for_overrides_delete_mutations,)+from posthog.models.deletion_targets import EVENTS_JSON, TargetPlacementdef test_full_job(cluster: ClickhouseCluster):@@ -83,7 +92,7 @@ def test_full_job(cluster: ClickhouseCluster):# ensure we cleaned up after ourselvestable = PersonOverridesSnapshotTable(UUID(limited_run_result.dagster_run.run_id))- dictionary = PersonOverridesSnapshotDictionary(table)+ dictionary = PersonOverridesSnapshotDictionary(source=table)assert not any(cluster.map_all_hosts(table.exists).result().values())assert not any(cluster.map_all_hosts(dictionary.exists).result().values())@@ -101,7 +110,7 @@ def test_full_job(cluster: ClickhouseCluster):# ensure we cleaned up after ourselves againtable = PersonOverridesSnapshotTable(UUID(full_run_result.dagster_run.run_id))- dictionary = PersonOverridesSnapshotDictionary(table)+ dictionary = PersonOverridesSnapshotDictionary(source=table)assert not any(cluster.map_all_hosts(table.exists).result().values())assert not any(cluster.map_all_hosts(dictionary.exists).result().values())@@ -127,7 +136,7 @@ def test_cleanup_job(cluster: ClickhouseCluster) -> None:# ensure we left some resources dangling around due to the op selectiontable = PersonOverridesSnapshotTable(UUID(partial_squash_run_result.dagster_run.run_id))- dictionary = PersonOverridesSnapshotDictionary(table)+ dictionary = PersonOverridesSnapshotDictionary(source=table)assert all(cluster.map_all_hosts(table.exists).result().values())assert all(cluster.map_all_hosts(dictionary.exists).result().values())@@ -145,3 +154,63 @@ def test_cleanup_job(cluster: ClickhouseCluster) -> None:# cleanup should have removed any dangling resources from the partial jobassert not any(cluster.map_all_hosts(table.exists).result().values())assert not any(cluster.map_all_hosts(dictionary.exists).result().values())+++def _create_snapshot_with(cluster: ClickhouseCluster, rows: list[tuple]) -> PersonOverridesSnapshotDictionary:+ table = PersonOverridesSnapshotTable(id=uuid_module.uuid4())+ cluster.any_host(table.create).result()++ def insert(client: Client) -> None:+ client.execute(f"INSERT INTO {table.qualified_name} (team_id, distinct_id, person_id, version) VALUES", rows)++ cluster.any_host(insert).result()+ return PersonOverridesSnapshotDictionary(source=table)+++def test_a_staged_snapshot_dictionary_holds_the_same_rows_as_the_snapshot_table(cluster: ClickhouseCluster):+ # A cluster that shares no Keeper with the job's own never receives the replicated snapshot+ # table, so it builds the dictionary from a staged object. The squash is gated on both sides+ # checksumming alike, which only means something if every column round-trips exactly. This one+ # carries a UUID and a String key, neither of which the deletes dictionaries exercise.+ dictionary = _create_snapshot_with(cluster, [(1, "a", UUID(int=7), 3), (2, "b", UUID(int=8), 4)])+ 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(create).result()+ from_snapshot_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_snapshot_table+ finally:+ cluster.any_host(dictionary.drop).result()+ cluster.any_host(dictionary.source.drop).result()+++def test_run_person_id_update_mutations_rewrites_events_json_on_its_own_cluster(cluster: ClickhouseCluster):+ # sharded_events_json may sit on a cluster whose shards only its own handle enumerates. Running+ # its rewrite over the job's handle would skip those rows, and the overrides that record the+ # correct person_id are deleted in the very next op, so the divergence would be permanent.+ dictionary = _create_snapshot_with(cluster, [(1, "a", UUID(int=7), 3)])+ sibling = cluster.sibling(django_settings.CLICKHOUSE_SINGLE_SHARD_CLUSTER)++ with (+ patch(+ "posthog.dags.person_overrides.placement_for",+ return_value=TargetPlacement(target=EVENTS_JSON, cluster=sibling),+ ),+ patch.object(+ type(dictionary.events_json_update_mutation_runner), "run_on_shards", autospec=True+ ) as run_on_shards,+ ):+ run_person_id_update_mutations(cluster, dictionary)++ dispatched = [call.args[1] for call in run_on_shards.call_args_list]+ assert sibling in dispatched+ cluster.any_host(dictionary.source.drop).result()diff --git a/posthog/dags/tests/test_staged_dictionary.py b/posthog/dags/tests/test_staged_dictionary.pynew file mode 100644index 000000000000..0fc44258b86b--- /dev/null+++ b/posthog/dags/tests/test_staged_dictionary.py@@ -0,0 +1,77 @@+from typing import Any, cast++import pytest++import dagster+from parameterized import parameterized++from posthog.clickhouse.cluster import ClickhouseCluster+from posthog.dags.common.staged_dictionary import (+ StageableDictionary,+ StagedDictionary,+ load_and_verify_on_every_cluster,+)+++class _Checksums:+ def __init__(self, by_host: dict[str, int]) -> None:+ self._by_host = by_host++ def result(self) -> dict[str, int]:+ return self._by_host+++class _StubCluster:+ """Enough of a handle for the verification gate: a name, and a checksum per host."""++ def __init__(self, name: str, checksums: dict[str, int]) -> None:+ self.data_cluster_name = name+ self._checksums = checksums++ def map_all_hosts(self, fn: Any, concurrency: int | None = None) -> _Checksums:+ return _Checksums(self._checksums)+++class _StubDictionary:+ name = "snapshot_dictionary"+ query = "SELECT 1"++ def staged(self) -> StagedDictionary:+ raise NotImplementedError++ def load(self, client: Any) -> int:+ raise NotImplementedError+++def _verify(clusters: list[_StubCluster]) -> None:+ load_and_verify_on_every_cluster(+ cast(list[ClickhouseCluster], clusters), cast(StageableDictionary, _StubDictionary())+ )+++class TestLoadAndVerifyOnEveryCluster:+ @parameterized.expand(+ [+ ("one cluster disagrees with the other", {"a": 1}, {"b": 2}),+ ("two hosts of one cluster disagree", {"a": 1, "b": 2}, {"c": 1}),+ ]+ )+ def test_it_fails_when_the_rows_are_not_identical_everywhere(+ self, _name: str, first: dict[str, int], second: dict[str, int]+ ) -> None:+ # This gate is the only thing standing between a stale staged object and a mutation that+ # joins an empty dictionary, changes nothing, and reports success.+ with pytest.raises(dagster.Failure, match="does not hold the same rows"):+ _verify([_StubCluster("posthog", first), _StubCluster("events", second)])++ def test_it_passes_when_every_host_agrees(self) -> None:+ _verify([_StubCluster("posthog", {"a": 7, "b": 7}), _StubCluster("events", {"c": 7})])++ def test_it_names_both_clusters_when_they_disagree(self) -> None:+ # The message is the only clue to which side went stale, so a run that fails here is+ # actionable rather than a bare assertion.+ with pytest.raises(dagster.Failure) as failure:+ _verify([_StubCluster("posthog", {"a": 1}), _StubCluster("events", {"b": 2})])++ assert "posthog=[1]" in str(failure.value.description)+ assert "events=[2]" in str(failure.value.description)diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 939d6aa7cbfa..2279f2f078ce 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -135,23 +135,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+# Dictionary staging (posthog/dags/common/staged_dictionary.py), used by deletes_job and by the+# person-overrides squash. A dictionary reaches every host of the main cluster because its+# 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.+# join that replica set. So when a target's storage lives on another cluster, the 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+DICTIONARY_STAGING_S3_BUCKET = os.getenv("DICTIONARY_STAGING_S3_BUCKET") or OBJECT_STORAGE_BUCKET+DICTIONARY_STAGING_S3_PREFIX = os.getenv("DICTIONARY_STAGING_S3_PREFIX", "deletes_dictionaries")+DICTIONARY_STAGING_S3_REGION = os.getenv("DICTIONARY_STAGING_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+ DICTIONARY_STAGING_S3_ENDPOINT: Optional[str] = (+ os.getenv("DICTIONARY_STAGING_S3_ENDPOINT", "http://objectstorage:19000") or None)else:- DELETES_DICTIONARY_S3_ENDPOINT = os.getenv("DELETES_DICTIONARY_S3_ENDPOINT", "") or None+ DICTIONARY_STAGING_S3_ENDPOINT = os.getenv("DICTIONARY_STAGING_S3_ENDPOINT", "") or None