: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): refuse targets this cluster handle cannot sweep (#85684)
Paweł Szczur490edde0a145
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex 29b6511047f7..c6d5834f9e2b 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -24,6 +24,32 @@ Team deletion for tables that are replicated rather than sharded runs through aA sharded table must not be registered there — it would sweep one shard.The team arm inside `delete_events` covers sharded tables.+## Reach: one handle addresses one cluster++Every sweep dispatches over a `ClickhouseCluster`, and one of those addresses exactly one cluster.+Hosts come from `clusterAllReplicas(<name>, system.clusters) WHERE name = <name> AND is_local`, and only hosts whose `hostClusterRole` macro is `data` are given a shard number.+`cluster.shards`, `map_one_host_per_shard` and `map_any_host_in_shards`, which is how every mutation reaches a storage table, enumerate those hosts alone.+Passing `data_cluster=` replaces that shard map rather than merging a second one in, so a single handle cannot span two clusters.++A Distributed table has no such limit: it routes to whichever cluster its engine names.+That asymmetry is what makes an off-cluster storage table dangerous rather than merely unsupported.+The sweep finds nothing to mutate and reports success, while the proxy every verification reads through still returns the rows.++Two gates keep that from passing silently.++- `is_present` refuses a registered target whose storage table is on no data node here while its Distributed proxy still returns rows (`UnreachableTargetError`). Absent from everywhere and empty is still treated as not yet migrated, which is the ordinary pre-rollout state.+- `assert_sweep_complete` runs after the immediate person-removal and event-removal sweeps and counts survivors through the proxy, so rows a mutation never reached fail the request instead of completing it (`UnsweptRowsError`).++Both gates probe hosts rather than compare cluster names.+Two cluster names can cover the same nodes, which is what the dev stack and CI do, so a name comparison would refuse deployments that can in fact sweep the table.+`DeletionTarget.cluster_setting` names where a storage table lives for the refusal message and for the dispatch below; it does not decide reachability.+`sharded_events_json` carries `CLICKHOUSE_EVENTS_CLUSTER`, which names the `events` cluster.++Neither gate makes an off-cluster table sweepable.+Reaching one needs a second handle built with `get_cluster(cluster=...)`, and every sweep loop reading its shards from the handle that holds the target rather than from the one the job was given.+The pending-deletes dictionary the `deletes_job` predicate joins against has to be bootstrapped on that second cluster too.+None of that exists yet.+## Covered tables- `sharded_events` — all sweeps.@@ -107,5 +133,6 @@ Keeping the fork downstream of person resolution is the contract, tracked on #81Register 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.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, it cannot be swept at all today; see "Reach" above before registering it.`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.diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.pyindex 91eca8c61fc4..232a4835c653 100644--- a/posthog/clickhouse/cluster.py+++ b/posthog/clickhouse/cluster.py@@ -172,6 +172,10 @@ class ClickhouseCluster:self.__extra_hosts: set[HostInfo] = set()migrations_cluster = cluster or settings.CLICKHOUSE_CLUSTER+ # The cluster whose DATA nodes back `shards`, which is what every sharded mutation+ # dispatches over. Callers holding a table that lives elsewhere have no way to reach it+ # through this instance, so they need to be able to ask.+ self.__data_cluster_name = data_cluster or migrations_clustercluster_hosts = self.__get_cluster_hosts(bootstrap_client, migrations_cluster, retry_policy)for row in cluster_hosts:@@ -343,6 +347,10 @@ class ClickhouseCluster:hosts.update(shard_hosts)return hosts+ @property+ def data_cluster_name(self) -> str:+ return self.__data_cluster_name+@propertydef shards(self) -> list[int]:return list(self.__shards.keys())diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex 90abbb327419..504d016fdd08 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -41,9 +41,12 @@ from posthog.models.data_deletion_request import (verify_queued_request,)from posthog.models.deletion_targets import (+ COVERAGE_DOC,DeletionTarget,UnsweepableRowsError,+ UnsweptRowsError,assert_no_unsweepable_rows,+ assert_sweep_complete,resolve_targets,)from posthog.models.event.deletion import cluster_has_events_json_table@@ -429,13 +432,11 @@ def load_deletion_request()-_COVERAGE_DOC = "docs/internal/clickhouse-deletion-coverage.md"-_HOGQL_UNSWEEPABLE_REASON = ("the request carries a HogQL predicate, which only compiles against the events schema ""(this table has no HogQL table definition, so the compiled fragment names columns it lacks). ""To proceed, re-file the request without the predicate, or narrow its events to ones this "- f"table never stores. See {_COVERAGE_DOC}."+ f"table never stores. See {COVERAGE_DOC}.")@@ -462,6 +463,24 @@ def _refuse_unsweepable(raise dagster.Failure(description=f"Deletion request {deletion_request.request_id}: {exc}") from exc+def _verify_swept(+ cluster: ClickhouseCluster,+ targets: list[DeletionTarget],+ deletion_request: DeletionRequestContext,+ predicate_for: Callable[[DeletionTarget], tuple[str, dict]],+) -> None:+ """Raise a dagster.Failure when rows this request named are still readable after the sweep."""+ try:+ assert_sweep_complete(+ cluster,+ targets,+ predicate_for,+ events=[] if deletion_request.delete_all_events else deletion_request.events,+ )+ except UnsweptRowsError as exc:+ raise dagster.Failure(description=f"Deletion request {deletion_request.request_id}: {exc}") from exc++def _event_removal_targets(cluster: ClickhouseCluster, deletion_request: DeletionRequestContext) -> list[DeletionTarget]:@@ -517,6 +536,17 @@ def _run_immediate_event_deletion(elapsed = time.monotonic() - shard_startcontext.log.info(f"{target.data_table} shard {shard_num} complete in {elapsed:.1f}s")+ _verify_swept(+ cluster,+ targets,+ deletion_request,+ lambda target: (+ event_removal_where(deletion_request, use_new_events_schema=target.uses_new_events_schema)+ if target.accepts_hogql_predicate+ else portable_event_removal_where(deletion_request)+ ),+ )+context.add_output_metadata({"mode": dagster.MetadataValue.text("immediate"),@@ -601,7 +631,7 @@ _PROPERTY_REWRITE_UNSWEEPABLE_REASON = ("be honored by mutation at all, because flag_key sits in the table's sort key where no UPDATE ""can reset it. There is no way to complete this request today: ""either narrow its events to ones this table never stores, or wait out the table's TTL. "- f"See {_COVERAGE_DOC}."+ f"See {COVERAGE_DOC}.")@@ -1278,6 +1308,11 @@ def delete_person_events_op(cluster.map_all_hosts_in_shard(shard_num, waiter.wait).result()context.log.info(f"{target.data_table} shard {shard_num} complete in {time.monotonic() - shard_start:.1f}s")+ try:+ assert_sweep_complete(cluster, targets, lambda _target: (predicate, params), events=[])+ except UnsweptRowsError as exc:+ raise dagster.Failure(description=f"Deletion request {person_removal.request_id}: {exc}") from exc+context.add_output_metadata({"shards_processed": dagster.MetadataValue.int(len(shards)),diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.pyindex 5317ed7ecb66..7f81e9e43f66 100644--- a/posthog/dags/tests/test_data_deletion_requests.py+++ b/posthog/dags/tests/test_data_deletion_requests.py@@ -46,7 +46,8 @@ from posthog.models.data_deletion_request import (RequestType,auto_approve_pending_requests,)-from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_SOURCE_EVENT+from posthog.models.deletion_targets import DeletionTarget, UnreachableTargetError, is_present+from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_DATA_TABLE, FLAG_EVALUATIONS_SOURCE_EVENTfrom posthog.test.persons import create_personTEAM_ID = 99999@@ -1984,6 +1985,56 @@ def test_delete_person_events_op_runs_lightweight_delete_per_shard(cluster: Clicassert surviving == [other_uuid]+def test_is_present_refuses_a_target_this_handle_cannot_sweep(cluster: ClickhouseCluster):+ # Mutations dispatch over the shards of the one cluster this handle enumerates, so a storage+ # table rolled out on another one is on no host it can reach. Reporting it simply absent drops+ # it from resolve_targets and every sweep then completes without touching it, which is the+ # failure this guard exists to stop. Standing in for that: a storage table no host carries,+ # behind a proxy that still reads rows.+ target = DeletionTarget(+ data_table="sharded_events_on_another_cluster",+ read_table="events",+ optional=True,+ cluster_setting="CLICKHOUSE_EVENTS_CLUSTER",+ )++ cluster.any_host(_truncate_writable_events).result()+ assert is_present(cluster, target) is False++ cluster.any_host(partial(_insert_events, [(TEAM_ID, "$pageview", str(uuid4()), datetime.now())])).result()+ with pytest.raises(UnreachableTargetError):+ is_present(cluster, target)+++def test_delete_person_events_op_fails_when_the_persons_rows_outlive_the_sweep(cluster: ClickhouseCluster):+ # The mutation lands on a table the person's rows are not on, so `events` still returns them+ # once every shard reports complete. That is what an unreachable shard or an off-cluster storage+ # table looks like from here, and the request must fail rather than reach COMPLETED.+ person_uuid = str(uuid4())+ cluster.any_host(_truncate_writable_events).result()+ cluster.any_host(_truncate_flag_evaluations).result()+ cluster.any_host(+ partial(_insert_events_with_person, [(TEAM_ID, "$pageview", str(uuid4()), datetime.now(), person_uuid)])+ ).result()++ stranded = DeletionTarget(data_table=FLAG_EVALUATIONS_DATA_TABLE, read_table="events")+ ctx = PersonRemovalContext(+ request_id=str(uuid4()),+ team_id=TEAM_ID,+ person_uuids=[person_uuid],+ person_distinct_ids=[],+ drop_profiles=False,+ drop_events=True,+ drop_recordings=False,+ )++ with patch("posthog.dags.data_deletion_requests.resolve_targets", return_value=[stranded]):+ with pytest.raises(dagster.Failure, match="still readable"):+ delete_person_events_op(build_op_context(), cluster, ctx)++@pytest.mark.django_dbdef test_delete_person_events_op_noop_when_disabled(cluster: ClickhouseCluster):ctx = PersonRemovalContext(diff --git a/posthog/models/deletion_targets.py b/posthog/models/deletion_targets.pyindex b078ee4dd06a..36043d086d8f 100644--- a/posthog/models/deletion_targets.py+++ b/posthog/models/deletion_targets.py@@ -11,7 +11,7 @@ The reasoning behind each registration, exclusion and known gap is indocs/internal/clickhouse-deletion-coverage.md."""-from collections.abc import Sequence+from collections.abc import Callable, Sequencefrom dataclasses import dataclassfrom enum import Enumfrom functools import partial@@ -35,11 +35,25 @@ from posthog.models.flag_evaluations.sql import (FLAG_EVALUATIONS_TABLE,)+COVERAGE_DOC = "docs/internal/clickhouse-deletion-coverage.md"-class UnsweepableRowsError(Exception):++class DeletionCoverageError(Exception):+ """A deletion would report success while rows it named survive somewhere."""+++class UnsweepableRowsError(DeletionCoverageError):"""A deletion would report success while rows it cannot reach survive on another table."""+class UnreachableTargetError(DeletionCoverageError):+ """A registered target's storage table is on a cluster this handle cannot address."""+++class UnsweptRowsError(DeletionCoverageError):+ """A sweep ran to completion and rows it was supposed to remove are still readable."""++class HogQLSchema(Enum):"""Which schema a compiled HogQL predicate must target to run against a table."""@@ -60,6 +74,11 @@ class DeletionTarget:data_table: strread_table: str+ # Name of the Django setting holding the cluster its storage table is on, for the refusal+ # message and for the per-cluster dispatch that does not exist yet. Reachability is decided by+ # probing the hosts, not by comparing this against the handle's cluster: two cluster names can+ # cover the same nodes, which is what the dev stack and CI do.+ cluster_setting: str = "CLICKHOUSE_CLUSTER"# Guarded on system.tables: the table sits behind a migration that may not have run everywhere.optional: bool = False# The schema a HogQL predicate compiles against here, None where no HogQL table definition@@ -79,6 +98,10 @@ class DeletionTarget:# events skip this table without querying it.stored_events: frozenset[str] | None = None+ @property+ def cluster_name(self) -> str:+ return getattr(settings, self.cluster_setting)+@propertydef accepts_hogql_predicate(self) -> bool:return self.hogql_schema is not None@@ -110,6 +133,7 @@ EVENTS_JSON = DeletionTarget(data_table=EVENTS_JSON_DATA_TABLE,read_table=DISTRIBUTED_EVENTS_JSON_TABLE,optional=True,+ cluster_setting="CLICKHOUSE_EVENTS_CLUSTER",hogql_schema=HogQLSchema.NATIVE_JSON,accepts_property_rewrite=True,# Dual-written from the same events, so its uuids are the legacy table's.@@ -157,22 +181,64 @@ def _table_exists_via_sync_execute(table: str) -> bool:return bool(result and result[0][0])+def _has_any_rows(client: Client, table: str) -> bool:+ # LIMIT 1 rather than count(): this only has to answer "is there anything here", and on a+ # multi-terabyte events table a count would read every part.+ # nosemgrep: clickhouse-fstring-param-audit (table is an internal constant, not user input)+ return bool(client.execute(f"SELECT 1 FROM {settings.CLICKHOUSE_DATABASE}.{table} LIMIT 1"))+++def _assert_no_rows_behind_the_proxy(cluster: ClickhouseCluster, target: DeletionTarget) -> None:+ """Fail when a storage table no host here carries still has rows behind its Distributed proxy.++ A ``ClickhouseCluster`` addresses exactly one cluster: hosts come from ``system.clusters`` for+ that one name, and only hosts whose ``hostClusterRole`` macro is ``data`` carry a shard number,+ which is what every sharded mutation dispatches over. A Distributed table has no such limit and+ routes to whichever cluster its engine names, so it still reads rows this handle cannot touch.+ Skipping the target would complete the request while those rows survive.++ Silence when the proxy is missing or empty, which is the ordinary state of a table whose+ rollout has not reached this deployment.+ """++ def probe(client: Client) -> bool:+ if not _table_exists(client, target.read_table):+ return False+ return _has_any_rows(client, target.read_table)++ if not cluster.any_host_by_role(probe, NodeRole.DATA).result():+ return++ raise UnreachableTargetError(+ f"{target.data_table} is registered for deletion with its storage on cluster "+ f"{target.cluster_name!r}, and no data node of {cluster.data_cluster_name!r} carries it, "+ f"while its Distributed proxy {target.read_table} still returns rows. Sweeping without it "+ f"would report an erasure that did not happen. See {COVERAGE_DOC}."+ )++def is_present(cluster: ClickhouseCluster, target: DeletionTarget) -> bool:- """Whether any data node carries this target's storage table.+ """Whether this handle can sweep the target, refusing rather than skipping when it cannot.- ``any`` rather than ``all``: on a partially-migrated cluster the mutation fails loudly on the- hosts missing the table, which is preferable to silently skipping a deletion.+ ``any`` data node rather than ``all``: on a partially-migrated cluster the mutation fails loudly+ on the hosts missing the table, which is preferable to silently skipping a deletion."""if not target.optional:return Trueresults = cluster.map_hosts_by_role(partial(_table_exists, table=target.data_table), NodeRole.DATA).result()- return any(results.values())+ if any(results.values()):+ return True+ _assert_no_rows_behind_the_proxy(cluster, target)+ return Falsedef resolve_targets(cluster: ClickhouseCluster, targets: Sequence[DeletionTarget] = PERSONAL_DATA_TARGETS) -> list[DeletionTarget]:- """The subset of ``targets`` that actually exists on this cluster."""+ """The subset of ``targets`` this handle can sweep.++ Raises rather than narrowing when one it cannot sweep still holds rows; see ``is_present``.+ """return [target for target in targets if is_present(cluster, target)]@@ -203,6 +269,18 @@ def surviving_rows_sql(read_table: str, predicate: str) -> str:return f"SELECT count() FROM {read_table} WHERE {predicate} AND _row_exists = 1"+def count_surviving_rows(cluster: ClickhouseCluster, target: DeletionTarget, predicate: str, params: dict) -> int:+ """Rows still matching ``predicate`` on ``target``, read through its Distributed proxy.++ Read on a data node, which is the only role these tables exist on. Bounded like the job's other+ scans: no target indexes ``event``, so this reads the team's rows across the request's+ partitions once the table is no longer empty.+ """+ query = Query(surviving_rows_sql(target.read_table, predicate), params, settings={"max_execution_time": "1800"})+ rows = cluster.any_host_by_role(query, NodeRole.DATA).result()+ return int(rows[0][0]) if rows else 0++def assert_no_unsweepable_rows(cluster: ClickhouseCluster,targets: Sequence[DeletionTarget],@@ -228,13 +306,39 @@ def assert_no_unsweepable_rows(if not target.may_hold_any_of(events):continue- # Read through the Distributed proxy on a data node — these tables exist on no other role.- # Bounded like the job's other scans: no target indexes `event`, so this reads the team's- # rows across the request's partitions once the table is no longer empty.- query = Query(surviving_rows_sql(target.read_table, predicate), params, settings={"max_execution_time": "1800"})- rows = cluster.any_host_by_role(query, NodeRole.DATA).result()- count = int(rows[0][0]) if rows else 0+ count = count_surviving_rows(cluster, target, predicate, params)if count:raise UnsweepableRowsError(f"{count} row(s) in {target.read_table} match this request but cannot be deleted: {reason}")+++def assert_sweep_complete(+ cluster: ClickhouseCluster,+ targets: Sequence[DeletionTarget],+ predicate_for: Callable[[DeletionTarget], tuple[str, dict]],+ *,+ events: Sequence[str],+) -> None:+ """Fail when rows a finished sweep was supposed to have removed are still readable.++ Counts through the Distributed proxy rather than the storage tables the sweep mutated, so it+ also covers the rows those mutations never reached: a shard the handle does not enumerate, or a+ storage table on another cluster. Call it only once every mutation has been waited on, or it+ reports work still in flight.++ ``predicate_for`` returns the criteria to count per target, because a HogQL fragment compiles+ to different physical columns on the legacy and native-JSON schemas.+ """+ for target in targets:+ if not target.may_hold_any_of(events):+ continue++ predicate, params = predicate_for(target)+ count = count_surviving_rows(cluster, target, predicate, params)+ if count:+ raise UnsweptRowsError(+ f"the sweep finished but {count} row(s) it should have removed are still readable in "+ f"{target.read_table}. Completing now would report an erasure that did not happen. "+ f"See {COVERAGE_DOC}."+ )diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex e950baa650b5..a8c80d47a155 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -316,6 +316,10 @@ CLICKHOUSE_WRITABLE_CLUSTER: str = os.getenv("CLICKHOUSE_WRITABLE_CLUSTER", "posCLICKHOUSE_PRIMARY_REPLICA_CLUSTER: str = os.getenv("CLICKHOUSE_PRIMARY_REPLICA_CLUSTER", "posthog_primary_replica")CLICKHOUSE_AUX_CLUSTER: str = os.getenv("CLICKHOUSE_AUX_CLUSTER", "aux")CLICKHOUSE_AI_EVENTS_CLUSTER: str = os.getenv("CLICKHOUSE_AI_EVENTS_CLUSTER", "ai_events")+# The cluster the native-JSON events tables are rolled out on. Named here so the deletion+# registry can say where a storage table lives; whether a given deployment can reach it is+# decided by probing the hosts, not by comparing this against the handle's cluster.+CLICKHOUSE_EVENTS_CLUSTER: str = os.getenv("CLICKHOUSE_EVENTS_CLUSTER", "events")# CI uses this to run the test suite against both schemas. Production reads use the instance settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA: bool = TEST and get_from_env("CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA", False, type_cast=str_to_bool