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.

fix(clickhouse): bound the person_id squash on sharded_events_json (#114370)

Rory Shanks9d53ca6c1de4
diff --git a/posthog/dags/common/overrides_manager.py b/posthog/dags/common/overrides_manager.py
index c79ad73f987f..1bf151ab6315 100644
--- a/posthog/dags/common/overrides_manager.py
+++ b/posthog/dags/common/overrides_manager.py
@@ -151,21 +151,27 @@ class OverridesSnapshotDictionary(ABC, Generic[TOverridesSnapshotTable]):
return self.get_checksum(client)
- @property
@abstractmethod
- def update_commands(self):
+ def update_commands(self, partition_clause: str = "") -> set[str]:
raise NotImplementedError()
- def update_mutation_runner_for(self, table: str) -> AlterTableMutationRunner:
+ def update_mutation_runner_for(self, table: str, partition_id: str | None = None) -> AlterTableMutationRunner:
"""The rewrite this snapshot applies, aimed at one target's storage table.
A squash rewrites every table that stamps the overridden column, so the table is an
- argument rather than a property of the snapshot.
+ argument rather than a property of the snapshot. A partition_id limits the rewrite to that
+ one partition.
"""
+ if partition_id is None:
+ return AlterTableMutationRunner(
+ table=table,
+ commands=self.update_commands(),
+ parameters={"name": self.qualified_name},
+ )
return AlterTableMutationRunner(
table=table,
- commands=self.update_commands,
- parameters={"name": self.qualified_name},
+ commands=self.update_commands(" IN PARTITION ID %(partition_id)s"),
+ parameters={"name": self.qualified_name, "partition_id": partition_id},
)
@property
diff --git a/posthog/dags/person_overrides.py b/posthog/dags/person_overrides.py
index 26c23ee3f32f..71389a67701f 100644
--- a/posthog/dags/person_overrides.py
+++ b/posthog/dags/person_overrides.py
@@ -9,7 +9,7 @@ from clickhouse_driver import Client
from posthog import settings
from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds
-from posthog.clickhouse.cluster import ClickhouseCluster, MutationWaiter, wait_for_mutations_on_shards
+from posthog.clickhouse.cluster import ClickhouseCluster, MutationWaiter, Query, wait_for_mutations_on_shards
from posthog.dags.common import JobOwners
from posthog.dags.common.overrides_manager import OverridesSnapshotDictionary, OverridesSnapshotTable
from posthog.dags.common.staged_dictionary import (
@@ -18,7 +18,7 @@ from posthog.dags.common.staged_dictionary import (
load_and_verify_on_every_cluster,
)
from posthog.dataclasses import frozen
-from posthog.models.deletion_targets import SQUASH_TARGETS, resolve_placements, sweep_clusters
+from posthog.models.deletion_targets import SQUASH_TARGETS, TargetPlacement, resolve_placements, sweep_clusters
from posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE
@@ -132,10 +132,9 @@ class PersonOverridesSnapshotDictionary(OverridesSnapshotDictionary):
[[checksum]] = results
return checksum
- @property
- def update_commands(self):
+ def update_commands(self, partition_clause: str = "") -> set[str]:
return {
- "UPDATE person_id = dictGet(%(name)s, 'person_id', (team_id, distinct_id)) WHERE dictHas(%(name)s, (team_id, distinct_id))"
+ f"UPDATE person_id = dictGet(%(name)s, 'person_id', (team_id, distinct_id)){partition_clause} WHERE dictHas(%(name)s, (team_id, distinct_id)) AND person_id != dictGet(%(name)s, 'person_id', (team_id, distinct_id))"
}
@property
@@ -284,11 +283,24 @@ def run_person_id_update_mutations(
one are deleted in the very next op.
"""
enqueued: list[tuple[ClickhouseCluster, dict[int, MutationWaiter]]] = []
+ patch_part_placements: list[TargetPlacement] = []
for placement in resolve_placements(cluster, SQUASH_TARGETS):
+ if placement.target.uses_patch_parts:
+ patch_part_placements.append(placement)
+ continue
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)))
+ # A lightweight update whose WHERE cannot be pruned holds a block number open in every partition
+ # until it finishes, and writes each chunk as one patch part per partition it touches. One
+ # statement per partition keeps both to a single partition, so the other partitions keep merging.
+ # The patch part is written before enqueue_on_shards returns, so these run in series.
+ for placement in patch_part_placements:
+ for partition_id, shards in sorted(_shards_by_partition(placement).items()):
+ runner = dictionary.update_mutation_runner_for(placement.target.data_table, partition_id=partition_id)
+ runner.patch_parts = True
+ runner.enqueue_on_shards(placement.cluster, shards)
+
# Every mutation is already in flight, so these waits overlap and cost the longest rather than
# their sum. The capacity wait inside enqueue_on_shards is still per table and serial.
for handle, shard_mutations in enqueued:
@@ -296,6 +308,28 @@ def run_person_id_update_mutations(
return dictionary
+def _shards_by_partition(placement: TargetPlacement) -> dict[str, set[int]]:
+ """Every data partition of the target's table, mapped to the shards that hold it.
+
+ Every replica is read because a partition that one replica has not fetched yet still holds rows
+ that the squash must rewrite.
+ """
+ query = Query(
+ """
+ SELECT DISTINCT partition_id
+ FROM system.parts
+ WHERE database = %(database)s AND table = %(table)s AND active AND NOT startsWith(partition_id, 'patch-')
+ """,
+ {"database": settings.CLICKHOUSE_DATABASE, "table": placement.target.data_table},
+ )
+ shards_by_partition: dict[str, set[int]] = {}
+ for host, rows in placement.cluster.map_all_hosts(query).result().items():
+ assert host.shard_num is not None
+ for (partition_id,) in rows:
+ shards_by_partition.setdefault(partition_id, set()).add(host.shard_num)
+ return shards_by_partition
+
+
@dagster.op
def start_overrides_delete_mutations(
cluster: dagster.ResourceParam[ClickhouseCluster],
diff --git a/posthog/dags/tests/test_person_overrides.py b/posthog/dags/tests/test_person_overrides.py
index 9994e5e21bb1..bffea99449f7 100644
--- a/posthog/dags/tests/test_person_overrides.py
+++ b/posthog/dags/tests/test_person_overrides.py
@@ -11,7 +11,7 @@ from django.conf import settings as django_settings
import dagster
from clickhouse_driver import Client
-from posthog.clickhouse.cluster import AlterTableMutationRunner, ClickhouseCluster
+from posthog.clickhouse.cluster import AlterTableMutationRunner, ClickhouseCluster, Query
from posthog.dags.deletes import deletes_job
from posthog.dags.person_overrides import (
GetExistingDictionaryConfig,
@@ -277,6 +277,13 @@ def test_run_person_id_update_mutations_rewrites_each_target_on_its_own_cluster(
# passes when a target is dropped entirely.
dictionary = _create_snapshot_with(cluster, [(1, "a", UUID(int=7), 3)])
sibling = cluster.sibling(django_settings.CLICKHOUSE_SINGLE_SHARD_CLUSTER)
+ sibling.map_one_host_per_shard(Query(f"TRUNCATE TABLE {EVENTS_JSON_DATA_TABLE}")).result()
+ sibling.any_host(
+ Query(
+ f"INSERT INTO {EVENTS_JSON_DATA_TABLE} (uuid, team_id, event, distinct_id, timestamp) VALUES",
+ [(uuid_module.uuid4(), 1, "$pageview", "a", datetime(2025, month, 15)) for month in (1, 2)],
+ )
+ ).result()
placements = [
TargetPlacement(target=EVENTS, cluster=cluster),
TargetPlacement(target=EVENTS_JSON, cluster=sibling),
@@ -285,7 +292,7 @@ def test_run_person_id_update_mutations_rewrites_each_target_on_its_own_cluster(
calls = Mock()
enqueued = {
EVENTS_DATA_TABLE(): {0: Mock()},
- EVENTS_JSON_DATA_TABLE: {0: Mock()},
+ EVENTS_JSON_DATA_TABLE: {},
FLAG_EVALUATIONS_DATA_TABLE: {0: Mock()},
}
@@ -306,27 +313,34 @@ def test_run_person_id_update_mutations_rewrites_each_target_on_its_own_cluster(
# This assertion names the targets literally instead of reusing SQUASH_TARGETS. That constant
# 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,
- }
+ assert sorted(
+ (
+ enqueue.args[0].table,
+ enqueue.args[1] is sibling,
+ enqueue.args[0].patch_parts,
+ enqueue.args[0].parameters.get("partition_id"),
+ )
+ for enqueue in enqueue_on_shards.call_args_list
+ ) == sorted(
+ [
+ (EVENTS_DATA_TABLE(), False, False, None),
+ (FLAG_EVALUATIONS_DATA_TABLE, True, False, None),
+ # One statement per partition. A single statement over the whole table holds a block
+ # number open in every partition and stalls merges across the table until it finishes.
+ (EVENTS_JSON_DATA_TABLE, True, True, "202501"),
+ (EVENTS_JSON_DATA_TABLE, True, True, "202502"),
+ ]
+ )
# 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"] * 3 + ["wait"] * 3
+ assert [name for name, *_ in calls.mock_calls] == ["enqueue"] * 4 + ["wait"] * 2
cluster.any_host(dictionary.source.drop).result()