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): fail required migrations without target hosts (#91548)

Hugues Pouillotfffac77218b6
diff --git a/posthog/clickhouse/client/migration_tools.py b/posthog/clickhouse/client/migration_tools.py
index 4a0c0373ef3b..8a206aa0dabf 100644
--- a/posthog/clickhouse/client/migration_tools.py
+++ b/posthog/clickhouse/client/migration_tools.py
@@ -37,6 +37,7 @@ def run_sql_with_exceptions(
node_roles: list[NodeRole] | NodeRole | None = None,
sharded: Optional[bool] = None,
is_alter_on_replicated_table: Optional[bool] = None,
+ require_hosts: bool = False,
):
"""
Executes a SQL query on each node separately with specific options, handling distributed execution and node roles.
@@ -57,6 +58,8 @@ def run_sql_with_exceptions(
is_alter_on_replicated_table: bool, optional (default is False)
Specifies whether the query is an ALTER statement executed on replicated tables.
This will run on just one host per shard or one host for the whole cluster if there is no sharding.
+ require_hosts: bool, optional (default is False)
+ Raises when none of the requested node roles exist in the migration topology.
Returns:
migrations.RunPython
@@ -106,7 +109,7 @@ def run_sql_with_exceptions(
logger.info(" Running ALTER on replicated table on just one host")
return cluster.any_host_by_roles(query, node_roles=node_roles_list).result()
else:
- return cluster.map_hosts_by_roles(query, node_roles=node_roles_list).result()
+ return cluster.map_hosts_by_roles(query, node_roles=node_roles_list, require_hosts=require_hosts).result()
operation = migrations.RunPython(lambda _: run_migration())
@@ -119,5 +122,6 @@ def run_sql_with_exceptions(
operation._effective_node_roles = node_roles_list
operation._sharded = sharded
operation._is_alter_on_replicated_table = is_alter_on_replicated_table
+ operation._require_hosts = require_hosts
return operation
diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.py
index 991be9d83693..4a74d9015bb6 100644
--- a/posthog/clickhouse/cluster.py
+++ b/posthog/clickhouse/cluster.py
@@ -450,6 +450,8 @@ class ClickhouseCluster:
node_roles: list[NodeRole],
concurrency: int | None = None,
workload: Workload = Workload.DEFAULT,
+ *,
+ require_hosts: bool = False,
) -> FuturesMap[HostInfo, T]:
"""
Execute the callable once for each host in the cluster with the given node role.
@@ -457,13 +459,12 @@ class ClickhouseCluster:
The number of concurrent queries can limited with the ``concurrency`` parameter, or set to ``None`` to use the
default limit of the executor.
"""
+ hosts = self.__hosts_by_roles(self.__hosts, node_roles, workload)
+ if require_hosts and not hosts:
+ raise ValueError(f"No hosts found with roles {node_roles}")
+
with ThreadPoolExecutor(max_workers=concurrency) as executor:
- return FuturesMap(
- {
- host: executor.submit(self.__get_task_function(host, fn))
- for host in self.__hosts_by_roles(self.__hosts, node_roles, workload)
- }
- )
+ return FuturesMap({host: executor.submit(self.__get_task_function(host, fn)) for host in hosts})
def map_all_hosts_in_shard(
self, shard_num: int, fn: Callable[[Client], T], concurrency: int | None = None
diff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.py
index f36259131fb5..939fce63aaba 100644
--- a/posthog/clickhouse/test/test_cluster.py
+++ b/posthog/clickhouse/test/test_cluster.py
@@ -699,6 +699,31 @@ def test_map_hosts_with_combined_roles() -> None:
assert sorted(executed_hosts) == ["aux-host-1", "data-host-1", "data-host-2"]
+def test_map_hosts_with_missing_role_defaults_to_noop() -> None:
+ bootstrap_client_mock = Mock()
+ bootstrap_client_mock.execute = Mock(
+ return_value=[
+ ("data-host-1", "9000", "1", "1", "online", "data"),
+ ]
+ )
+ cluster = ClickhouseCluster(bootstrap_client_mock)
+
+ assert cluster.map_hosts_by_role(lambda _: (), node_role=NodeRole.INGESTION_SMALL).result() == {}
+
+
+def test_map_hosts_with_required_missing_role_raises() -> None:
+ bootstrap_client_mock = Mock()
+ bootstrap_client_mock.execute = Mock(
+ return_value=[
+ ("data-host-1", "9000", "1", "1", "online", "data"),
+ ]
+ )
+ cluster = ClickhouseCluster(bootstrap_client_mock)
+
+ with pytest.raises(ValueError, match="No hosts found with roles.*INGESTION_SMALL"):
+ cluster.map_hosts_by_roles(lambda _: (), node_roles=[NodeRole.INGESTION_SMALL], require_hosts=True)
+
+
def test_satellite_dedup_same_physical_host() -> None:
"""In local dev, satellite clusters point to the same ClickHouse node as the main cluster.
NodeRole.ALL should not execute on the same physical host twice."""