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(clickhouse): sweep events_json with patch parts on the events cluster (#112514)

Rory Shanksb8d6d2b11c7c
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.md
index 6fb0a429c145..7d00b6a7c8fe 100644
--- a/docs/internal/clickhouse-deletion-coverage.md
+++ b/docs/internal/clickhouse-deletion-coverage.md
@@ -85,10 +85,8 @@ 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 every table in `SQUASH_TARGETS` — `sharded_events` and `sharded_flag_evaluations` — through a mutation that joins a snapshot dictionary, then deletes the overrides it just applied.
+`squash_person_overrides` rewrites `person_id` on every table in `SQUASH_TARGETS` (`sharded_events`, `sharded_events_json` and `sharded_flag_evaluations`) through an update 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.
-`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 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.
@@ -96,7 +94,7 @@ Leaving one out stays possible, and `PERSON_ID_REWRITE_EXEMPT` is where that dec
## Covered tables
- `sharded_events` — all sweeps.
-- `sharded_events_json` — person, team, queued-uuid and event removal, but `deletes_job` skips it by default today. Not a squash target. Property rewriting is unsupported: temporary properties and quarantine diagnostics retain additional copies that the legacy property-removal machinery does not rewrite. Optional: only present after the native-JSON migration. See the known gap below.
+- `sharded_events_json` — all sweeps, on the events cluster, through patch parts instead of mutations (`uses_patch_parts`). Optional: only present after the native-JSON migration.
- `sharded_flag_evaluations` — person, team, queued-uuid and deferred event removal. Not immediate event removal or property removal (below). Optional.
- `sharded_posthog_document_embeddings_<model>` — event and team deletion, through `delete_event_documents`. An embedded document is keyed by the id of the thing it describes (`document_id`), and an Event deletion's key is that same id, so the pending dictionary is joined on `(team_id, Event, document_id)`. Every per-model table listed by the error tracking facade's `document_embedding_tables` is swept and counted.
@@ -148,31 +146,6 @@ So a run can mark requests verified without proving the rows are gone. What stop
removing nothing is upstream of the count: `MutationRunner.reuse_since` keeps a run from adopting a
mutation an earlier run enqueued, which is the failure the count was added to notice.
-### `deletes_job` skips `sharded_events_json` by default
-
-`SweepTargetsConfig.skip_targets` defaults to `["sharded_events_json"]`, so the weekly sweep leaves
-that table alone and does not address the events cluster at all.
-Deletion request verification reads the same `DEFAULT_DELETION_TARGETS` set, so it does not count
-rows in a table that the default sweep leaves unchanged.
-
-The table's storage is on the events cluster, which `deletes_job` reaches through a sibling handle.
-Resolving that handle has not been reliable: a run that fails to resolve it drops the target and
-still marks the requests verified, which reports an erasure that did not happen. Skipping the target
-outright makes the sweep say so, in `resolve_sweep_targets`, rather than leaving the outcome to
-whether one probe answered.
-
-The cost is that rows `sharded_events_json` holds for a deleted person, team or queued uuid stay
-readable, and the requests covering them are marked verified either way, so a later run does not
-return to them. The table is dual-written from the same events, so those rows duplicate ones the
-sweep does remove from `sharded_events`.
-
-To sweep it again:
-
-- For one run, set `skip_targets: []` under the `resolve_sweep_targets` op in run config.
-- Permanently, add `EVENTS_JSON` to `DEFAULT_DELETION_TARGETS` in `posthog/models/deletion_targets.py`.
-
-Neither restores what earlier runs left behind. That needs a backfill sweep over the affected uuids.
-
### Property removal does not reach `flag_evaluations`
`person_properties` and `group0..group4_properties` no longer exist on the table: no Insight or Hog function used either as a breakdown or a filter, so the ClickHouse team dropped them directly on both prod clusters, and `posthog/models/flag_evaluations/sql.py` no longer declares them, so any environment built from the migrations matches. Event `properties` and `person_id` are still sent.
@@ -252,7 +225,6 @@ Write-time parity is not sufficient on its own, because a later merge moves the
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 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.
`flag_evaluations_backfill_job` (`posthog/dags/flag_evaluations_backfill.py`) is a second producer.
@@ -272,7 +244,7 @@ When one of those runs starts during a copy, the shard stops, and its error name
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; `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.
+A table you do leave out goes in `PERSON_ID_REWRITE_EXEMPT` with the reason.
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.
diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
index 0c129af743d5..1ca1694203d5 100644
--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
@@ -12757,6 +12757,17 @@
'''
# ---
# name: TestDashboard.test_retrieve_dashboard.12
+ '''
+ SELECT "django_content_type"."id",
+ "django_content_type"."app_label",
+ "django_content_type"."model"
+ FROM "django_content_type"
+ WHERE ("django_content_type"."app_label" = 'dashboards'
+ AND "django_content_type"."model" = 'dashboard')
+ LIMIT 21
+ '''
+# ---
+# name: TestDashboard.test_retrieve_dashboard.13
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -12777,7 +12788,7 @@
5 /* ... */))
'''
# ---
-# name: TestDashboard.test_retrieve_dashboard.13
+# name: TestDashboard.test_retrieve_dashboard.14
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -12876,7 +12887,7 @@
LIMIT 21
'''
# ---
-# name: TestDashboard.test_retrieve_dashboard.14
+# name: TestDashboard.test_retrieve_dashboard.15
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -12901,7 +12912,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestDashboard.test_retrieve_dashboard.15
+# name: TestDashboard.test_retrieve_dashboard.16
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -12924,7 +12935,7 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestDashboard.test_retrieve_dashboard.16
+# name: TestDashboard.test_retrieve_dashboard.17
'''
SELECT "posthog_insightvariable"."id",
"posthog_insightvariable"."name",
@@ -12944,7 +12955,7 @@
ORDER BY "posthog_insightvariable"."name" ASC
'''
# ---
-# name: TestDashboard.test_retrieve_dashboard.17
+# name: TestDashboard.test_retrieve_dashboard.18
'''
SELECT "posthog_dashboardtile"."id",
"posthog_dashboardtile"."dashboard_id",
diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.py
index 5cad56ae64b3..2844711dc91e 100644
--- a/posthog/clickhouse/cluster.py
+++ b/posthog/clickhouse/cluster.py
@@ -771,6 +771,16 @@ class MutationNotFound(Exception):
pass
+# The other replicas of a shard fetch a patch part asynchronously, so a read straight after a
+# patch-part sweep can still see the rows on a replica that has not fetched it. This is a grace
+# period before such a read, not a guarantee: a replica that lags longer still shows the rows.
+PATCH_PART_REPLICATION_GRACE_SECONDS = 0 if settings.TEST else 60
+
+
+def wait_for_patch_part_replication() -> None:
+ time.sleep(PATCH_PART_REPLICATION_GRACE_SECONDS)
+
+
# not present in clickhouse_driver.errors.ErrorCodes; see ClickHouse src/Common/ErrorCodes.cpp
TOO_MANY_MUTATIONS = 692
AUTHENTICATION_FAILED = 516
@@ -875,6 +885,10 @@ class MutationRunner(abc.ABC):
# 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)
+ # Run the statement as a lightweight update or delete, which writes a patch part and returns once
+ # it is written. There is no mutation in system.mutations to adopt, wait for capacity on, or poll.
+ # The table needs enable_block_number_column and enable_block_offset_column.
+ patch_parts: bool = field(default=False, kw_only=True)
@abc.abstractmethod
def get_all_commands(self) -> Set[str]:
@@ -897,6 +911,17 @@ class MutationRunner(abc.ABC):
"""
expected_commands = self.get_all_commands()
+ if self.patch_parts:
+ # lightweight_force fails the statement where a patch part is not possible, rather than
+ # running a mutation this runner would never wait for.
+ settings = {
+ **self.settings,
+ "lightweight_delete_mode": "lightweight_update_force",
+ "alter_update_mode": "lightweight_force",
+ }
+ client.execute(self.get_statement(expected_commands), self.parameters, settings=settings)
+ return MutationWaiter(self.table, set())
+
if self.force:
logger.info(
"Forcing mutation for %r, even if it already exists. This may cause issues if the mutation is already running.",
diff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.py
index 1f33fe6305d5..bee21ddf2c90 100644
--- a/posthog/clickhouse/test/test_cluster.py
+++ b/posthog/clickhouse/test/test_cluster.py
@@ -29,8 +29,9 @@ from posthog.clickhouse.cluster import (
T,
get_cluster,
redact_sql_secrets,
+ wait_for_mutations_on_shards,
)
-from posthog.models.event.sql import EVENTS_DATA_TABLE
+from posthog.models.event.sql import EVENTS_DATA_TABLE, EVENTS_JSON_DATA_TABLE
pytestmark = pytest.mark.django_db
@@ -927,6 +928,32 @@ def test_lightweight_delete(cluster: ClickhouseCluster) -> None:
assert all(result[0][0] < count for result in query_results.values())
+def test_patch_part_delete_writes_no_mutation(cluster: ClickhouseCluster) -> None:
+ # A patch-part delete that fell back to ALTER UPDATE would still remove the rows, so the
+ # mutation log is the only place the regression shows.
+ table = EVENTS_JSON_DATA_TABLE
+ kept, deleted = uuid.uuid4(), uuid.uuid4()
+ cluster.map_one_host_per_shard(Query(f"TRUNCATE TABLE {table}")).result()
+ cluster.any_host(
+ Query(
+ f"INSERT INTO {table} (uuid, team_id, event, distinct_id, timestamp) VALUES",
+ [(u, 1, "$pageview", "d", datetime(2026, 1, 1, tzinfo=UTC)) for u in (kept, deleted)],
+ )
+ ).result()
+ mutations_sql = f"SELECT count() FROM system.mutations WHERE database = currentDatabase() AND table = '{table}'"
+ [[[mutations_before]]] = cluster.map_all_hosts(Query(mutations_sql)).result().values()
+
+ runner = LightweightDeleteMutationRunner(
+ table=table, predicate="uuid = %(uuid)s", parameters={"uuid": deleted}, patch_parts=True
+ )
+ wait_for_mutations_on_shards(cluster, runner.enqueue_on_shards(cluster))
+
+ for rows in cluster.map_all_hosts(Query(f"SELECT uuid FROM {table}")).result().values():
+ assert [row[0] for row in rows] == [kept]
+ [[[mutations_after]]] = cluster.map_all_hosts(Query(mutations_sql)).result().values()
+ assert mutations_after == mutations_before
+
+
def test_alter_mutation_force_parameter(cluster: ClickhouseCluster) -> None:
"""Test that force=True skips checking for existing mutations"""
table = EVENTS_DATA_TABLE()
diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.py
index 7c16d1b4cf0e..8128ef5352dc 100644
--- a/posthog/dags/data_deletion_requests.py
+++ b/posthog/dags/data_deletion_requests.py
@@ -28,7 +28,11 @@ import posthog.hogql.compiler.bytecode # noqa: F401
from posthog.clickhouse.adhoc_events_deletion import ADHOC_EVENTS_DELETION_TABLE
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser
-from posthog.clickhouse.cluster import ClickhouseCluster, LightweightDeleteMutationRunner
+from posthog.clickhouse.cluster import (
+ ClickhouseCluster,
+ LightweightDeleteMutationRunner,
+ wait_for_patch_part_replication,
+)
from posthog.clickhouse.events_json import UNPARSEABLE_PROPERTIES_KEY
from posthog.clickhouse.workload import Workload
from posthog.dags.common import JobOwners
@@ -52,6 +56,7 @@ from posthog.models.data_deletion_request import (
)
from posthog.models.deletion_targets import (
COVERAGE_DOC,
+ EVENTS_JSON,
FLAG_EVALUATIONS,
PERSONAL_DATA_TARGETS,
DeletionTarget,
@@ -60,16 +65,10 @@ from posthog.models.deletion_targets import (
UnsweptRowsError,
assert_no_unsweepable_rows,
assert_sweep_complete,
+ placement_for,
resolve_placements,
- resolve_targets_here,
-)
-from posthog.models.event.deletion import cluster_has_events_json_table
-from posthog.models.event.sql import (
- DISTRIBUTED_EVENTS_JSON_TABLE,
- EVENTS_DATA_TABLE,
- EVENTS_JSON_DATA_TABLE,
- json_property_presence_expr,
)
+from posthog.models.event.sql import DISTRIBUTED_EVENTS_JSON_TABLE, json_property_presence_expr
from posthog.models.person.bulk_delete import (
PersonDeletionStep,
delete_persons_profile,
@@ -655,6 +654,8 @@ def _verify_immediate_event_deletion(
) -> None:
tables = list(dict.fromkeys(shard.data_table for shard in deleted_shards))
targets = [next(t for t in PERSONAL_DATA_TARGETS if t.data_table == table) for table in tables]
+ if any(target.uses_patch_parts for target in targets):
+ wait_for_patch_part_replication()
_verify_swept(
cluster,
targets,
@@ -788,6 +789,7 @@ def delete_event_removal_shard(
predicate=predicate,
parameters=parameters,
settings={"lightweight_deletes_sync": 0},
+ patch_parts=placement.target.uses_patch_parts,
)
shard_start = time.monotonic()
@@ -1176,6 +1178,18 @@ def _run_on_shard(cluster: ClickhouseCluster, target: PropertyRemovalTarget, fn:
return next(iter(result.values()))
+def _deletion_target(target: PropertyRemovalTarget) -> DeletionTarget:
+ return next(t for t in PERSONAL_DATA_TARGETS if t.data_table == target.table)
+
+
+def _cluster_for(cluster: ClickhouseCluster, target: PropertyRemovalTarget) -> ClickhouseCluster:
+ """The handle whose shards carry ``target``'s table, which for sharded_events_json is the events cluster."""
+ placement = placement_for(cluster, _deletion_target(target))
+ if placement is None:
+ raise dagster.Failure(description=f"{target.table} is not present on any reachable cluster")
+ return placement.cluster
+
+
def _query_logger(context: dagster.OpExecutionContext, target: PropertyRemovalTarget) -> QueryLogger:
def log(label: str, sql: str) -> None:
context.log.info(f"[{target.mapping_key}] [{label}] {' '.join(sql.split())}")
@@ -1198,22 +1212,23 @@ 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_here(cluster) if not t.accepts_property_rewrite]
+ placements = resolve_placements(cluster)
+ unsweepable = [p.target for p in placements if not p.target.accepts_property_rewrite]
if unsweepable:
# Bound by the same marker as the sweep and the verify gate, so a row ingested after the
# marker, which the sweep would never touch, cannot refuse the request forever.
_refuse_property_removal_unsweepable(cluster, unsweepable, deletion_request, _marker_str(deletion_request))
- tables = [(EVENTS_DATA_TABLE(), False)]
- if cluster_has_events_json_table(cluster):
- tables.append((EVENTS_JSON_DATA_TABLE, True))
- shards = sorted(cluster.shards)
+ rewritten = [p for p in placements if p.target.accepts_property_rewrite]
context.log.info(
- f"Fanning out property removal {deletion_request.request_id} to {len(tables)} table(s) x {len(shards)} shard(s)"
+ f"Fanning out property removal {deletion_request.request_id} to "
+ + ", ".join(f"{p.target.data_table} x {len(p.cluster.shards)} shard(s)" for p in rewritten)
)
- for table, json_schema in tables:
- for shard in shards:
- target = PropertyRemovalTarget(table=table, shard=shard, json_schema=json_schema)
+ for placement in rewritten:
+ for shard in sorted(placement.cluster.shards):
+ target = PropertyRemovalTarget(
+ table=placement.target.data_table, shard=shard, json_schema=placement.target.uses_new_events_schema
+ )
yield dagster.DynamicOutput(target, mapping_key=target.mapping_key)
@@ -1315,7 +1330,7 @@ def copy_property_removal_shard(
def copy(client: Client) -> dict:
return _copy_property_removal_target(client, deletion_request, target, marker_str, hogql_compiled, staging, log)
- copied = _run_on_shard(cluster, target, copy)
+ copied = _run_on_shard(_cluster_for(cluster, target), target, copy)
context.add_output_metadata({"copied": dagster.MetadataValue.int(copied["rows"])})
return target
@@ -1410,6 +1425,7 @@ def delete_property_removal_shard(
parameters=predicate.params,
settings={"lightweight_deletes_sync": 2, "mutations_sync": 2},
reuse_since=delete_since,
+ patch_parts=_deletion_target(target).uses_patch_parts,
)
log("delete-originals", delete_runner.get_statement(delete_runner.get_all_commands()))
# mutations_sync = 2 blocks on every replica of this shard; the explicit wait is a backstop.
@@ -1418,7 +1434,7 @@ def delete_property_removal_shard(
staging.finish_step(client, _DELETED, {"rows": originals})
return originals
- deleted = _run_on_shard(cluster, target, delete)
+ deleted = _run_on_shard(_cluster_for(cluster, target), target, delete)
context.add_output_metadata({"deleted": dagster.MetadataValue.int(deleted)})
return target
@@ -1482,6 +1498,7 @@ def reingest_property_removal_shard(
parameters=month_params,
settings={"lightweight_deletes_sync": 2, "mutations_sync": 2},
reuse_since=clear_since,
+ patch_parts=_deletion_target(target).uses_patch_parts,
)
log("clear-partial-reingest", clear_runner.get_statement(clear_runner.get_all_commands()))
clear_runner(client).wait(client)
@@ -1509,7 +1526,7 @@ def reingest_property_removal_shard(
staging.finish_step(client, _REINGESTED, {"rows": copied["rows"]})
return copied["rows"]
- reingested = _run_on_shard(cluster, target, reingest)
+ reingested = _run_on_shard(_cluster_for(cluster, target), target, reingest)
context.add_output_metadata({"reingested": dagster.MetadataValue.int(reingested)})
return target
@@ -1580,7 +1597,7 @@ def verify_property_removal_shard(
staging.finish_step(client, _VERIFIED, {"rows": sum(cleaned_months.values())})
return stats
- stats = _run_on_shard(cluster, target, verify)
+ stats = _run_on_shard(_cluster_for(cluster, target), target, verify)
context.add_output_metadata({"verified": dagster.MetadataValue.int(stats["copied"])})
return stats
@@ -1596,6 +1613,10 @@ def _target_presence_clause(
if target.json_schema
else _property_filter_clause(deletion_request.properties)
)
+ elif target.json_schema and deletion_request.person_properties:
+ # Matches the selection in _property_removal_where: quarantined raw properties can hold a
+ # $set copy of a person property, and the copy does not clean them.
+ clauses.append(json_property_presence_expr("properties", UNPARSEABLE_PROPERTIES_KEY))
if deletion_request.person_properties:
clauses.append(
_json_property_filter_clause(deletion_request.person_properties, column="person_properties")
@@ -1640,7 +1661,8 @@ 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_here(cluster) if not t.accepts_property_rewrite]
+ placements = resolve_placements(cluster)
+ unsweepable = [p.target for p in placements if not p.target.accepts_property_rewrite]
if unsweepable:
_refuse_property_removal_unsweepable(cluster, unsweepable, deletion_request, marker_str)
@@ -1649,7 +1671,7 @@ def verify_property_removal(
targets: list[tuple[str, bool, tuple[str, dict]]] = [
("events", False, compile_hogql_predicate(deletion_request)),
]
- if cluster_has_events_json_table(cluster):
+ if any(p.target is EVENTS_JSON for p in placements):
targets.append(
(
DISTRIBUTED_EVENTS_JSON_TABLE,
@@ -1689,6 +1711,8 @@ def verify_property_removal(
)[0][0]
return remaining
+ if any(p.target.uses_patch_parts for p in placements):
+ wait_for_patch_part_replication()
results = [
cluster.any_host(partial(check, table=table, json_schema=json_schema, hogql_compiled=hogql_compiled)).result()
for table, json_schema, hogql_compiled in targets
@@ -1729,7 +1753,7 @@ def cleanup_property_removal_staging(
target = PropertyRemovalTarget(table=stats["table"], shard=stats["shard"], json_schema=stats["json_schema"])
staging = _ShardStaging(request_id=deletion_request.request_id, target=target)
- emptied = _run_on_shard(cluster, target, staging.empty_data_files)
+ emptied = _run_on_shard(_cluster_for(cluster, target), target, staging.empty_data_files)
context.log.info(f"[{target.mapping_key}] emptied {emptied} staged file(s)")
return deletion_request
@@ -1877,12 +1901,15 @@ def delete_person_events_op(
predicate=predicate,
parameters=params,
settings={"lightweight_deletes_sync": 0},
+ patch_parts=target.uses_patch_parts,
)
shard_result = placement.cluster.map_any_host_in_shards({shard_num: runner}).result()
_host, waiter = next(iter(shard_result.items()))
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")
+ if any(target.uses_patch_parts for target in targets):
+ wait_for_patch_part_replication()
try:
assert_sweep_complete(cluster, targets, lambda _target: (predicate, params), events=[])
except UnsweptRowsError as exc:
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.py
index 764a713f5380..dfe76ff71895 100644
--- a/posthog/dags/deletes.py
+++ b/posthog/dags/deletes.py
@@ -39,6 +39,7 @@ from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.deletion_targets import (
COVERAGE_DOC,
DEFAULT_DELETION_TARGETS,
+ EVENTS_TARGETS,
PERSONAL_DATA_TARGETS,
DeletionTarget,
_any_node_has,
@@ -46,8 +47,6 @@ from posthog.models.deletion_targets import (
surviving_rows_sql,
sweep_clusters,
)
-from posthog.models.event.deletion import events_data_tables
-from posthog.models.event.sql import EVENTS_DATA_TABLE
from posthog.models.group.sql import GROUPS_TABLE
from posthog.models.person.sql import (
PERSON_DISTINCT_ID2_TABLE,
@@ -104,9 +103,6 @@ class DeleteConfig(dagster.Config):
class SweepTargetsConfig(dagster.Config):
- # sharded_events_json is skipped until the events cluster is reliably reachable from the sweep.
- # A run that resolves it inconsistently can report an erasure without mutating its rows. Add it
- # to DEFAULT_DELETION_TARGETS to sweep and verify it again, or pass [] for one run.
skip_targets: list[str] = pydantic.Field(
default_factory=lambda: [
target.data_table for target in PERSONAL_DATA_TARGETS if target not in DEFAULT_DELETION_TARGETS
@@ -117,7 +113,7 @@ class SweepTargetsConfig(dagster.Config):
"addressed at all. Its rows stay readable while the requests covering them are still "
"marked verified, so only skip a target whose rows you accept leaving in place. An "
"unrecognised name fails the run rather than silently sweeping every target. Defaults to "
- '["sharded_events_json"]; pass [] to sweep every registered target.',
+ "the targets outside DEFAULT_DELETION_TARGETS; pass [] to sweep every registered target.",
)
@@ -702,6 +698,7 @@ def delete_events(
load_and_verify_deletes_dictionary, load_and_verify_adhoc_event_deletes_dictionary
),
reuse_since=reuse_floor,
+ patch_parts=placement.target.uses_patch_parts,
),
)
for placement in placements
@@ -1254,22 +1251,24 @@ def find_partitions_to_cleanup(
cluster: dagster.ResourceParam[ClickhouseCluster],
) -> list[int]:
"""Find partitions that contain old events for the specified teams."""
- query = f"""
- SELECT toYYYYMM(timestamp) as partition, count(1) as rows
- FROM {EVENTS_DATA_TABLE()}
- WHERE team_id IN %(team_ids)s
- AND age('month', timestamp, now()) >= %(min_age_months)s
- GROUP BY partition
- ORDER BY partition DESC
- """
-
parameters = {
"team_ids": config.team_ids,
"min_age_months": config.min_age_months,
}
- results = cluster.any_host_by_role(Query(query, parameters=parameters), NodeRole.DATA).result()
- partitions = [partition for partition, _rows in results]
+ # Each events table is read on every shard of its own cluster: a month can hold old rows in one
+ # table or shard and none in the others, and the cleanup only visits the months found here.
+ found: set[int] = set()
+ for placement in resolve_placements(cluster, EVENTS_TARGETS):
+ query = f"""
+ SELECT DISTINCT toYYYYMM(timestamp) as partition
+ FROM {placement.target.data_table}
+ WHERE team_id IN %(team_ids)s
+ AND age('month', timestamp, now()) >= %(min_age_months)s
+ """
+ results = placement.cluster.map_one_host_per_shard(Query(query, parameters=parameters)).result()
+ found.update(partition for rows in results.values() for (partition,) in rows)
+ partitions = sorted(found, reverse=True)
context.add_output_metadata(
{
@@ -1300,14 +1299,14 @@ def cleanup_old_events_by_partition(
#
# Events only, deliberately: this enforces a multi-year retention floor for a named set of
# teams, and every other personal-data table already expires sooner under its own TTL.
- event_tables = events_data_tables(cluster)
+ placements = resolve_placements(cluster, EVENTS_TARGETS)
for idx, partition in enumerate(partitions, 1):
context.log.info(f"Processing partition {partition} ({idx}/{total_partitions})")
- for table in event_tables:
+ for placement in placements:
delete_mutation_runner = LightweightDeleteMutationRunner(
- table=table,
+ table=placement.target.data_table,
predicate="""
team_id IN %(team_ids)s
AND age('month', timestamp, now()) >= %(min_age_months)s
@@ -1318,13 +1317,14 @@ def cleanup_old_events_by_partition(
},
partition=str(partition),
settings={"lightweight_deletes_sync": 0},
+ patch_parts=placement.target.uses_patch_parts,
)
# Run on one host per shard
- shard_mutations = cluster.map_one_host_per_shard(delete_mutation_runner).result()
+ shard_mutations = placement.cluster.map_one_host_per_shard(delete_mutation_runner).result()
# Wait for all mutations to complete
- _ = cluster.map_all_hosts_in_shards(
+ _ = placement.cluster.map_all_hosts_in_shards(
{
host.shard_num: mutation.wait
for host, mutation in shard_mutations.items()
diff --git a/posthog/dags/person_overrides.py b/posthog/dags/person_overrides.py
index 48a3965a7465..26c23ee3f32f 100644
--- a/posthog/dags/person_overrides.py
+++ b/posthog/dags/person_overrides.py
@@ -286,6 +286,7 @@ def run_person_id_update_mutations(
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)
+ runner.patch_parts = placement.target.uses_patch_parts
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
diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.py
index 9d88e65b5e9c..c0dcacb67d4f 100644
--- a/posthog/dags/tests/test_data_deletion_requests.py
+++ b/posthog/dags/tests/test_data_deletion_requests.py
@@ -31,9 +31,11 @@ from posthog.dags.data_deletion_requests import (
PersonRemovalContext,
PropertyRemovalTarget,
_cleaned_select_list,
+ _presence_params,
_property_removal_where,
_refuse_property_removal_unsweepable,
_ShardStaging,
+ _target_presence_clause,
auto_approve_deletion_requests_job,
auto_approve_deletion_requests_schedule,
cleanup_property_removal_staging,
@@ -3021,6 +3023,37 @@ def test_native_property_removal_gate_checks_retained_copies(
_refuse_property_removal_unsweepable(cluster, [EVENTS_JSON], request, marker)
+ "properties,person_properties,stored_properties,present",
+ [
+ ([], ["email"], '{"$unparseable_properties":"malformed $set email"}', True),
+ ([], ["email"], '{"other":"value"}', False),
+ ],
+)
+def test_json_target_presence_clause_sees_quarantine_on_person_only_requests(
+ properties: list[str], person_properties: list[str], stored_properties: str, present: bool
+) -> None:
+ # A copy that kept quarantined raw properties would pass this check and be reinserted past the
+ # marker, where the final verification no longer looks.
+ request = _property_removal_ctx(properties=properties, person_properties=person_properties)
+ target = PropertyRemovalTarget(table=EVENTS_JSON.data_table, shard=1, json_schema=True)
+ clause = _target_presence_clause(request, target, [])
+ [[matched]] = sync_execute(
+ f"""WITH rows AS (
+ SELECT CAST(%(properties)s, %(event_type)s) AS properties,
+ CAST('{{}}', %(person_type)s) AS person_properties,
+ CAST('{{}}', 'JSON(max_dynamic_paths=32)') AS temporary_properties
+ ) SELECT countIf({clause}) FROM rows""",
+ {
+ **_presence_params(request),
+ "properties": stored_properties,
+ "event_type": EVENTS_PROPERTIES_JSON_TYPE(),
+ "person_type": PERSON_PROPERTIES_JSON_TYPE(),
+ },
+ )
+ assert bool(matched) is present
+
+
def test_property_removal_where_scopes_to_events_by_default():
sql, params = _property_removal_where(_property_removal_ctx())
assert "AND event IN %(events)s" in sql
diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.py
index 408903a3cc50..5e97e132359f 100644
--- a/posthog/dags/tests/test_deletes.py
+++ b/posthog/dags/tests/test_deletes.py
@@ -1225,11 +1225,10 @@ def test_skip_targets_drops_a_target_named_by_either_of_its_tables(skip_targets,
assert resolve_sweep_targets(context) == expected
-def test_events_json_is_skipped_by_default() -> None:
- # The events cluster is not reliably reachable from the sweep, and a run that resolves it
- # inconsistently reports an erasure it did not perform. Dropping the default would resume that
- # sweep silently, because nothing else in a run says which targets it was supposed to reach.
- expected = ["sharded_events", "sharded_flag_evaluations"]
+def test_events_json_is_swept_by_default() -> None:
+ # Skipping a target by default leaves its rows in place while the requests covering them are
+ # marked verified, and nothing else in a run says which targets it was supposed to reach.
+ expected = ["sharded_events", "sharded_events_json", "sharded_flag_evaluations"]
assert resolve_sweep_targets(build_op_context()) == expected
assert [target.data_table for target in DEFAULT_DELETION_TARGETS] == expected
diff --git a/posthog/dags/tests/test_person_overrides.py b/posthog/dags/tests/test_person_overrides.py
index 7566b5948a12..9994e5e21bb1 100644
--- a/posthog/dags/tests/test_person_overrides.py
+++ b/posthog/dags/tests/test_person_overrides.py
@@ -27,8 +27,8 @@ from posthog.dags.person_overrides import (
)
from posthog.dags.tests.conftest import insert_flag_evaluations
from posthog.models.async_deletion import AsyncDeletion, DeletionType
-from posthog.models.deletion_targets import EVENTS, FLAG_EVALUATIONS, TargetPlacement
-from posthog.models.event.sql import EVENTS_DATA_TABLE
+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_TABLE
@@ -279,11 +279,13 @@ def test_run_person_id_update_mutations_rewrites_each_target_on_its_own_cluster(
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()},
}
@@ -302,23 +304,29 @@ def test_run_person_id_update_mutations_rewrites_each_target_on_its_own_cluster(
run_person_id_update_mutations(cluster, dictionary)
# This assertion names the targets literally instead of reusing SQUASH_TARGETS. That constant
- # would still match after someone adds sharded_events_json back to it, which would send the
- # squash to the events cluster.
- resolve_placements.assert_called_once_with(cluster, (EVENTS, FLAG_EVALUATIONS))
+ # would still match after someone drops a target from it.
+ 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,
}
+ assert {enqueue.args[0].table: enqueue.args[0].patch_parts for enqueue in enqueue_on_shards.call_args_list} == {
+ EVENTS_DATA_TABLE(): False,
+ EVENTS_JSON_DATA_TABLE: True,
+ FLAG_EVALUATIONS_DATA_TABLE: False,
+ }
# 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"] * 2 + ["wait"] * 2
+ assert [name for name, *_ in calls.mock_calls] == ["enqueue"] * 3 + ["wait"] * 3
cluster.any_host(dictionary.source.drop).result()
diff --git a/posthog/models/deletion_targets.py b/posthog/models/deletion_targets.py
index c144a038167e..9f52c4642cea 100644
--- a/posthog/models/deletion_targets.py
+++ b/posthog/models/deletion_targets.py
@@ -128,6 +128,9 @@ class DeletionTarget:
# The event names this table can hold, None meaning unconstrained. Lets a request naming other
# events skip this table without querying it.
stored_events: frozenset[str] | None = None
+ # Deletes and person_id rewrites on this table write patch parts instead of mutations; see
+ # MutationRunner.patch_parts.
+ uses_patch_parts: bool = False
def __post_init__(self) -> None:
if self.accepts_property_rewrite and not self.stores_person_properties:
@@ -188,9 +191,11 @@ 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.
+ accepts_property_rewrite=True,
+ accepts_person_id_rewrite=True,
# Dual-written from the same events, so its uuids are the legacy table's.
queue_uuid_candidates=False,
+ uses_patch_parts=True,
)
# Flag-evaluation telemetry carries the same person_id and group payload as events, so team and
@@ -211,12 +216,9 @@ FLAG_EVALUATIONS = DeletionTarget(
EVENTS_TARGETS: tuple[DeletionTarget, ...] = (EVENTS, EVENTS_JSON)
PERSONAL_DATA_TARGETS: tuple[DeletionTarget, ...] = (*EVENTS_TARGETS, FLAG_EVALUATIONS)
-# sharded_events_json stays registered because deletion support will return when the events cluster
-# is reliably reachable. Keeping the default sweep targets separate makes every verifier follow the
-# same temporary exclusion as deletes_job.
-DEFAULT_DELETION_TARGETS: tuple[DeletionTarget, ...] = tuple(
- target for target in PERSONAL_DATA_TARGETS if target is not EVENTS_JSON
-)
+# The targets deletes_job sweeps and deletion requests verify by default. Leaving a target out
+# keeps it registered while its rows stay in place; see COVERAGE_DOC.
+DEFAULT_DELETION_TARGETS: tuple[DeletionTarget, ...] = PERSONAL_DATA_TARGETS
# 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.
@@ -227,12 +229,7 @@ SQUASH_TARGETS: tuple[DeletionTarget, ...] = tuple(
# 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})
+PERSON_ID_REWRITE_EXEMPT: frozenset[str] = frozenset()
# 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.