Skip to content

: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.

feat(deletions): dispatch each target to the cluster that stores it (#89046)

Paweł Szczur1f388c09b949
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.md
index c6d5834f9e2b..496354758f9d 100644
--- a/docs/internal/clickhouse-deletion-coverage.md
+++ b/docs/internal/clickhouse-deletion-coverage.md
@@ -37,18 +37,29 @@ The sweep finds nothing to mutate and reports success, while the proxy every ver
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.
+- `placement_for` refuses a registered target whose storage table is on no data node of any cluster reachable from 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.
+`DeletionTarget.cluster_setting` names where a storage table lives, and `ClickhouseCluster.sibling` turns that name into a handle; neither decides 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.
+## Dispatching to a target's own cluster
+
+`resolve_placements` pairs each target with the handle whose shards carry it: the job's own handle where the table is local, a sibling derived from it where it is not.
+The handle in hand is probed first, so a deployment whose tables are all on one cluster never builds a second one.
+
+Sweeps that iterate placements dispatch each target over `placement.cluster.shards`:
+
+- `delete_person_events_op`
+- `execute_event_deletion`, immediate mode
+
+The rest are bound to a single handle and refuse rather than skip when a target has moved off it (`dispatchable_here`, `UnreachableTargetError`):
+
+- Property removal. Its staging table is host-local and its fan-out is one op per shard of one cluster.
+- The deferred queue fill. Both halves of its `INSERT` are host-local: the source table it reads and the `adhoc_events_deletion` queue it writes.
+- `deletes_job`. Its mutation predicate joins a pending-deletes dictionary that would have to be bootstrapped on the second cluster first — created, populated from Postgres, replicated, loaded and checksum-verified.
## Covered tables
@@ -133,6 +144,6 @@ Keeping the fork downstream of person resolution is the contract, tracked on #81
Register 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.
+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.
`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.py
index 232a4835c653..388cad39a978 100644
--- a/posthog/clickhouse/cluster.py
+++ b/posthog/clickhouse/cluster.py
@@ -255,6 +255,36 @@ class ClickhouseCluster:
self.__client_settings = client_settings
self.__retry_policy = retry_policy
self.__connection_overrides = dict(connection_overrides) if connection_overrides else {}
+ # Kept so `sibling` can build a handle for another cluster from the same connection.
+ self.__bootstrap_client = bootstrap_client
+ self.__extra_host_infos = list(extra_hosts) if extra_hosts else []
+ self.__siblings: dict[str, ClickhouseCluster] = {}
+
+ def sibling(self, cluster: str) -> ClickhouseCluster:
+ """A handle addressing ``cluster``, carrying this one's connection settings.
+
+ ``shards`` covers exactly one cluster, so a caller holding a table stored on another one
+ cannot dispatch to it through this instance. Deriving the second handle here rather than
+ from a second resource keeps host, credentials, client settings and retry policy in one
+ place: a handle assembled anywhere else can drift from the one the job already holds.
+
+ Memoized, because discovery costs a query per cluster and callers resolve the same table
+ once per op. Raises whatever the server says when no such cluster is defined here.
+ """
+ if cluster == self.__data_cluster_name:
+ return self
+ sibling = self.__siblings.get(cluster)
+ if sibling is None:
+ sibling = self.__siblings[cluster] = ClickhouseCluster(
+ self.__bootstrap_client,
+ extra_hosts=self.__extra_host_infos,
+ logger=self.__logger,
+ client_settings=self.__client_settings,
+ cluster=cluster,
+ retry_policy=self.__retry_policy,
+ connection_overrides=self.__connection_overrides,
+ )
+ return sibling
def __get_cluster_hosts(self, client: Client, cluster: str, retry_policy: RetryPolicy | None = None):
get_cluster_hosts_fn = lambda client: client.execute(
diff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.py
index 53bfac398f14..f36259131fb5 100644
--- a/posthog/clickhouse/test/test_cluster.py
+++ b/posthog/clickhouse/test/test_cluster.py
@@ -544,6 +544,30 @@ def test_map_hosts_with_satellite_clusters() -> None:
times_called.clear()
+def test_sibling_addresses_another_cluster_and_is_memoized() -> None:
+ hosts_by_cluster = {
+ "posthog": [("host1", 9000, 1, 1, "online", "data")],
+ "events": [
+ ("events-host1", 9000, 1, 1, "online", "data"),
+ ("events-host2", 9000, 2, 1, "online", "data"),
+ ],
+ }
+ bootstrap_client_mock = Mock()
+ bootstrap_client_mock.execute = Mock(side_effect=lambda query, params: hosts_by_cluster[params["name"]])
+
+ cluster = ClickhouseCluster(bootstrap_client_mock, cluster="posthog")
+
+ assert cluster.sibling("posthog") is cluster
+
+ sibling = cluster.sibling("events")
+ assert sibling.data_cluster_name == "events"
+ assert sorted(sibling.shards) == [1, 2]
+ # The handle it was derived from keeps its own shard map, so the two clusters are not merged.
+ assert cluster.shards == [1]
+ # Memoized: rebuilding would rediscover the hosts and open a second pool per host.
+ assert cluster.sibling("events") is sibling
+
+
def test_satellite_cluster_hosts_have_no_shard_info() -> None:
bootstrap_client_mock = Mock()
diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.py
index 504d016fdd08..3e6146ed856f 100644
--- a/posthog/dags/data_deletion_requests.py
+++ b/posthog/dags/data_deletion_requests.py
@@ -43,11 +43,13 @@ from posthog.models.data_deletion_request import (
from posthog.models.deletion_targets import (
COVERAGE_DOC,
DeletionTarget,
+ TargetPlacement,
UnsweepableRowsError,
UnsweptRowsError,
assert_no_unsweepable_rows,
assert_sweep_complete,
- resolve_targets,
+ resolve_placements,
+ resolve_targets_here,
)
from posthog.models.event.deletion import cluster_has_events_json_table
from posthog.models.event.sql import (
@@ -481,22 +483,22 @@ def _verify_swept(
raise dagster.Failure(description=f"Deletion request {deletion_request.request_id}: {exc}") from exc
-def _event_removal_targets(
+def _event_removal_placements(
cluster: ClickhouseCluster, deletion_request: DeletionRequestContext
-) -> list[DeletionTarget]:
- """Targets this event-removal request can actually sweep, refusing to strand rows on the rest."""
+) -> list[TargetPlacement]:
+ """Targets this event-removal request can sweep, each with the handle that reaches it."""
events = [] if deletion_request.delete_all_events else deletion_request.events
# A target that can't hold any of the named events has nothing to sweep, and mutations serialize
# per table, so enqueueing a no-op one would queue in front of real work.
- targets = [target for target in resolve_targets(cluster) if target.may_hold_any_of(events)]
+ placements = [p for p in resolve_placements(cluster) if p.target.may_hold_any_of(events)]
if not deletion_request.hogql_predicate:
- return targets
+ return placements
- unsweepable = [target for target in targets if not target.accepts_hogql_predicate]
+ unsweepable = [p.target for p in placements if not p.target.accepts_hogql_predicate]
if unsweepable:
predicate, params = portable_event_removal_where(deletion_request)
_refuse_unsweepable(cluster, unsweepable, deletion_request, predicate, params, reason=_HOGQL_UNSWEEPABLE_REASON)
- return [target for target in targets if target.accepts_hogql_predicate]
+ return [p for p in placements if p.target.accepts_hogql_predicate]
def _run_immediate_event_deletion(
@@ -504,20 +506,24 @@ def _run_immediate_event_deletion(
cluster: ClickhouseCluster,
deletion_request: DeletionRequestContext,
) -> None:
- targets = _event_removal_targets(cluster, deletion_request)
- shards = sorted(cluster.shards)
+ placements = _event_removal_placements(cluster, deletion_request)
+ targets = [p.target for p in placements]
- context.log.info(
- f"Starting immediate event deletion across {len(shards)} shards on tables {[t.data_table for t in targets]}"
- )
+ context.log.info(f"Starting immediate event deletion on tables {[t.data_table for t in targets]}")
- for target in targets:
+ swept_shards = 0
+ for placement in placements:
+ target = placement.target
# The HogQL fragment compiles differently per schema: materialized-column/JSONExtract
# reads on the legacy table, JSON subcolumn reads on the native-JSON table.
predicate, parameters = event_removal_where(
deletion_request, use_new_events_schema=target.uses_new_events_schema
)
+ # placement.cluster, not the job's handle: shard numbers are per cluster.
+ shards = sorted(placement.cluster.shards)
+ swept_shards += len(shards)
+
for idx, shard_num in enumerate(shards, 1):
context.log.info(f"Processing {target.data_table} shard {shard_num} ({idx}/{len(shards)})")
shard_start = time.monotonic()
@@ -529,9 +535,9 @@ def _run_immediate_event_deletion(
settings={"lightweight_deletes_sync": 0},
)
- shard_result = cluster.map_any_host_in_shards({shard_num: runner}).result()
+ shard_result = placement.cluster.map_any_host_in_shards({shard_num: runner}).result()
_host, mutation_waiter = next(iter(shard_result.items()))
- cluster.map_all_hosts_in_shard(shard_num, mutation_waiter.wait).result()
+ placement.cluster.map_all_hosts_in_shard(shard_num, mutation_waiter.wait).result()
elapsed = time.monotonic() - shard_start
context.log.info(f"{target.data_table} shard {shard_num} complete in {elapsed:.1f}s")
@@ -550,7 +556,7 @@ def _run_immediate_event_deletion(
context.add_output_metadata(
{
"mode": dagster.MetadataValue.text("immediate"),
- "shards_processed": dagster.MetadataValue.int(len(shards)),
+ "shards_processed": dagster.MetadataValue.int(swept_shards),
"swept_tables": dagster.MetadataValue.text(", ".join(t.data_table for t in targets)),
}
)
@@ -565,7 +571,20 @@ def _queue_events_for_deferred_deletion(
# personal-data table. Flag-evaluation rows still have to be read on their own: they mirror a
# subset of events, so a uuid there may not be in sharded_events once routing moves those
# events off it.
- sources = [t for t in _event_removal_targets(cluster, deletion_request) if t.queue_uuid_candidates]
+ placements = [p for p in _event_removal_placements(cluster, deletion_request) if p.target.queue_uuid_candidates]
+ # Both halves of the INSERT are host-local: the source table and the queue it feeds. A source
+ # on another cluster has no host that holds both, and reading it through its Distributed proxy
+ # instead would pull every matching uuid across the wire into one shard's queue.
+ stranded = [p.target for p in placements if p.cluster is not cluster]
+ if stranded:
+ raise dagster.Failure(
+ description=(
+ f"Deletion request {deletion_request.request_id}: cannot queue uuids from "
+ f"{', '.join(t.data_table for t in stranded)}; the queue is on "
+ f"{cluster.data_cluster_name!r} and those tables are not. See {COVERAGE_DOC}."
+ )
+ )
+ sources = [p.target for p in placements]
db = django_settings.CLICKHOUSE_DATABASE
shards = sorted(cluster.shards)
predicate, params = event_removal_where(deletion_request)
@@ -726,7 +745,7 @@ def get_property_removal_shards(
anything, is what stops the request completing while matching rows survive elsewhere. It lives
in this op rather than the load op because this is the first one holding a cluster handle.
"""
- unsweepable = [t for t in resolve_targets(cluster) if not t.accepts_property_rewrite]
+ unsweepable = [t for t in resolve_targets_here(cluster) if not t.accepts_property_rewrite]
if unsweepable:
marker = deletion_request.inserted_at_marker
if marker is None:
@@ -1066,7 +1085,7 @@ def verify_property_removal(
# Repeat the fan-out gate here. That one is point-in-time: rows can land between it and now, and
# a re-execution from a failed shard reuses the fan-out op's cached output without re-running it.
# Bounded by the same marker as the checks below so post-marker ingestion can't wedge the run.
- unsweepable = [t for t in resolve_targets(cluster) if not t.accepts_property_rewrite]
+ unsweepable = [t for t in resolve_targets_here(cluster) if not t.accepts_property_rewrite]
if unsweepable:
presence, presence_params = _property_removal_where(deletion_request, inserted_at_max=marker_str)
_refuse_unsweepable(
@@ -1283,17 +1302,21 @@ def delete_person_events_op(
context.log.info("No persons resolved; nothing to delete")
return person_removal
- targets = resolve_targets(cluster)
- shards = sorted(cluster.shards)
+ placements = resolve_placements(cluster)
+ targets = [p.target for p in placements]
context.log.info(
- f"Deleting rows for {len(person_removal.person_uuids)} persons across {len(shards)} shards "
- f"on tables {[t.data_table for t in targets]}"
+ f"Deleting rows for {len(person_removal.person_uuids)} persons on tables {[t.data_table for t in targets]}"
)
# Schema-agnostic columns only (team_id, person_id, timestamp), so one predicate serves every
# target.
predicate, params = _person_event_predicate(person_removal)
- for target in targets:
+ swept_shards = 0
+ for placement in placements:
+ target = placement.target
+ # placement.cluster, not the job's handle: shard numbers are per cluster.
+ shards = sorted(placement.cluster.shards)
+ swept_shards += len(shards)
for idx, shard_num in enumerate(shards, 1):
context.log.info(f"Processing {target.data_table} shard {shard_num} ({idx}/{len(shards)})")
shard_start = time.monotonic()
@@ -1303,9 +1326,9 @@ def delete_person_events_op(
parameters=params,
settings={"lightweight_deletes_sync": 0},
)
- shard_result = cluster.map_any_host_in_shards({shard_num: runner}).result()
+ shard_result = placement.cluster.map_any_host_in_shards({shard_num: runner}).result()
_host, waiter = next(iter(shard_result.items()))
- cluster.map_all_hosts_in_shard(shard_num, waiter.wait).result()
+ placement.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:
@@ -1315,7 +1338,7 @@ def delete_person_events_op(
context.add_output_metadata(
{
- "shards_processed": dagster.MetadataValue.int(len(shards)),
+ "shards_processed": dagster.MetadataValue.int(swept_shards),
"swept_tables": dagster.MetadataValue.text(", ".join(t.data_table for t in targets)),
}
)
diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.py
index 7f81e9e43f66..4c5583447b04 100644
--- a/posthog/dags/tests/test_data_deletion_requests.py
+++ b/posthog/dags/tests/test_data_deletion_requests.py
@@ -7,6 +7,7 @@ from uuid import uuid4
import pytest
from unittest.mock import patch
+from django.conf import settings as django_settings
from django.utils import timezone
import dagster
@@ -46,7 +47,13 @@ from posthog.models.data_deletion_request import (
RequestType,
auto_approve_pending_requests,
)
-from posthog.models.deletion_targets import DeletionTarget, UnreachableTargetError, is_present
+from posthog.models.deletion_targets import (
+ EVENTS,
+ DeletionTarget,
+ TargetPlacement,
+ UnreachableTargetError,
+ placement_for,
+)
from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_DATA_TABLE, FLAG_EVALUATIONS_SOURCE_EVENT
from posthog.test.persons import create_person
@@ -1986,12 +1993,12 @@ def test_delete_person_events_op_runs_lightweight_delete_per_shard(cluster: Clic
@pytest.mark.django_db
-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.
+def test_placement_for_refuses_a_target_no_cluster_here_can_sweep(cluster: ClickhouseCluster):
+ # Mutations dispatch over the shards of the one cluster a 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_placements 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, on a cluster
+ # this deployment does not define, behind a proxy that still reads rows.
target = DeletionTarget(
data_table="sharded_events_on_another_cluster",
read_table="events",
@@ -2000,11 +2007,50 @@ def test_is_present_refuses_a_target_this_handle_cannot_sweep(cluster: Clickhous
)
cluster.any_host(_truncate_writable_events).result()
- assert is_present(cluster, target) is False
+ assert placement_for(cluster, target) is None
cluster.any_host(partial(_insert_events, [(TEAM_ID, "$pageview", str(uuid4()), datetime.now())])).result()
with pytest.raises(UnreachableTargetError):
- is_present(cluster, target)
+ placement_for(cluster, target)
+
+
+def test_delete_person_events_op_dispatches_on_the_targets_own_cluster(cluster: ClickhouseCluster):
+ # Shard numbers are per cluster, so the handle a target is paired with is the only one whose
+ # shards mean anything for it. Sweeping an off-cluster table over the job's own handle sends
+ # its mutations to hosts that never held those rows, and every shard still reports complete.
+ person_uuid = str(uuid4())
+ cluster.any_host(_truncate_writable_events).result()
+ cluster.any_host(
+ partial(_insert_events_with_person, [(TEAM_ID, "$pageview", str(uuid4()), datetime.now(), person_uuid)])
+ ).result()
+
+ # A second handle over the same node: a different object with its own shard map, which is what
+ # an off-cluster target's placement looks like here.
+ sibling = cluster.sibling(django_settings.CLICKHOUSE_SINGLE_SHARD_CLUSTER)
+ 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_placements",
+ return_value=[TargetPlacement(target=EVENTS, cluster=sibling)],
+ ),
+ patch.object(sibling, "map_any_host_in_shards", wraps=sibling.map_any_host_in_shards) as on_sibling,
+ patch.object(cluster, "map_any_host_in_shards", wraps=cluster.map_any_host_in_shards) as on_job_handle,
+ ):
+ delete_person_events_op(build_op_context(), cluster, ctx)
+
+ assert on_sibling.called
+ assert not on_job_handle.called
+ assert cluster.any_host(partial(_count_events_for_person, TEAM_ID, person_uuid)).result() == 0
@pytest.mark.django_db
@@ -2030,7 +2076,8 @@ def test_delete_person_events_op_fails_when_the_persons_rows_outlive_the_sweep(c
drop_recordings=False,
)
- with patch("posthog.dags.data_deletion_requests.resolve_targets", return_value=[stranded]):
+ placement = TargetPlacement(target=stranded, cluster=cluster)
+ with patch("posthog.dags.data_deletion_requests.resolve_placements", return_value=[placement]):
with pytest.raises(dagster.Failure, match="still readable"):
delete_person_events_op(build_op_context(), cluster, ctx)
diff --git a/posthog/models/deletion_targets.py b/posthog/models/deletion_targets.py
index 36043d086d8f..910ffdd6ca12 100644
--- a/posthog/models/deletion_targets.py
+++ b/posthog/models/deletion_targets.py
@@ -19,6 +19,7 @@ from functools import partial
from django.conf import settings
from clickhouse_driver import Client
+from clickhouse_driver.errors import ServerException
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import NodeRole
@@ -37,6 +38,9 @@ from posthog.models.flag_evaluations.sql import (
COVERAGE_DOC = "docs/internal/clickhouse-deletion-coverage.md"
+# ClickHouse's CLUSTER_DOESNT_EXIST, which clickhouse_driver does not name.
+_CLUSTER_DOESNT_EXIST = 701
+
class DeletionCoverageError(Exception):
"""A deletion would report success while rows it named survive somewhere."""
@@ -74,10 +78,12 @@ class DeletionTarget:
data_table: str
read_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.
+ # Name of the Django setting holding the cluster its storage table is on. A target naming a
+ # cluster the job's handle does not address is swept through a sibling handle for that cluster.
+ # Reachability is still 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.
+ # Anything that may live elsewhere must also be ``optional``, since that is what makes the
+ # storage table's presence a question rather than an assumption.
cluster_setting: str = "CLICKHOUSE_CLUSTER"
# Guarded on system.tables: the table sits behind a migration that may not have run everywhere.
optional: bool = False
@@ -122,6 +128,19 @@ class DeletionTarget:
return not self.stored_events.isdisjoint(events)
+@dataclass(frozen=True, kw_only=True)
+class TargetPlacement:
+ """A target and the cluster handle whose shards carry its storage table.
+
+ Sweeps dispatch per shard, and a handle enumerates the shards of exactly one cluster, so the
+ two travel together: reading the target off one handle and dispatching it on another is the
+ mistake this pairing exists to prevent.
+ """
+
+ target: DeletionTarget
+ cluster: ClickhouseCluster
+
+
EVENTS = DeletionTarget(
data_table=EVENTS_DATA_TABLE(),
read_table="events",
@@ -217,34 +236,90 @@ def _assert_no_rows_behind_the_proxy(cluster: ClickhouseCluster, target: Deletio
)
-def is_present(cluster: ClickhouseCluster, target: DeletionTarget) -> bool:
- """Whether this handle can sweep the target, refusing rather than skipping when it cannot.
+def _any_data_node_has(cluster: ClickhouseCluster, table: str) -> bool:
+ """Whether any data node of ``cluster`` carries ``table``.
- ``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.
+ ``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.
"""
- if not target.optional:
- return True
- results = cluster.map_hosts_by_role(partial(_table_exists, table=target.data_table), NodeRole.DATA).result()
- if any(results.values()):
- return True
+ results = cluster.map_hosts_by_role(partial(_table_exists, table=table), NodeRole.DATA).result()
+ return any(results.values())
+
+
+def _sibling_holding(cluster: ClickhouseCluster, target: DeletionTarget) -> ClickhouseCluster | None:
+ """A handle for the target's own cluster, when that cluster is defined here and carries it."""
+ if target.cluster_name == cluster.data_cluster_name:
+ return None
+ try:
+ sibling = cluster.sibling(target.cluster_name)
+ except ServerException as exc:
+ if exc.code != _CLUSTER_DOESNT_EXIST:
+ raise
+ # No such cluster here, which is every deployment the split that moves this table has not
+ # reached: local, CI, self-hosted. Leave the verdict to the proxy check.
+ return None
+ return sibling if _any_data_node_has(sibling, target.data_table) else None
+
+
+def placement_for(cluster: ClickhouseCluster, target: DeletionTarget) -> TargetPlacement | None:
+ """Where ``target`` can be swept from, refusing rather than skipping when nowhere can.
+
+ Reachability is settled by probing hosts, never by comparing cluster names: two names can
+ cover the same nodes, which is what the dev stack and CI do. So the handle in hand is tried
+ first, and a sibling is built only for a table it does not carry.
+ """
+ if not target.optional or _any_data_node_has(cluster, target.data_table):
+ return TargetPlacement(target=target, cluster=cluster)
+
+ sibling = _sibling_holding(cluster, target)
+ if sibling is not None:
+ return TargetPlacement(target=target, cluster=sibling)
+
_assert_no_rows_behind_the_proxy(cluster, target)
- return False
+ return None
-def resolve_targets(
+def dispatchable_here(cluster: ClickhouseCluster, target: DeletionTarget) -> bool:
+ """Whether ``cluster``'s own shards carry ``target``, for sweeps bound to a single handle.
+
+ Refuses instead of answering False when another cluster's shards carry it. A caller fanning
+ out over ``cluster.shards`` cannot reach those rows, and skipping them would report work it
+ never did.
+ """
+ placement = placement_for(cluster, target)
+ if placement is None:
+ return False
+ if placement.cluster is cluster:
+ return True
+ raise UnreachableTargetError(
+ f"{target.data_table} is stored on cluster {target.cluster_name!r}, which this sweep has no "
+ f"way to reach: it dispatches per shard of {cluster.data_cluster_name!r}. Running without "
+ f"it would report an erasure that did not happen. See {COVERAGE_DOC}."
+ )
+
+
+def resolve_placements(
cluster: ClickhouseCluster, targets: Sequence[DeletionTarget] = PERSONAL_DATA_TARGETS
-) -> list[DeletionTarget]:
- """The subset of ``targets`` this handle can sweep.
+) -> list[TargetPlacement]:
+ """Every target that can be swept, each paired with the handle that reaches it.
- Raises rather than narrowing when one it cannot sweep still holds rows; see ``is_present``.
+ Raises rather than narrowing when one that cannot be reached still holds rows; see
+ ``placement_for``.
"""
- return [target for target in targets if is_present(cluster, target)]
+ placements = (placement_for(cluster, target) for target in targets)
+ return [placement for placement in placements if placement is not None]
+
+
+def resolve_targets_here(
+ cluster: ClickhouseCluster, targets: Sequence[DeletionTarget] = PERSONAL_DATA_TARGETS
+) -> list[DeletionTarget]:
+ """The subset of ``targets`` ``cluster``'s own shards carry; see ``dispatchable_here``."""
+ return [target for target in targets if dispatchable_here(cluster, target)]
def personal_data_tables(cluster: ClickhouseCluster) -> list[str]:
"""Every physical table a person, team, or queued-uuid deletion must sweep."""
- return [target.data_table for target in resolve_targets(cluster)]
+ return [target.data_table for target in resolve_targets_here(cluster)]
def resolve_data_targets_via_sync_execute(targets: Sequence[DeletionTarget]) -> list[DeletionTarget]:
diff --git a/posthog/models/event/deletion.py b/posthog/models/event/deletion.py
index ee16a85855e6..cd40a2b7c1ae 100644
--- a/posthog/models/event/deletion.py
+++ b/posthog/models/event/deletion.py
@@ -16,21 +16,24 @@ from posthog.clickhouse.cluster import ClickhouseCluster
from posthog.models.deletion_targets import (
EVENTS_JSON,
EVENTS_TARGETS,
- is_present,
+ dispatchable_here,
resolve_data_targets_via_sync_execute,
resolve_read_targets_via_sync_execute,
- resolve_targets,
+ resolve_targets_here,
)
def cluster_has_events_json_table(cluster: ClickhouseCluster) -> bool:
- """Whether any data node carries the native-JSON events data table."""
- return is_present(cluster, EVENTS_JSON)
+ """Whether this handle's own data nodes carry the native-JSON events data table.
+
+ Refuses rather than answering False when another cluster's do; see ``dispatchable_here``.
+ """
+ return dispatchable_here(cluster, EVENTS_JSON)
def events_data_tables(cluster: ClickhouseCluster) -> list[str]:
"""The physical events data tables that deletions/mutations must target, for Dagster jobs."""
- return [target.data_table for target in resolve_targets(cluster, EVENTS_TARGETS)]
+ return [target.data_table for target in resolve_targets_here(cluster, EVENTS_TARGETS)]
def events_data_tables_via_sync_execute() -> list[str]:
diff --git a/posthog/models/test/test_deletion_targets.py b/posthog/models/test/test_deletion_targets.py
new file mode 100644
index 000000000000..2919045ca0d2
--- /dev/null
+++ b/posthog/models/test/test_deletion_targets.py
@@ -0,0 +1,80 @@
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+
+import pytest
+from unittest.mock import Mock, patch
+
+from django.test import override_settings
+
+from posthog.clickhouse.cluster import ClickhouseCluster, HostInfo
+from posthog.models.deletion_targets import DeletionTarget, UnreachableTargetError, dispatchable_here, placement_for
+
+# One data node each, so a table present on one cluster and absent from the other is the only
+# difference between them. That is the topology the placement resolution exists for and the one no
+# single-node test environment can reproduce.
+_HOSTS_BY_CLUSTER: dict[str, list[tuple]] = {
+ "posthog": [("data1", 9000, 1, 1, "online", "data")],
+ "events": [("events1", 9000, 1, 1, "online", "data")],
+}
+
+_OFF_CLUSTER_TARGET = DeletionTarget(
+ data_table="sharded_events_json",
+ read_table="events_json",
+ optional=True,
+ cluster_setting="CLICKHOUSE_EVENTS_CLUSTER",
+)
+
+
+class _FakeClient:
+ def __init__(self, tables: set[str]) -> None:
+ self._tables = tables
+
+ def execute(self, query: str, params: dict | None = None, *args: object, **kwargs: object) -> list[list[int]]:
+ if "system.tables" in query:
+ assert params is not None
+ return [[1 if params["name"] in self._tables else 0]]
+ raise AssertionError(f"unexpected query: {query}")
+
+
+@contextmanager
+def _cluster_with(tables_by_host: dict[str, set[str]]) -> Iterator[ClickhouseCluster]:
+ """A handle on ``posthog`` whose hosts, and its siblings' hosts, carry the tables given."""
+ bootstrap = Mock()
+ bootstrap.execute = Mock(side_effect=lambda query, params: _HOSTS_BY_CLUSTER[params["name"]])
+
+ def get_task_function(_self: ClickhouseCluster, host: HostInfo, fn: Callable) -> Callable:
+ return lambda: fn(_FakeClient(tables_by_host[host.connection_info.host]))
+
+ with patch.object(ClickhouseCluster, "_ClickhouseCluster__get_task_function", get_task_function):
+ yield ClickhouseCluster(bootstrap, cluster="posthog")
+
+
+@override_settings(CLICKHOUSE_EVENTS_CLUSTER="events")
+def test_placement_routes_a_target_to_the_cluster_that_carries_it() -> None:
+ with _cluster_with({"data1": set(), "events1": {"sharded_events_json"}}) as cluster:
+ placement = placement_for(cluster, _OFF_CLUSTER_TARGET)
+
+ assert placement is not None
+ assert placement.cluster.data_cluster_name == "events"
+ assert placement.cluster is not cluster
+
+
+@override_settings(CLICKHOUSE_EVENTS_CLUSTER="events")
+def test_placement_prefers_the_handle_in_hand_over_a_sibling() -> None:
+ # Two cluster names covering the same nodes is what the dev stack and CI do. Building a sibling
+ # there would sweep the same rows twice, so the handle in hand has to win.
+ with _cluster_with({"data1": {"sharded_events_json"}, "events1": {"sharded_events_json"}}) as cluster:
+ placement = placement_for(cluster, _OFF_CLUSTER_TARGET)
+
+ assert placement is not None
+ assert placement.cluster is cluster
+
+
+@override_settings(CLICKHOUSE_EVENTS_CLUSTER="events")
+def test_dispatchable_here_refuses_a_target_another_cluster_carries() -> None:
+ # Sweeps that fan out over a single handle (property removal, the queued-uuid drain) have no way
+ # to reach another cluster's shards. Answering False would put back the silent skip that
+ # completes a request while the rows survive.
+ with _cluster_with({"data1": set(), "events1": {"sharded_events_json"}}) as cluster:
+ with pytest.raises(UnreachableTargetError):
+ dispatchable_here(cluster, _OFF_CLUSTER_TARGET)