diff --git a/src/Analyzer/Resolve/resolveFunction.cpp b/src/Analyzer/Resolve/resolveFunction.cpp index bb3e74a48993..9961d7419d20 100644 --- a/src/Analyzer/Resolve/resolveFunction.cpp +++ b/src/Analyzer/Resolve/resolveFunction.cpp @@ -2775,8 +2775,12 @@ ProjectionNames QueryAnalyzer::resolveFunction(QueryTreeNodePtr & node, Identifi /// `randConstant(), randConstant()` shares. What separates two calls is their arguments, which /// the hash still covers: `randConstant(1)` and `randConstant(2)` keep their own values, and that /// is the documented way to ask for two different constants in one query. + /// + /// Server constants (`hostName`, `serverUUID`, ...) capture `Context::isDistributed` when built. + /// A local `UNION` branch and a later cluster branch must not share that instance. if (function && !function->isDeterministic() && !function->isStateful() - && function->isDeterministicInScopeOfQuery()) + && function->isDeterministicInScopeOfQuery() + && !function->isServerConstant()) { auto hash = function_node_ptr->getTreeHash({ .compare_aliases = false }); function_base_cache = &functions_cache[hash]; diff --git a/tests/queries/0_stateless/05294_union_hostname_with_cluster_function.reference b/tests/queries/0_stateless/05294_union_hostname_with_cluster_function.reference new file mode 100644 index 000000000000..8c8256f6afc5 --- /dev/null +++ b/tests/queries/0_stateless/05294_union_hostname_with_cluster_function.reference @@ -0,0 +1,2 @@ +1 1 1 +2 2 1 diff --git a/tests/queries/0_stateless/05294_union_hostname_with_cluster_function.sql b/tests/queries/0_stateless/05294_union_hostname_with_cluster_function.sql new file mode 100644 index 000000000000..b578f6ad5915 --- /dev/null +++ b/tests/queries/0_stateless/05294_union_hostname_with_cluster_function.sql @@ -0,0 +1,15 @@ +-- A local GROUP BY hostName() must not be reused for a later cluster branch. +-- hostName() is folded on the local branch and must stay a per-shard column on the cluster branch. + +SELECT tag, c, h = hostName() +FROM +( + SELECT hostName() AS h, count() AS c, 1 AS tag + FROM numbers(1) + GROUP BY h + UNION ALL + SELECT hostName() AS h, count() AS c, 2 AS tag + FROM cluster('test_cluster_two_shards', system.one) + GROUP BY h +) +ORDER BY tag;