: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(deletes): stop adopting a delete mutation an earlier run enqueued (#99972)
Paweł Szczurea894fe102a2
diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.pyindex 17ec2758dc56..ab1a020b0942 100644--- a/posthog/clickhouse/cluster.py+++ b/posthog/clickhouse/cluster.py@@ -10,6 +10,7 @@ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence, Setfrom concurrent.futures import ALL_COMPLETED, FIRST_EXCEPTION, Future, ThreadPoolExecutor, as_completedfrom copy import copyfrom dataclasses import dataclass, field+from datetime import datetimefrom typing import Any, ClassVar, Generic, Literal, NamedTuple, Optional, TypeVarfrom clickhouse_driver import Client@@ -812,6 +813,13 @@ class MutationRunner(abc.ABC):# How long to wait for the table to be free of other mutations before giving up. 0 waits# forever, which is what a caller with no deadline of its own wants.capacity_timeout: float = field(default=0.0, kw_only=True)+ # Oldest ``create_time`` an existing mutation may have for this runner to adopt it instead of+ # enqueueing its own. A command names the dictionaries it joins, never their contents, so a+ # caller whose dictionaries are rebuilt each run produces the same command text over different+ # data. Without a floor the match reaches back to whatever a previous run left in+ # system.mutations, and adopting that finished mutation deletes nothing while reporting done.+ # None keeps the unbounded match, which is right only where the command text pins the data.+ reuse_since: datetime | None = field(default=None, kw_only=True)@abc.abstractmethoddef get_all_commands(self) -> Set[str]:@@ -842,7 +850,7 @@ class MutationRunner(abc.ABC):mutations_running: Mapping[str, str] = {}else:logger.info("Ensuring mutation for %r is running or has completed.", expected_commands)- mutations_running = self.find_existing_mutations(client, expected_commands)+ mutations_running = self.find_existing_mutations(client, expected_commands, since=self.reuse_since)commands_to_enqueue = expected_commands - mutations_running.keys()if not commands_to_enqueue:@@ -907,10 +915,17 @@ class MutationRunner(abc.ABC):)time.sleep(poll_interval)- def find_existing_mutations(self, client: Client, commands: Set[str] | None = None) -> Mapping[str, str]:+ def find_existing_mutations(+ self, client: Client, commands: Set[str] | None = None, since: datetime | None = None+ ) -> Mapping[str, str]:"""Find the mutation ID (if it exists) associated with each command provided (or all commands if no commands arespecified.)++ ``since`` drops mutations created before it, so a caller can refuse to adopt one an earlier+ run enqueued. Pass it on the lookup that decides whether to enqueue, and leave it off the+ one that confirms an enqueue: the second is looking for the mutation it just created, and a+ clock reading taken on another host could exclude it."""if commands is None:commands = self.get_all_commands()@@ -969,6 +984,7 @@ class MutationRunner(abc.ABC):database = %(__database)sAND table = %(__table)sAND NOT is_killed -- ok to restart a killed mutation+ AND (%(__since)s IS NULL OR create_time >= %(__since)s)GROUP BY command) mutations USING (command)ORDER BY position ASC@@ -978,6 +994,7 @@ class MutationRunner(abc.ABC):"__database": settings.CLICKHOUSE_DATABASE,"__table": self.table,"__alter_prefix": alter_prefix,+ "__since": since,# self.parameters are already rendered into __command_*; passing them again would# reintroduce the substitution this avoids.**{f"__command_{i}": text for i, text in enumerate(rendered_commands)},diff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.pyindex c5fb68c855ce..22165509471c 100644--- a/posthog/clickhouse/test/test_cluster.py+++ b/posthog/clickhouse/test/test_cluster.py@@ -3,6 +3,7 @@ import jsonimport uuidfrom collections import defaultdictfrom collections.abc import Callable, Iterator, Mapping+from datetime import datetime, timedeltaimport pytestfrom posthog.test.base import materialized@@ -834,6 +835,54 @@ def test_alter_mutation_force_parameter(cluster: ClickhouseCluster) -> None:assert mutations_count_after[host][0][0] > mutations_count_before[host][0][0]+def test_reuse_since_refuses_a_mutation_created_before_it(cluster: ClickhouseCluster) -> None:+ # A command names the dictionaries it joins, never their contents, so the same text stands for+ # different data on a later run. Adopting the earlier run's finished mutation reports a delete+ # that never ran, and it is silent: the waiter sees a finished mutation and returns at once.+ table = EVENTS_DATA_TABLE()+ cluster.map_one_host_per_shard(Query(f"INSERT INTO {table} SELECT * FROM generateRandom() LIMIT 10")).result()++ sentinel_uuid = uuid.uuid1()++ def build(reuse_since: datetime | None) -> AlterTableMutationRunner:+ return AlterTableMutationRunner(+ table=table,+ commands={"UPDATE person_id = %(uuid)s WHERE 1 = 1"},+ parameters={"uuid": sentinel_uuid},+ reuse_since=reuse_since,+ )++ wait_and_check_mutations_on_shards(cluster, cluster.map_one_host_per_shard(build(None)).result())++ count_mutations = Query(+ "SELECT count() FROM system.mutations WHERE database = currentDatabase() AND table = %(table)s",+ {"table": table},+ )+ before = cluster.map_all_hosts(count_mutations).result()++ def last_create_time(client: Client) -> datetime:+ [[created]] = client.execute(+ "SELECT max(create_time) FROM system.mutations WHERE database = currentDatabase() AND table = %(table)s",+ {"table": table},+ )+ return created++ # The latest reading across hosts, so the floor sits past the mutation on every one of them.+ newest = max(cluster.map_all_hosts(last_create_time).result().values())++ # A floor predating the mutation still adopts it, which is what keeps a retry inside one run+ # from enqueueing the same work twice.+ cluster.map_one_host_per_shard(build(newest - timedelta(hours=1))).result()+ adopted = cluster.map_all_hosts(count_mutations).result()+ for host, rows in before.items():+ assert adopted[host][0][0] == rows[0][0], "a mutation created after the floor should have been adopted"++ cluster.map_one_host_per_shard(build(newest + timedelta(seconds=1))).result()+ enqueued = cluster.map_all_hosts(count_mutations).result()+ for host, rows in before.items():+ assert enqueued[host][0][0] > rows[0][0], "a mutation created before the floor should not have been adopted"++@pytest.mark.parametrize("sql,expected",[diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.pyindex 9594f6f98e9a..43d327a4e6d6 100644--- a/posthog/dags/deletes.py+++ b/posthog/dags/deletes.py@@ -555,6 +555,7 @@ def delete_events(# Every registered target must get this delete, or rows survive on the table that got skipped.placements = resolve_placements(cluster)+ reuse_floor = _mutation_reuse_floor(cluster)delete_mutation_runners = [(placement,@@ -564,6 +565,7 @@ def delete_events(parameters=_delete_predicate_params(load_and_verify_deletes_dictionary, load_and_verify_adhoc_event_deletes_dictionary),+ reuse_since=reuse_floor,),)for placement in placements@@ -632,6 +634,7 @@ def delete_team_data("dictionary": load_and_verify_deletes_dictionary.qualified_name,"team_deletion_type": DeletionType.Team,},+ reuse_since=_mutation_reuse_floor(cluster),)# This mutation run on any host because it will be replicated to all shards since@@ -707,6 +710,18 @@ def _delete_predicate_params(}+def _mutation_reuse_floor(cluster: ClickhouseCluster) -> datetime:+ """A ClickHouse clock reading to bound mutation reuse by; see MutationRunner.reuse_since.++ Read from ClickHouse rather than here so it compares against ``system.mutations.create_time``+ on the same clock. A reading slightly ahead of a host costs a duplicate mutation, which is+ idempotent; one behind would let a previous run's mutation be adopted, which is the failure+ this floor exists to stop.+ """+ rows = cluster.any_host_by_role(Query("SELECT now()"), NodeRole.DATA).result()+ return rows[0][0]++def _rows_from_any_host(cluster: ClickhouseCluster, query: Query) -> list:return [cluster.any_host_by_role(query, NodeRole.DATA).result()]@@ -792,9 +807,6 @@ def mark_deletions_verified(pending_deletions_dictionary: PendingDeletesDictionary,adhoc_event_deletes_dictionary: AdhocEventDeletesDictionary,) -> VerifiedDeletionResources:- # Only a report. The mutations have already run, the requests are marked verified either way,- # and failing here would strand the run without undoing anything. It exists so a sweep that- # removed nothing leaves a trace rather than passing as a clean run.unswept = _count_unswept_rows(context,cluster,@@ -802,14 +814,19 @@ def mark_deletions_verified(adhoc_event_deletes_dictionary,config.verification_max_execution_time,)+ context.add_output_metadata({"unswept_rows": dagster.MetadataValue.json(unswept)})++ # A request marked verified is a claim the rows are gone, and nothing revisits it: the adhoc+ # tombstone this op writes also keeps those uuids out of every later run. So a count that came+ # back non-zero has to stop the marking rather than annotate it. Leaving the requests pending+ # costs a repeated sweep next run, which is the recoverable direction.remaining = {table: count for table, count in unswept.items() if count}if remaining:- context.log.error(- "The sweep finished and rows it should have removed are still readable: "+ raise dagster.Failure(+ description="The sweep finished and rows it should have removed are still readable: "+ ", ".join(f"{table}={count}" for table, count in remaining.items())- + f". Marking these requests verified anyway. See {COVERAGE_DOC}."+ + f". Leaving these requests pending for the next run. See {COVERAGE_DOC}.")- context.add_output_metadata({"unswept_rows": dagster.MetadataValue.json(unswept)})now = timezone.now()deletion_ids = [