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): route sharded ALTER on satellite clusters via any_ho… (#58175)

Bryan Ciaraldi96d0f9c970b4
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.py
index 18bbf28c03e4..e41698171c4f 100644
--- a/posthog/clickhouse/client/connection.py
+++ b/posthog/clickhouse/client/connection.py
@@ -40,6 +40,16 @@ class NodeRole(StrEnum):
SESSIONS = "sessions"
+# Roles that host replicated MergeTree data; valid ALTER TABLE targets.
+DATA_NODE_ROLES: frozenset[NodeRole] = frozenset(
+ {NodeRole.DATA, NodeRole.AI_EVENTS, NodeRole.AUX, NodeRole.OPS, NodeRole.SESSIONS}
+)
+# Single-shard data clusters: ALTER runs on one host, replication propagates.
+SINGLE_SHARD_DATA_NODE_ROLES: frozenset[NodeRole] = frozenset(
+ {NodeRole.AI_EVENTS, NodeRole.AUX, NodeRole.OPS, NodeRole.SESSIONS}
+)
+
+
_default_workload = Workload.ONLINE
diff --git a/posthog/clickhouse/client/migration_tools.py b/posthog/clickhouse/client/migration_tools.py
index 9e25e1670c93..df6b4095997b 100644
--- a/posthog/clickhouse/client/migration_tools.py
+++ b/posthog/clickhouse/client/migration_tools.py
@@ -5,7 +5,7 @@ from typing import Optional
from infi.clickhouse_orm import migrations
from posthog import settings
-from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.connection import DATA_NODE_ROLES, SINGLE_SHARD_DATA_NODE_ROLES, NodeRole
from posthog.clickhouse.cluster import ClickhouseCluster, Query, get_cluster
from posthog.settings.data_stores import (
CLICKHOUSE_CLUSTER,
@@ -83,9 +83,17 @@ def run_sql_with_exceptions(
query = Query(sql)
if sharded and is_alter_on_replicated_table:
- assert (NodeRole.DATA in node_roles_list and len(node_roles_list) == 1) or (
- settings.E2E_TESTING or settings.DEBUG or not settings.CLOUD_DEPLOYMENT
- ), "When running migrations on sharded tables, the node_role must be NodeRole.DATA"
+ is_local_or_test = settings.E2E_TESTING or settings.DEBUG or not settings.CLOUD_DEPLOYMENT
+ single_role = node_roles_list[0] if len(node_roles_list) == 1 else None
+ assert is_local_or_test or (single_role is not None and single_role in DATA_NODE_ROLES), (
+ "When running migrations on sharded tables, node_roles must be exactly one of "
+ f"{sorted(r.name for r in DATA_NODE_ROLES)}"
+ )
+ # Satellite clusters are single-shard and live in __extra_hosts, which
+ # map_one_host_per_shard cannot reach; any_host_by_roles can.
+ if not is_local_or_test and single_role in SINGLE_SHARD_DATA_NODE_ROLES:
+ logger.info(" Running ALTER on sharded replicated table on one host of role %s", single_role)
+ return cluster.any_host_by_roles(query, node_roles=node_roles_list).result()
return cluster.map_one_host_per_shard(query).result()
elif is_alter_on_replicated_table:
logger.info(" Running ALTER on replicated table on just one host")
diff --git a/posthog/clickhouse/test/test_alter_replicated_validation.py b/posthog/clickhouse/test/test_alter_replicated_validation.py
index 099097e5fd3d..b7e6e35e4305 100644
--- a/posthog/clickhouse/test/test_alter_replicated_validation.py
+++ b/posthog/clickhouse/test/test_alter_replicated_validation.py
@@ -1,6 +1,9 @@
import unittest
+from unittest import mock
-from posthog.clickhouse.client.connection import NodeRole
+from parameterized import parameterized
+
+from posthog.clickhouse.client.connection import DATA_NODE_ROLES, SINGLE_SHARD_DATA_NODE_ROLES, NodeRole
from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
@@ -54,3 +57,77 @@ class TestAlterReplicatedValidation(unittest.TestCase):
self.assertEqual(operation._sharded, True)
self.assertEqual(operation._is_alter_on_replicated_table, False)
+
+
+def _build_cluster_mock() -> mock.MagicMock:
+ cluster = mock.MagicMock()
+ for method in ("map_one_host_per_shard", "any_host_by_roles", "map_hosts_by_roles"):
+ getattr(cluster, method).return_value.result.return_value = None
+ return cluster
+
+
+class TestShardedAlterRouting(unittest.TestCase):
+ def _exec_with_cloud(self, node_roles: list[NodeRole], cluster: mock.MagicMock) -> None:
+ with (
+ mock.patch("posthog.clickhouse.client.migration_tools.settings.E2E_TESTING", False),
+ mock.patch("posthog.clickhouse.client.migration_tools.settings.DEBUG", False),
+ mock.patch("posthog.clickhouse.client.migration_tools.settings.CLOUD_DEPLOYMENT", "US"),
+ mock.patch(
+ "posthog.clickhouse.client.migration_tools.get_migrations_cluster",
+ return_value=cluster,
+ ),
+ ):
+ operation = run_sql_with_exceptions(
+ sql="ALTER TABLE sharded_x ADD COLUMN y String",
+ node_roles=node_roles,
+ sharded=True,
+ is_alter_on_replicated_table=True,
+ )
+ operation._func(None)
+
+ def test_data_role_uses_map_one_host_per_shard(self):
+ cluster = _build_cluster_mock()
+ self._exec_with_cloud([NodeRole.DATA], cluster)
+ cluster.map_one_host_per_shard.assert_called_once()
+ cluster.any_host_by_roles.assert_not_called()
+
+ @parameterized.expand([(role.name, role) for role in sorted(SINGLE_SHARD_DATA_NODE_ROLES, key=lambda r: r.name)])
+ def test_satellite_role_uses_any_host_by_roles(self, _name: str, role: NodeRole):
+ cluster = _build_cluster_mock()
+ self._exec_with_cloud([role], cluster)
+ cluster.any_host_by_roles.assert_called_once()
+ _args, kwargs = cluster.any_host_by_roles.call_args
+ self.assertEqual(kwargs["node_roles"], [role])
+ cluster.map_one_host_per_shard.assert_not_called()
+
+ def test_non_data_bearing_role_rejected(self):
+ cluster = _build_cluster_mock()
+ with self.assertRaises(AssertionError):
+ self._exec_with_cloud([NodeRole.INGESTION_SMALL], cluster)
+ cluster.any_host_by_roles.assert_not_called()
+ cluster.map_one_host_per_shard.assert_not_called()
+
+ def test_local_or_test_falls_through_to_per_shard(self):
+ cluster = _build_cluster_mock()
+ with (
+ mock.patch("posthog.clickhouse.client.migration_tools.settings.DEBUG", True),
+ mock.patch(
+ "posthog.clickhouse.client.migration_tools.get_migrations_cluster",
+ return_value=cluster,
+ ),
+ ):
+ operation = run_sql_with_exceptions(
+ sql="ALTER TABLE sharded_x ADD COLUMN y String",
+ node_roles=[NodeRole.AUX],
+ sharded=True,
+ is_alter_on_replicated_table=True,
+ )
+ operation._func(None)
+ cluster.map_one_host_per_shard.assert_called_once()
+ cluster.any_host_by_roles.assert_not_called()
+
+ def test_data_node_roles_membership(self):
+ self.assertIn(NodeRole.DATA, DATA_NODE_ROLES)
+ for role in SINGLE_SHARD_DATA_NODE_ROLES:
+ self.assertIn(role, DATA_NODE_ROLES)
+ self.assertNotIn(NodeRole.DATA, SINGLE_SHARD_DATA_NODE_ROLES)
diff --git a/posthog/clickhouse/test/test_migrations.py b/posthog/clickhouse/test/test_migrations.py
index 468f4c5f79de..26d85f4ea60a 100644
--- a/posthog/clickhouse/test/test_migrations.py
+++ b/posthog/clickhouse/test/test_migrations.py
@@ -10,7 +10,7 @@ from unittest import TestCase, mock
from infi.clickhouse_orm.utils import import_submodules
-from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.connection import DATA_NODE_ROLES, NodeRole
# Migrations created before this validation existed are grandfathered.
MIN_CHECKED_MIGRATION_NUMBER = 150
@@ -18,17 +18,6 @@ MIGRATIONS_PACKAGE_NAME = "posthog.clickhouse.migrations"
# `operations` lists can be cloud-gated; re-evaluate them under each prod-shaped value plus
# the unset default so gated branches don't silently bypass the guard.
CLOUD_DEPLOYMENTS_TO_CHECK = ("", "US", "EU", "DEV")
-# Cluster roles that host actual replicated MergeTree data — i.e. where sharded data tables
-# and non-sharded replicated tables live. ALTER TABLE on those tables must target exactly
-# one of these roles, never an ingestion / coordinator / shuffler role. The main cluster's
-# data role is `DATA`; satellite clusters expose their own data role.
-DATA_BEARING_NODE_ROLES: set[NodeRole] = {
- NodeRole.DATA,
- NodeRole.AI_EVENTS,
- NodeRole.AUX,
- NodeRole.OPS,
- NodeRole.SESSIONS,
-}
class TestUniqueMigrationPrefixes(TestCase):
@@ -133,16 +122,16 @@ class TestUniqueMigrationPrefixes(TestCase):
errors.append("is_alter_on_replicated_table parameter must be explicitly specified for ALTER TABLE queries")
allowed_roles_label = "one of " + ", ".join(
- f"NodeRole.{r.name}" for r in sorted(DATA_BEARING_NODE_ROLES, key=lambda r: r.name)
+ f"NodeRole.{r.name}" for r in sorted(DATA_NODE_ROLES, key=lambda r: r.name)
)
- if sharded and (len(node_roles) != 1 or node_roles[0] not in DATA_BEARING_NODE_ROLES):
+ if sharded and (len(node_roles) != 1 or node_roles[0] not in DATA_NODE_ROLES):
errors.append(f"ALTER TABLE on sharded tables must have node_role={allowed_roles_label}")
if (
not sharded
and is_alter_on_replicated_table
- and (len(node_roles) != 1 or node_roles[0] not in DATA_BEARING_NODE_ROLES)
+ and (len(node_roles) != 1 or node_roles[0] not in DATA_NODE_ROLES)
):
errors.append(f"ALTER TABLE on non-sharded tables must have node_role={allowed_roles_label}")