: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
chore(clickhouse): make squash coverage a checked invariant (#98865)
Phil Haackdefc6e2f5133
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex 2b9da8aa84f2..093d4e785af4 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -87,7 +87,8 @@ The same staging carries the person-overrides squash, which is not a deletion buSkipping 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.`sharded_events_json` is deliberately not in the list, so the squash never dispatches to the events cluster.A row a merge stranded there keeps the absorbed `person_id` until its partition ages out, and nothing later can recover the mapping.-`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.+`SQUASH_TARGETS` is derived from the `accepts_person_id_rewrite` capability rather than kept as a second hand-written list, so a target registered for deletion and then forgotten by the squash is not expressible.+Leaving one out stays possible, and `PERSON_ID_REWRITE_EXEMPT` is where that decision gets written down.`posthog/dags/common/staged_dictionary.py` holds the piece both jobs share.## Covered tables@@ -239,10 +240,10 @@ Keeping the fork downstream of person resolution is the contract, tracked on #81Write-time parity is not sufficient on its own, because a later merge moves the person the sweep looks for.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` `sharded_events` takes.-A table missing from `SQUASH_TARGETS` strands its rows permanently, because the squash deletes the overrides that recorded the mapping right after applying them.-That is the accepted cost for `sharded_events_json`, which is excluded on purpose.-Rows a merge stranded before `sharded_flag_evaluations` joined the list age out with their partition.+`sharded_flag_evaluations` is a squash target as well as a deletion target for that reason: it sets `accepts_person_id_rewrite`, and `person_id` is not in its sort key, so it takes the same `ALTER UPDATE` `sharded_events` takes.+A target that leaves the capability unset strands its rows permanently, because the squash deletes the overrides that recorded the mapping right after applying them.+That is the accepted cost for `sharded_events_json`, which is exempt on purpose.+Rows a merge stranded before `sharded_flag_evaluations` joined the squash age out with their partition.## Related, and deliberately unchanged@@ -253,10 +254,11 @@ Rows a merge stranded before `sharded_flag_evaluations` joined the list age out## Adding a tableRegister 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.+Set `accepts_person_id_rewrite` unless you mean to leave the table out of the squash, which needs `person_id` outside the table's sorting and partition keys; skipping it is what stranded `flag_evaluations` rows on a merged-away person (#93035).+A table you do leave out goes in `PERSON_ID_REWRITE_EXEMPT` with the reason, the way `sharded_events_json` does.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 deletion list, so that decision has to be made rather than skipped.-Nothing yet forces the `SQUASH_TARGETS` decision.+It fails the same way on a registered target that neither sets `accepts_person_id_rewrite` nor appears in `PERSON_ID_REWRITE_EXEMPT`, and on a squash target carrying `person_id` in its sorting or partition key.+It also fails on a `PERSON_ID_REWRITE_EXEMPT` entry that names a squash target or a table no target registers, so the list holds only exemptions that are still in force.diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.pyindex 3145cde07cb9..b2cd26ebf2a3 100644--- a/posthog/clickhouse/cluster.py+++ b/posthog/clickhouse/cluster.py@@ -807,8 +807,13 @@ 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."""+def wait_for_mutations_on_shards(+ cluster: ClickhouseCluster, shard_mutations: Mapping[int, MutationWaiter | MutationWaiters]+) -> None:+ """Block until every mutation in ``shard_mutations`` is complete on all hosts within its shard.++ A shard's value can bundle several mutations, which is how a sweep spanning tables waits on one.+ """# 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 retriesretry_policy = RetryPolicy(max_attempts=3, delay=10.0, exceptions=(MutationNotFound,))diff --git a/posthog/clickhouse/test/test_deletion_coverage.py b/posthog/clickhouse/test/test_deletion_coverage.pyindex 93a663cab711..aa8491ceb3f7 100644--- a/posthog/clickhouse/test/test_deletion_coverage.py+++ b/posthog/clickhouse/test/test_deletion_coverage.py@@ -3,7 +3,12 @@ from posthog.test.base import BaseTest, ClickhouseTestMixinfrom django.conf import settingsfrom posthog.clickhouse.client import sync_execute-from posthog.models.deletion_targets import PERSONAL_DATA_TARGETS, TTL_ONLY_TABLES+from posthog.models.deletion_targets import (+ PERSON_ID_REWRITE_EXEMPT,+ PERSONAL_DATA_TARGETS,+ SQUASH_TARGETS,+ TTL_ONLY_TABLES,+)class TestDeletionCoverage(ClickhouseTestMixin, BaseTest):@@ -43,3 +48,73 @@ class TestDeletionCoverage(ClickhouseTestMixin, BaseTest):"TTL_ONLY_TABLES with the retention window you are accepting as its erasure bound. ""See docs/internal/clickhouse-deletion-coverage.md.")++ def test_every_personal_data_target_is_squashed_or_exempt(self):+ # A merge moves a distinct_id to another person, and a later deletion names only the+ # survivor, so a target the squash skips keeps its rows on the absorbed person until the+ # TTL drops them (#93035). The test above cannot catch that: it keys on person_properties,+ # which flag_evaluations does not declare, which is how flag_evaluations slipped through.+ skipped = {target.data_table for target in PERSONAL_DATA_TARGETS if not target.accepts_person_id_rewrite}+ unaccounted = sorted(skipped - PERSON_ID_REWRITE_EXEMPT)++ assert not unaccounted, (+ f"{unaccounted} are swept for person deletion, but squash_person_overrides never rewrites "+ "their person_id, so a merge strands rows on the person it absorbed. Set "+ "accepts_person_id_rewrite=True on each (posthog/models/deletion_targets.py), or add it to "+ "PERSON_ID_REWRITE_EXEMPT with the window you are accepting. "+ "See docs/internal/clickhouse-deletion-coverage.md."+ )++ stale = sorted(PERSON_ID_REWRITE_EXEMPT - skipped)+ assert not stale, (+ f"{stale} are in PERSON_ID_REWRITE_EXEMPT but are not registered targets the squash skips. "+ "Remove each entry: either the target now sets accepts_person_id_rewrite=True, or it is no "+ "longer in PERSONAL_DATA_TARGETS."+ )++ def test_squash_targets_accept_an_alter_update_on_person_id(self):+ # The squash rewrites person_id with ALTER UPDATE, and ClickHouse refuses one on a column in+ # the sorting key or the partition key. A target marked accepts_person_id_rewrite whose key+ # carries person_id fails on the weekly job rather than here.+ #+ # Matched on the column name in system.columns rather than scanned out of the key+ # expression: that text both rejects an unrelated column whose name contains person_id and+ # misses the partition key entirely.+ params = {+ "database": settings.CLICKHOUSE_DATABASE,+ "tables": [target.data_table for target in SQUASH_TARGETS],+ }+ # Scoped to the tables that are actually here, because an optional target sits behind a+ # migration that may not have run on this deployment. Absent is fine; present without the+ # column is not.+ present = {+ table+ for [table] in sync_execute(+ "SELECT name FROM system.tables WHERE database = %(database)s AND name IN %(tables)s",+ params,+ )+ }+ assert present, "expected at least the events storage table to exist"++ rows = sync_execute(+ """+ SELECT table, is_in_sorting_key, is_in_partition_key+ FROM system.columns+ WHERE database = %(database)s AND table IN %(tables)s AND name = 'person_id'+ """,+ params,+ )+ # A target the squash rewrites but whose table has no person_id at all drops out of the+ # scan below and would pass unexamined, while the job still issues it an ALTER UPDATE.+ undeclared = sorted(present - {table for table, _, _ in rows})+ assert not undeclared, (+ f"{undeclared} are squash targets whose storage table declares no person_id, so the "+ "ALTER UPDATE the squash issues them cannot resolve its own target column."+ )++ offenders = sorted(table for table, in_sorting, in_partition in rows if in_sorting or in_partition)+ assert not offenders, (+ f"{offenders} are squash targets carrying person_id in their sorting or partition key, "+ "so the squash cannot assign it. Both are fixed once the table holds data, so this "+ "needs a new table rather than an ALTER."+ )diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.pyindex 257fe99cb48d..348fe39eb26e 100644--- a/posthog/dags/deletes.py+++ b/posthog/dags/deletes.py@@ -23,6 +23,7 @@ from posthog.clickhouse.cluster import (NodeRole,Query,Workload,+ wait_for_mutations_on_shards,)from posthog.clickhouse.plugin_log_entries import PLUGIN_LOG_ENTRIES_TABLEfrom posthog.dags.common import JobOwners@@ -875,8 +876,9 @@ def wait_for_delete_mutations_in_shards(pending_deletes_dict, cluster_mutations = delete_mutationsfor (cluster_name, shard_role), shard_mutations in cluster_mutations.items():- handle = cluster.sibling(cluster_name, shard_role)- handle.map_all_hosts_in_shards({shard: mutation.wait for shard, mutation in shard_mutations.items()}).result()+ # Shared with the squash, which is where the retry comes from: under replication lag a+ # mutation can be briefly invisible on a shard, and that used to fail the whole run.+ wait_for_mutations_on_shards(cluster.sibling(cluster_name, shard_role), shard_mutations)return pending_deletes_dictdiff --git a/posthog/dags/person_overrides.py b/posthog/dags/person_overrides.pyindex cee78530860b..42e5e276e5b6 100644--- a/posthog/dags/person_overrides.py+++ b/posthog/dags/person_overrides.py@@ -17,22 +17,9 @@ 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, FLAG_EVALUATIONS, resolve_placements, sweep_clusters+from posthog.models.deletion_targets import SQUASH_TARGETS, 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.-#-# sharded_events_json is deliberately absent, so the squash never reaches the events cluster. Its-# rows keep the person_id a merge left on them, because this job deletes the overrides that record-# the correct one; see COVERAGE_DOC.-#-# Deliberately not PERSONAL_DATA_TARGETS: registering a table for deletion should not silently make-# it a squash target as well.-SQUASH_TARGETS = (EVENTS, FLAG_EVALUATIONS)-def _squash_clusters(cluster: ClickhouseCluster) -> list[ClickhouseCluster]:"""Every cluster the person_id rewrite dispatches to, the handle in hand first.diff --git a/posthog/models/deletion_targets.py b/posthog/models/deletion_targets.pyindex 1173865cd109..5bcb3d4f52e7 100644--- a/posthog/models/deletion_targets.py+++ b/posthog/models/deletion_targets.py@@ -115,6 +115,13 @@ class DeletionTarget:# accepts_property_rewrite=True implies this must stay True too, since the rewrite assumes the# column holds real data; __post_init__ below enforces that pairing.stores_person_properties: bool = True+ # Whether the person-overrides squash rewrites person_id here. A merge moves a distinct_id to+ # another person, and a later deletion names only the survivor, so a table the squash skips+ # keeps its rows on the absorbed person and no sweep ever matches them (#93035).+ # Opt-in rather than assumed, because the rewrite is an ALTER UPDATE and ClickHouse refuses one+ # on a sort key column. Leaving it False is a decision that a merge may strand rows here until+ # the TTL passes; test_deletion_coverage.py makes you record that decision.+ accepts_person_id_rewrite: bool = False# Read uuids from this table when queueing a deferred deletion. False where the rows duplicate# another target's uuids, which would queue each one twice.queue_uuid_candidates: bool = True@@ -171,6 +178,7 @@ EVENTS = DeletionTarget(read_table="events",hogql_schema=HogQLSchema.LEGACY,accepts_property_rewrite=True,+ accepts_person_id_rewrite=True,)EVENTS_JSON = DeletionTarget(@@ -180,6 +188,7 @@ EVENTS_JSON = DeletionTarget(cluster_setting="CLICKHOUSE_EVENTS_CLUSTER",node_role=NodeRole.EVENTS,hogql_schema=HogQLSchema.NATIVE_JSON,+ # Left out of the squash on purpose; PERSON_ID_REWRITE_EXEMPT carries the reason and the cost.# Dual-written from the same events, so its uuids are the legacy table's.queue_uuid_candidates=False,)@@ -195,12 +204,29 @@ FLAG_EVALUATIONS = DeletionTarget(read_table=FLAG_EVALUATIONS_TABLE,optional=True,stores_person_properties=False,+ accepts_person_id_rewrite=True,stored_events=frozenset({FLAG_EVALUATIONS_SOURCE_EVENT}),)EVENTS_TARGETS: tuple[DeletionTarget, ...] = (EVENTS, EVENTS_JSON)PERSONAL_DATA_TARGETS: tuple[DeletionTarget, ...] = (*EVENTS_TARGETS, FLAG_EVALUATIONS)+# Every table squash_person_overrides rewrites person_id on. Derived from the capability rather than+# listed by hand, so registering a target and forgetting the squash is not expressible.+SQUASH_TARGETS: tuple[DeletionTarget, ...] = tuple(+ target for target in PERSONAL_DATA_TARGETS if target.accepts_person_id_rewrite+)++# Targets that carry person_id and are deliberately left out of the squash. An entry is not free:+# it accepts that a merge strands rows on the absorbed person until the TTL drops them, because the+# squash deletes the overrides that recorded the mapping right after applying them.+#+# sharded_events_json is exempt while the squash is not ready to dispatch to the events cluster. A+# run that resolves the table inconsistently is worse than one that never tries: it stages the+# snapshot dictionary onto a cluster it may not mutate, and the overrides are dropped either way.+# Setting accepts_person_id_rewrite on the target is what restores it; see COVERAGE_DOC.+PERSON_ID_REWRITE_EXEMPT: frozenset[str] = frozenset({EVENTS_JSON_DATA_TABLE})+# Storage tables that carry person properties and are reclaimed by their TTL alone. Each entry is a# decision that erasure may lag by the retention window, not an oversight.#