: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): squash person_id on flag_evaluations after a merge (#98802)
Phil Haack2f98c1a40967
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex b5b97b7bec73..72adef2f47e2 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -79,8 +79,9 @@ ClickHouse has no S3 dictionary source, but that source runs its query locally,- 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.+`squash_person_overrides` rewrites `person_id` on every table in `SQUASH_TARGETS` — `sharded_events`, `sharded_events_json` and `sharded_flag_evaluations` — through a mutation that joins a snapshot dictionary, then deletes the overrides it just applied.+Skipping one of those tables is worse than under-deleting: the overrides that record the correct `person_id` are gone in the next op, so the divergence is permanent.+`SQUASH_TARGETS` is deliberately its own list rather than `PERSONAL_DATA_TARGETS`, so registering a table for deletion does not silently enroll it in the squash as well.`posthog/dags/common/staged_dictionary.py` holds the piece both jobs share.## Covered tables@@ -171,10 +172,10 @@ The fix would belong to the producer, not the scanner.Keeping the fork downstream of person resolution is the contract, tracked on #81002.Write-time parity is not sufficient on its own, because a later merge moves the person the sweep looks for.-`squash_person_overrides` rewrites `person_id` on `EVENTS_TARGETS` only, so after person A merges into B the events rows carry B while the flag-evaluation rows still carry A.-A deletion of B is queued under B's uuid, so it misses those rows and they survive, with their event `properties` and their stale `person_id`, until the TTL drops the part.-The squash deletes the overrides right after applying them, so nothing can reconcile the divergence afterwards.-Extending the squash to `FLAG_EVALUATIONS` is the fix, and it belongs to `posthog/dags/person_overrides.py` rather than to this table. Tracked on #93035.+After person A merges into B, a deletion of B is queued under B's uuid, so any row still carrying A matches nothing and survives with its event `properties` and its stale `person_id` until the TTL drops the part.+`sharded_flag_evaluations` is a squash target as well as a deletion target for that reason: it is in `SQUASH_TARGETS` in `posthog/dags/person_overrides.py`, and `person_id` is not in its sort key, so it takes the same `ALTER UPDATE` the events tables take.+A table missing from `SQUASH_TARGETS` strands its rows permanently, because the squash deletes the overrides that recorded the mapping right after applying them.+Rows a merge stranded before `sharded_flag_evaluations` joined the list age out with their partition.## Related, and deliberately unchanged@@ -187,5 +188,8 @@ Extending the squash to `FLAG_EVALUATIONS` is the fix, and it belongs to `posthoRegister it in `PERSONAL_DATA_TARGETS`, with capability flags reflecting what its schema can actually take and what the sweep code actually implements: `accepts_property_rewrite` needs the rewrite machinery to reach the table, not just assignable columns; `stores_person_properties` needs the table's `person_properties` column to actually hold reachable data, not just exist in the schema; see `FLAG_EVALUATIONS` for a table where those diverged.If it is not going to be swept, add it to `TTL_ONLY_TABLES` with the window you are accepting.If its storage lives on a cluster other than the one the deletion jobs connect to, give it a `cluster_setting` naming that cluster and mark it `optional`; see "Reach" and "Dispatching" above for which sweeps then reach it and which refuse.+If a merge can move the `person_id` it stamps, add it to `SQUASH_TARGETS` in `posthog/dags/person_overrides.py` as well; registering it for deletion does not enroll it.+The squash applies an `ALTER UPDATE`, so the column has to sit outside the table's sort key; see the person_id parity section above.-`posthog/clickhouse/test/test_deletion_coverage.py` fails on any storage table that declares `person_properties` and appears in neither list, so the decision has to be made rather than skipped.+`posthog/clickhouse/test/test_deletion_coverage.py` fails on any storage table that declares `person_properties` and appears in neither deletion list, so that decision has to be made rather than skipped.+Nothing yet forces the `SQUASH_TARGETS` decision.diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.pyindex ab1a020b0942..4a640e37b7b2 100644--- a/posthog/clickhouse/cluster.py+++ b/posthog/clickhouse/cluster.py@@ -798,6 +798,16 @@ class MutationWaiters:waiter.wait(client)+def wait_for_mutations_on_shards(cluster: ClickhouseCluster, shard_mutations: Mapping[int, MutationWaiter]) -> None:+ """Block until every mutation in ``shard_mutations`` is complete on all hosts within its shard."""+ # during periods of elevated replication lag, it may take some time for mutations to become available on+ # the shards, so give them a little bit of breathing room with retries+ retry_policy = RetryPolicy(max_attempts=3, delay=10.0, exceptions=(MutationNotFound,))+ cluster.map_all_hosts_in_shards(+ {shard_num: retry_policy(waiter) for shard_num, waiter in shard_mutations.items()}+ ).result()++class MutationCapacityTimeout(Exception):"""Raised when another mutation held the table past a runner's ``capacity_timeout``."""@@ -1005,10 +1015,14 @@ class MutationRunner(abc.ABC):command: mutation_id for command, (mutation_id,) in zip(command_list, mutations) if mutation_id is not None}- def run_on_shards(self, cluster: ClickhouseCluster, shards: Iterable[int] | None = None) -> None:+ def enqueue_on_shards(+ self, cluster: ClickhouseCluster, shards: Iterable[int] | None = None+ ) -> dict[int, MutationWaiter]:"""- Enqueue (or find) this mutation on one host in each shard, and then block until the mutation is complete on all- hosts within the affected shards.+ Enqueue (or find) this mutation on one host in each shard, without waiting for it to complete.++ A caller running mutations on several tables enqueues all of them before waiting on any, so the total wait is+ the longest one rather than their sum. Pair with ``wait_for_mutations_on_shards``."""if shards is not None:shard_host_mutation_waiters = cluster.map_any_host_in_shards(dict.fromkeys(shards, self))@@ -1023,13 +1037,14 @@ class MutationRunner(abc.ABC):if host.shard_num is not None}assert len(shard_mutations) == len(shard_host_mutation_waiters)+ return shard_mutations- # during periods of elevated replication lag, it may take some time for mutations to become available on- # the shards, so give them a little bit of breathing room with retries- retry_policy = RetryPolicy(max_attempts=3, delay=10.0, exceptions=(MutationNotFound,))- cluster.map_all_hosts_in_shards(- {shard_num: retry_policy(waiter) for shard_num, waiter in shard_mutations.items()}- ).result()+ def run_on_shards(self, cluster: ClickhouseCluster, shards: Iterable[int] | None = None) -> None:+ """+ Enqueue (or find) this mutation on one host in each shard, and then block until the mutation is complete on all+ hosts within the affected shards.+ """+ wait_for_mutations_on_shards(cluster, self.enqueue_on_shards(cluster, shards))@dataclassdiff --git a/posthog/dags/common/overrides_manager.py b/posthog/dags/common/overrides_manager.pyindex f545d69c0eb1..c79ad73f987f 100644--- a/posthog/dags/common/overrides_manager.py+++ b/posthog/dags/common/overrides_manager.py@@ -151,20 +151,19 @@ class OverridesSnapshotDictionary(ABC, Generic[TOverridesSnapshotTable]):return self.get_checksum(client)- @property- @abstractmethod- def update_table(self):- raise NotImplementedError()-@property@abstractmethoddef update_commands(self):raise NotImplementedError()- @property- def update_mutation_runner(self) -> AlterTableMutationRunner:+ def update_mutation_runner_for(self, table: str) -> AlterTableMutationRunner:+ """The rewrite this snapshot applies, aimed at one target's storage table.++ A squash rewrites every table that stamps the overridden column, so the table is an+ argument rather than a property of the snapshot.+ """return AlterTableMutationRunner(- table=self.update_table,+ table=table,commands=self.update_commands,parameters={"name": self.qualified_name},)diff --git a/posthog/dags/person_overrides.py b/posthog/dags/person_overrides.pyindex 2c1a62b51004..e95713ac594f 100644--- a/posthog/dags/person_overrides.py+++ b/posthog/dags/person_overrides.py@@ -8,7 +8,7 @@ import pydanticfrom clickhouse_driver import Clientfrom posthog import settings-from posthog.clickhouse.cluster import AlterTableMutationRunner, ClickhouseCluster, MutationWaiter+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 (@@ -17,17 +17,25 @@ from posthog.dags.common.staged_dictionary import (load_and_verify_on_every_cluster,)from posthog.dataclasses import frozen-from posthog.models.deletion_targets import EVENTS_JSON, EVENTS_TARGETS, placement_for, sweep_clusters-from posthog.models.event.sql import EVENTS_DATA_TABLE, EVENTS_JSON_DATA_TABLE+from posthog.models.deletion_targets import EVENTS_TARGETS, FLAG_EVALUATIONS, resolve_placements, sweep_clustersfrom posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE+# Every table the squash rewrites person_id on. sharded_flag_evaluations is not an events table,+# but it stamps rows with the same person_id, and a person deletion matches the deleted person's+# uuid against that column. A row a merge left on the absorbed person therefore matches nothing and+# survives until its partition ages out, so the squash has to move it too.+#+# Deliberately not PERSONAL_DATA_TARGETS: registering a table for deletion should not silently make+# it a squash target as well.+SQUASH_TARGETS = (*EVENTS_TARGETS, FLAG_EVALUATIONS)+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)+ return sweep_clusters(cluster, SQUASH_TARGETS)@dataclass@@ -131,26 +139,12 @@ class PersonOverridesSnapshotDictionary(OverridesSnapshotDictionary):[[checksum]] = resultsreturn checksum- @property- def update_table(self):- return EVENTS_DATA_TABLE()-@propertydef update_commands(self):return {"UPDATE person_id = dictGet(%(name)s, 'person_id', (team_id, distinct_id)) WHERE dictHas(%(name)s, (team_id, distinct_id))"}- @property- def events_json_update_mutation_runner(self) -> AlterTableMutationRunner:- """The same person_id squash applied to the native-JSON events table — both tables must be- rewritten or person_id diverges between them while they coexist."""- return AlterTableMutationRunner(- table=EVENTS_JSON_DATA_TABLE,- commands=self.update_commands,- parameters={"name": self.qualified_name},- )-@propertydef overrides_table(self):return PERSON_DISTINCT_ID_OVERRIDES_TABLE@@ -289,14 +283,22 @@ def run_person_id_update_mutations(cluster: dagster.ResourceParam[ClickhouseCluster],dictionary: PersonOverridesSnapshotDictionary,) -> PersonOverridesSnapshotDictionary:- dictionary.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)+ """Rewrite person_id on every squash target, each on the cluster whose shards carry it.++ A target's storage table can sit on a cluster whose shards only its own handle enumerates, so+ the dispatch follows the resolved placement rather than the handle in hand. Skipping one would+ leave its rows on a person_id this run squashed away, and the overrides that record the correct+ one are deleted in the very next op.+ """+ enqueued: list[tuple[ClickhouseCluster, dict[int, MutationWaiter]]] = []+ for placement in resolve_placements(cluster, SQUASH_TARGETS):+ runner = dictionary.update_mutation_runner_for(placement.target.data_table)+ enqueued.append((placement.cluster, runner.enqueue_on_shards(placement.cluster)))++ # Every mutation is already in flight, so these waits overlap and cost the longest rather than+ # their sum. The capacity wait inside enqueue_on_shards is still per table and serial.+ for handle, shard_mutations in enqueued:+ wait_for_mutations_on_shards(handle, shard_mutations)return dictionarydiff --git a/posthog/dags/tests/test_person_overrides.py b/posthog/dags/tests/test_person_overrides.pyindex 0345b90cd57c..8ab83867b7fa 100644--- a/posthog/dags/tests/test_person_overrides.py+++ b/posthog/dags/tests/test_person_overrides.py@@ -4,14 +4,15 @@ from functools import partialfrom uuid import UUIDimport pytest-from unittest.mock import patch+from unittest.mock import Mock, call, patchfrom django.conf import settings as django_settingsimport dagsterfrom clickhouse_driver import Client-from posthog.clickhouse.cluster import ClickhouseCluster+from posthog.clickhouse.cluster import AlterTableMutationRunner, ClickhouseCluster+from posthog.dags.deletes import deletes_jobfrom posthog.dags.person_overrides import (GetExistingDictionaryConfig,PersonOverridesSnapshotDictionary,@@ -24,7 +25,11 @@ from posthog.dags.person_overrides import (squash_person_overrides,wait_for_overrides_delete_mutations,)-from posthog.models.deletion_targets import EVENTS_JSON, TargetPlacement+from posthog.dags.tests.conftest import insert_flag_evaluations+from posthog.models.async_deletion import AsyncDeletion, DeletionType+from posthog.models.deletion_targets import EVENTS, EVENTS_JSON, FLAG_EVALUATIONS, TargetPlacement+from posthog.models.event.sql import EVENTS_DATA_TABLE, EVENTS_JSON_DATA_TABLE+from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_DATA_TABLEdef test_full_job(cluster: ClickhouseCluster):@@ -123,6 +128,77 @@ def test_full_job(cluster: ClickhouseCluster):assert cluster.any_host(get_distinct_ids_with_overrides).result() == {"z"}+def test_a_person_deletion_after_a_merge_reaches_flag_evaluations(cluster: ClickhouseCluster):+ # A merge moves a distinct_id's rows onto the surviving person, and a deletion of that person+ # names only the surviving uuid. The squash is what makes the two agree, so a table it skips+ # keeps the absorbed uuid and the sweep never matches those rows, permanently, because the+ # override that recorded the mapping is deleted in the same squash run. This runs both dags+ # because the regression lives at the seam between them, which neither dag's own test covers.+ # nosemgrep: test-datetime-now-without-freeze (every timestamp here is an offset from this base, so no assertion reads a day bucket)+ timestamp = (datetime.now() + timedelta(days=31)).replace(microsecond=0)+ team_id = 4242+ absorbed_person, surviving_person = UUID(int=9001), UUID(int=9002)+ row_uuid = UUID(int=9003)++ cluster.any_host(+ partial(+ insert_flag_evaluations,+ [(team_id, "merged", absorbed_person, row_uuid, timestamp - timedelta(hours=2))],+ )+ ).result()++ def insert_override(client: Client) -> None:+ client.execute(+ "INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, _timestamp, version) VALUES",+ [(team_id, "merged", surviving_person, timestamp - timedelta(hours=1), 1)],+ )++ cluster.any_host(insert_override).result()++ def surviving_flag_evaluation_person_ids(client: Client) -> set[UUID]:+ # _row_exists = 1 drops rows a lightweight delete already hid; without it a swept row+ # still reads back until its part merges.+ rows = client.execute(+ "SELECT person_id FROM flag_evaluations WHERE uuid = %(uuid)s AND _row_exists = 1",+ {"uuid": row_uuid},+ )+ return {person_id for [person_id] in rows}++ squash_person_overrides.execute_in_process(+ run_config=dagster.RunConfig(+ {populate_snapshot_table.name: PopulateSnapshotTableConfig(timestamp=timestamp.isoformat())}+ ),+ resources={"cluster": cluster},+ )++ assert cluster.any_host(surviving_flag_evaluation_person_ids).result() == {surviving_person}++ deletion = AsyncDeletion.objects.create(+ team_id=team_id, deletion_type=DeletionType.Person, key=str(surviving_person)+ )+ deletion.created_at = timestamp+ deletion.save()++ # A person sweep only picks up requests made before the oldest surviving override, and the+ # squash consumed the only one this test wrote. An empty overrides table pins that watermark at+ # the epoch, so give the sweep an unrelated later override, which is what production always has.+ def insert_later_override(client: Client) -> None:+ client.execute(+ "INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, _timestamp, version) VALUES",+ [(team_id, "unrelated", UUID(int=9004), timestamp + timedelta(hours=1), 1)],+ )++ cluster.any_host(insert_later_override).result()++ deletes_job.execute_in_process(+ run_config={"ops": {"create_pending_deletions_table": {"config": {"team_id": team_id}}}},+ resources={"cluster": cluster},+ )++ assert cluster.any_host(surviving_flag_evaluation_person_ids).result() == set()++def test_cleanup_job(cluster: ClickhouseCluster) -> None:timestamp = datetime(2025, 1, 1)@@ -193,24 +269,59 @@ def test_a_staged_snapshot_dictionary_holds_the_same_rows_as_the_snapshot_table(@pytest.mark.django_db-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.+def test_run_person_id_update_mutations_rewrites_each_target_on_its_own_cluster(cluster: ClickhouseCluster):+ # sharded_events_json and sharded_flag_evaluations may each sit on a cluster whose shards only+ # its own handle enumerates. Running one of those rewrites over the job's handle would skip its+ # rows, and the overrides that record the correct person_id are deleted in the very next op, so+ # the divergence would be permanent. The assertion is keyed by table because a weaker one --+ # that some mutation reached the sibling -- still passes when a target is dropped entirely.dictionary = _create_snapshot_with(cluster, [(1, "a", UUID(int=7), 3)])sibling = cluster.sibling(django_settings.CLICKHOUSE_SINGLE_SHARD_CLUSTER)+ placements = [+ TargetPlacement(target=EVENTS, cluster=cluster),+ TargetPlacement(target=EVENTS_JSON, cluster=sibling),+ TargetPlacement(target=FLAG_EVALUATIONS, cluster=sibling),+ ]+ calls = Mock()+ enqueued = {+ EVENTS_DATA_TABLE(): {0: Mock()},+ EVENTS_JSON_DATA_TABLE: {0: Mock()},+ FLAG_EVALUATIONS_DATA_TABLE: {0: Mock()},+ }with (- patch(- "posthog.dags.person_overrides.placement_for",- return_value=TargetPlacement(target=EVENTS_JSON, cluster=sibling),- ),+ patch("posthog.dags.person_overrides.resolve_placements", return_value=placements) as resolve_placements,patch.object(- type(dictionary.events_json_update_mutation_runner), "run_on_shards", autospec=True- ) as run_on_shards,+ AlterTableMutationRunner,+ "enqueue_on_shards",+ autospec=True,+ side_effect=lambda runner, handle, shards=None: enqueued[runner.table],+ ) as enqueue_on_shards,+ patch("posthog.dags.person_overrides.wait_for_mutations_on_shards") as wait_for_mutations,):+ calls.attach_mock(enqueue_on_shards, "enqueue")+ calls.attach_mock(wait_for_mutations, "wait")run_person_id_update_mutations(cluster, dictionary)- dispatched = [call.args[1] for call in run_on_shards.call_args_list]- assert sibling in dispatched+ # This assertion names the targets literally instead of reusing SQUASH_TARGETS or EVENTS_TARGETS.+ # Either constant would still match after someone drops a target from its definition.+ resolve_placements.assert_called_once_with(cluster, (EVENTS, EVENTS_JSON, FLAG_EVALUATIONS))+ assert {enqueue.args[0].table: enqueue.args[1] for enqueue in enqueue_on_shards.call_args_list} == {+ EVENTS_DATA_TABLE(): cluster,+ EVENTS_JSON_DATA_TABLE: sibling,+ FLAG_EVALUATIONS_DATA_TABLE: sibling,+ }+ # Each wait has to receive the mutations its own enqueue returned. A wait handed an empty set+ # returns at once, and the next op deletes the overrides that record the mapping.+ wait_for_mutations.assert_has_calls(+ [+ call(cluster, enqueued[EVENTS_DATA_TABLE()]),+ call(sibling, enqueued[EVENTS_JSON_DATA_TABLE]),+ call(sibling, enqueued[FLAG_EVALUATIONS_DATA_TABLE]),+ ],+ any_order=True,+ )+ # Waiting on each mutation as it is enqueued would cost the sum of their completion times+ # rather than the longest, which is the whole reason the op enqueues in one pass.+ assert [name for name, *_ in calls.mock_calls] == ["enqueue"] * 3 + ["wait"] * 3cluster.any_host(dictionary.source.drop).result()