Repository navigation
Analyzer: exclude server-constant functions from shared function cache - #107775
josemimbre wants to merge 38 commits into
Conversation
ClickHouse#86967 moved the resolved-function cache from per-`IdentifierResolveScope` to per-`QueryAnalyzer`, deduplicating `FunctionBase` instances by the function node's tree hash so that non-deterministic calls like `randConstant` fold to the same constant within a query. `getSetting` and `rowNumberInAllBlocks` were excluded because they depend on scope-local state. Server-constant functions (`hostName`, `serverUUID`, `tcpPort`, `tcpPortSecure`, `timezone`, `serverTimezone`, `uptime`, `version`, `revision`, `getMacro`, `getScalar`, ...) suffer from the same problem. Their `FunctionBase` captures `context->isDistributed` at construction time via `FunctionConstantBase`, and that boolean gates `isSuitableForConstantFolding`. Reusing a `FunctionBase` built in one scope for a sibling scope with a different `is_distributed` context lets the wrong scope decide whether to fold the call. The plan produced for the distributed shard then disagrees with the local plan header and `addConvertingActions` throws: Cannot find column `_CAST('<host>'_String, 'String'_String)` in source stream, there are only columns: [count()] The minimal repro needs a multi-replica cluster, the new analyzer, and an outer `UNION ALL` with `hostName` projected in both branches wrapping a sub-SELECT over `clusterAllReplicas` that groups by `hostName`: SELECT host, sum(x) AS x FROM (SELECT hostName() AS host, 0 AS x UNION ALL SELECT hostName() AS host, count() AS x FROM clusterAllReplicas('test_cluster_two_shards', system.one) GROUP BY host) GROUP BY host SETTINGS enable_analyzer = 1; With `prefer_localhost_replica = 0` the same defect surfaces on the remote side as `NOT_FOUND_COLUMN_IN_BLOCK` instead. Until now the workaround was to wrap each `hostName` call in `materialize` to suppress folding. Add `!function->isServerConstant()` to the cache-eligibility condition. `IFunctionOverloadResolver` already exposes `isServerConstant` via the adaptors in `IFunctionAdaptors.h`, so this is a free check that runs before `build` and keeps the cache for `randConstant`-style cases intact. Add a regression test in `tests/queries/0_stateless` covering the original `hostName` case, the same query with `prefer_localhost_replica = 0`, and an analogous `tcpPort` case so other server-constants are guarded too.
|
Workflow [PR], commit [3b68a9a] Summary: ❌
AI ReviewSummaryThis PR fixes a broad set of analyzer function-cache and distributed constant-folding regressions around server-local introspection functions, and most of the earlier review points are addressed. One blocker remains: Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 128/144 (88.89%) · Uncovered code |
…sion test
`getServerPort` does not inherit from `FunctionConstantBase`: its
`GetServerPortOverloadResolver` and `FunctionBaseGetServerPort` are written by
hand, both capture `context->isDistributed` (the base also gates
`isSuitableForConstantFolding` on it), but neither overrides
`isServerConstant`. With the previous patch in this PR the cache-eligibility
check uses `IFunctionOverloadResolver::isServerConstant`, so `getServerPort`
slipped through and could still share a `FunctionBase` built in a
non-distributed scope across a distributed sibling scope.
Add the override on both the resolver and the base for consistency, and
extend `04356_analyzer_hostname_union_distributed_cache.sql` with a
`getServerPort('tcp_port')` variant so any future regression where this
classification is lost is caught.
…cache exclusion Follow-up on the shared function-base cache exclusion. Two gaps remained. Redone in this commit: - Replaced the hard-coded name checks (`function_name != "getSetting" && function_name != "rowNumberInAllBlocks"`) in the cache predicate with the resolver property `isDeterministicInScopeOfQuery`. It expresses exactly the required condition (constant within a query scope, so safe to share) and, as a side effect, now also excludes `getSettingOrDefault`, which shares the `FunctionGetSetting` implementation with `getSetting` and was silently admitted by the old name list. `randConstant` and `now` remain cached. - Marked `transactionID`, `transactionLatestSnapshot` and `transactionOldestSnapshot` as `isServerConstant`. Their `FunctionBase` captures `context->isDistributed()` at construction via `FunctionConstantBase` exactly like `hostName`/`tcpPort`/`getServerPort`, so they follow the same distributed-folding rule and must not be shared across scopes. This reuses the existing `!isServerConstant()` exclusion instead of a new property. It does not change constant folding (still gated by `isSuitableForConstantFolding`), only the cache exclusion and GROUP-BY-key removal, which is correct for them. Added test `04357_get_setting_or_default_scope_cache` for `getSetting` and `getSettingOrDefault` in sibling subqueries with different `SETTINGS`. The transaction functions now ride the same path covered by `04356_analyzer_hostname_union_distributed_cache`.
Guards that the analyzer function-resolution cache does not collapse the distributed branch of a query to the initiator's value. Two identical `queryID` calls in the outer scope and an inner `clusterAllReplicas` scope share the same tree hash and therefore the cached `FunctionBase`; the inner distributed branch must still report its own per-shard ids. `queryID` does not gate `isSuitableForConstantFolding` on `is_distributed` and its folded value is non-deterministic, so it is re-evaluated per shard regardless of the cache. This test locks that contract down.
`currentQueryID` reads the same `client_info.current_query_id` as `queryID`, but its `executeImpl` returned a real `ColumnConst`, so the analyzer could fold it on the initiator of a distributed query and every shard received the initiator's query id. Return the value materialized via `convertToFullColumnIfConst`, mirroring `queryID`, and extend the distributed regression test with the analogous `currentQueryID` shapes. Verified against the PR's prebuilt CI binary: the new test queries return 0 (collapsed to the initiator id) without this change, while the `queryID` counterparts return 1.
…e folding
`getServerSetting` reads a server-local value (config or runtime limit), but it
inherited the default `isSuitableForConstantFolding` and did not report
`isServerConstant`. In a distributed query the initiator folded the call and
shipped its own live value as a literal to every shard, e.g.:
SELECT _CAST(22142671221, 'UInt64') AS `getServerSetting('max_server_memory_usage')` ...
even though each shard may legitimately have a different value. Capture
`context->isDistributed()` at build time and gate folding on it, and report
`isServerConstant` (which also excludes the function from the analyzer function
cache, since the built base now captures scope-local state) - the same pattern
as `getServerPort`.
The regression test checks via `system.query_log` that both shard queries still
contain the function call instead of a folded literal, and covers the
cross-scope `UNION ALL` + `clusterAllReplicas` cache shape. Verified against
the PR's prebuilt CI binary: the first check returns 0 (folded) without this
change.
…og check The shard-side entries in `system.query_log` do not run in the test database, so anchor them to the latest initial query with the test's `log_comment`, which does run in `currentDatabase()`. This satisfies the style check and also makes the count assertion stable when the test is re-run in the same database.
…side folding Same class of bug as `getServerSetting`: the function reads a server-local value (`Context::getMergeTreeSettings`, which also depends on the `compatibility` setting), always returns a `ColumnConst`, and kept the default `isSuitableForConstantFolding`. In a distributed query the initiator folded the call and shipped its own merge tree setting value as a literal to every shard, even though shards may legitimately differ in config or compatibility. Capture `context->isDistributed()` at build time and gate folding on it, and report `isServerConstant` (which also excludes the function from the analyzer function cache) - the same pattern as `getServerSetting` and `getServerPort`. The regression test mirrors 04538: it checks via `system.query_log` that both shard queries still contain the function call instead of a folded literal, and covers the cross-scope `UNION ALL` + `clusterAllReplicas` cache shape. Verified against the PR's prebuilt CI binary: the first check returns 0 (folded) without this change.
…ide folding
Same class of bug as `getServerSetting`: `filesystemAvailable`,
`filesystemCapacity` and `filesystemUnreserved` (all served by
`FilesystemImpl`) read server-local disk state, return a `ColumnConst` in the
zero-argument form, and kept the default `isSuitableForConstantFolding`. In a
distributed query the initiator folded the calls and shipped its own free-space
numbers as literals to every shard, e.g.:
SELECT _CAST(321443934208, 'UInt64') AS `filesystemAvailable()`, ...
so every shard reported the initiator's filesystem state instead of its own.
The constant `disk_name` form folded the same way through
`useDefaultImplementationForConstants`.
Capture `context->isDistributed()` at build time and gate folding on it, and
report `isServerConstant` (which also excludes the functions from the analyzer
function cache) - the same pattern as `getServerSetting` and `getServerPort`.
The regression test mirrors 04538: it checks via `system.query_log` that both
shard queries still contain the zero-argument calls instead of folded literals,
and covers the cross-scope `UNION ALL` + `clusterAllReplicas` cache shape
(asserting only the row total, since free space is volatile). Verified against
the PR's prebuilt CI binary: the first check returns 0 (folded) without this
change.
The non-folded query shipped to shards is `SELECT filesystemAvailable() AS \`filesystemAvailable()\`, ...` - every expression carries an alias, so the previous comma-separated pattern `SELECT filesystemAvailable(), filesystemCapacity(), ...` never matched and the check returned 0 even with the fix in place: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107775&sha=ba5e72d097d5bb9fd5b1d92b5f464a802b288b95&name_0=PR&name_1=Fast%20test Match the first call as a prefix and require that no `_CAST(` literal replaced any of the three calls. Verified both directions: the folded (pre-fix) shard query still fails the check, and the aliased non-folded shape (confirmed with a multi-column `getServerPort` query, which already does not fold) passes it.
`connectionId` reads `client_info.connection_id`, which is not propagated to
secondary queries (`ClientInfo::write` does not serialize it), so each shard of
a distributed query observes its own value. But `executeImpl` returned a real
`ColumnConst`, so the analyzer folded the call on the initiator and shipped the
initiator's frontend connection id (set by the MySQL/PostgreSQL handlers) to
every shard:
SELECT _CAST(0, 'UInt64') AS `connectionId()` ...
Return the value materialized via `convertToFullColumnIfConst`, mirroring
`queryID` and `currentQueryID`.
The regression test checks via `system.query_log` that both shard queries still
contain the function call instead of a folded literal (the values cannot be
compared, since every native-protocol connection observes 0), and covers the
outer/inner `UNION ALL` + `clusterAllReplicas` shape. Verified against the PR's
prebuilt CI binary: the first check returns 0 (folded) without this change.
…ServerConstant` and block initiator-side folding
Same class of bug as `getServerSetting`: both functions inspect server-local
metadata (`computeMaxTableNameLength` over the local database path,
`DatabaseCatalog` for the local catalog), return a `ColumnConst` and kept the
default `isSuitableForConstantFolding`. In a distributed query the initiator
folded the calls and shipped its own filesystem or catalog state as literals to
every shard, e.g.:
SELECT _CAST(1, 'UInt8') AS `hasColumnInTable('system', 'one', 'dummy')` ...
Capture `context->isDistributed()` at build time and gate folding on it, and
report `isServerConstant` - the same pattern as `getServerSetting`.
`getMaxTableNameLengthForDatabase` also gets `isDeterministic` = false, which it
was missing despite reading mutable global state.
The regression test mirrors 04538: it checks via `system.query_log` that the
shard queries still contain the function calls instead of folded literals.
Verified against the PR's prebuilt CI binary: both checks return 0 (folded)
without this change.
`tid` returns the id of the thread processing the current block, which varies between blocks of one query, but it kept the default `isDeterministic` / `isDeterministicInScopeOfQuery` (both true) and the default `isSuitableForConstantFolding`. The analyzer therefore folded `SELECT tid()` into a single literal captured from the analysis thread, breaking the documented contract, and later optimizers were free to treat the function as deterministic. Report both determinism flags as false and opt out of constant folding. The per-block `ColumnConst` result is kept: constness within one block matches the documented semantics. The regression test checks via `EXPLAIN QUERY TREE` that the resolved projection keeps the `tid` function node instead of replacing it with a constant. Verified against the PR's prebuilt CI binary: the first check returns 0 (folded into a `CONSTANT` node) without this change.
`authenticatedUser` captures `client_info.authenticated_user` at build time, which is not propagated to secondary queries (`ClientInfo::write` does not serialize it), so each shard of a distributed query observes its own authentication identity. But `executeImpl` returned a real `ColumnConst`, so the analyzer folded the call on the initiator and shipped the initiator's authenticated user as a literal to every shard. Return the value materialized via `convertToFullColumnIfConst`, mirroring `queryID`, `currentQueryID` and `connectionId`. The regression test mirrors 04541: it checks via `system.query_log` that both shard queries still contain the function call instead of a folded literal. Verified against the PR's prebuilt CI binary: the check returns 0 (folded) without this change.
…zzer` `getFuzzerData` (available only in `USE_FUZZING_MODE` builds) reads the process-local static `fuzz_data` and returned a real `ColumnConst` with the default constant-folding behavior, so a distributed query on a fuzzing build would fold the call on the initiator and ship that node's fuzz payload to every shard. Return the value materialized via `convertToFullColumnIfConst`, the same treatment as `hasThreadFuzzer`. No regression test: the function does not exist outside `USE_FUZZING_MODE` builds, and no CI test job builds with fuzzing mode, so a stateless test would fail everywhere with `UNKNOWN_FUNCTION`. The change was syntax-checked with the `USE_FUZZING_MODE` guard forced on.
…zer-hostname-function-cache
`localtime` is a constant expression evaluated once on the initiator at query analysis time, in the initiator's session/server time zone - the SQL-standard `LOCALTIME`, documented as equivalent to `CAST(now() AS Time)`, which folds on the initiator the same way. Unlike the server-local introspection functions handled in this PR (`timezone`, `getServerSetting`, ...), it must keep folding in distributed scope and must stay in the analyzer's shared function cache: the cache is what guarantees that syntactically identical calls fold to the same constant within one query. The test pins all three aspects: the resolved projection is a constant, the distributed query ships the folded literal to the shards, and `localtime() = localtime()` holds. It guards against "fixing" the function into the per-shard class, which would break its documented contract and its equivalence with `CAST(now() AS Time)`.
…zer-hostname-function-cache # Conflicts: # src/Functions/connectionId.cpp # src/Functions/getClientHTTPHeader.cpp
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 98/110 (89.09%) · Uncovered code |
Making the result a full column was wrong: `authenticated_user` is never populated on secondary queries - `Session::authenticate` stores it only in `prepared_client_info`, `Session::makeQueryContextImpl` copies only `current_user`/`current_address` into the query context, and `ClientInfo::write` does not serialize the field at all. So shipping the call unfolded made every remote shard return an empty string instead of a meaningful identity. Keep the result a constant so the initiator folds its own authenticated user - the session identity, the only meaningful value - into the shipped query, until the field is propagated to secondary queries. Repurpose 04544 to pin the folded shape of the shipped shard queries and document why folding is deliberate here.
Build profile diff (arm_release)No arm_release build profile data for commit 3b68a9a - the build was skipped, reused from cache, or predates profile upload. |
Blocking the folding broke the distributed-user contract: `currentUser` reports the propagated `initial_user` on every shard, so a query like `SELECT currentUser(), defaultRoles() FROM clusterAllReplicas(...)` paired the initiator's identity with the shard account's default roles. Without a cluster secret the shard runs the secondary query as a different user (see `ClusterProxy::updateSettingsAndClientInfoForCluster`), and even with a secret only `current_roles` are propagated - settings profiles never are - so shard-side execution cannot report the initiator's access state. Keep the results constant so the initiator folds its own role/profile state into the shipped query, consistent with `currentUser` and `authenticatedUser`, until the full state is propagated to secondary queries. Repurpose 04612 to pin the folded shape of the shipped shard queries and the value-level consistency between an outer local scope and an inner clusterAllReplicas scope.
…ions State explicitly in the structured `FunctionDocumentation` of `authenticatedUser`, `currentRoles`/`enabledRoles`/`defaultRoles` and `currentProfiles`/`enabledProfiles`/`defaultProfiles` that in a distributed query they are evaluated on the initiator, because the underlying state is not propagated to secondary queries. Add a value-level regression to 04544: every shard must observe the initiator's authenticated user (equal to `currentUser` without `EXECUTE AS`), not an empty string.
…ng server constants Excluding every `isServerConstant` function from `functions_cache` fixed the cross-scope `is_distributed` leak but also removed the only per-query deduplication for repeated calls of server constants that change over time. `FunctionConstantBase` snapshots the value at build time, so identical calls such as `uptime` could resolve to different constants in the same query when analysis crosses a second boundary, violating the `isDeterministicInScopeOfQuery` contract and turning `SELECT uptime() = uptime()` into a timing-dependent result. Instead of dropping these functions from the cache, include the scope's `isDistributed` flag in the cache key - the only scope-local state a server-constant base captures. Scopes that disagree on it (the inner `clusterAllReplicas` sub-SELECT versus the outer query) never share a base, which keeps the original header-mismatch fix, while identical calls in scopes that agree keep deduplicating to a single constant. Add 04669 pinning that identical `uptime` calls compare equal within one query, including across sibling subquery scopes.
|
|
||
| static FunctionPtr create(ContextPtr context_) { return std::make_shared<FunctionGetMergeTreeSetting>(context_); } | ||
| explicit FunctionGetMergeTreeSetting(ContextPtr context_) : WithContext(context_) {} | ||
| explicit FunctionGetMergeTreeSetting(ContextPtr context_) : WithContext(context_), is_distributed(context_->isDistributed()) {} |
There was a problem hiding this comment.
This still becomes cache-unsafe again after the latest functions_cache[{hash, scope.context->isDistributed()}] change in resolveFunction. The built object keeps the first scope's ContextPtr and later reads getContext()->getMergeTreeSettings() in getValue, but compatibility is a scope-local query setting and can change those defaults per sibling subquery.
So two identical calls like getMergeTreeSetting(...) in the same isDistributed state can now share one FunctionBase even when the scopes have different SETTINGS compatibility, and the second branch will observe the first branch's compatibility-adjusted value. That reopens the same cross-scope SETTINGS leak that 04357 fixed for getSetting.
Please either keep this family out of the shared cache, or extend the cache key to include the extra scope-local state these server-constant functions capture. A focused sibling-subquery regression with different compatibility values would lock it down.
The `allow_get_client_http_header` permission is enforced only when the function is built for a scope. With the function cache keyed by tree hash and `isDistributed`, a scope with the setting disabled could reuse a `FunctionBase` built under an enabled sibling scope and read the header instead of throwing `FUNCTION_NOT_ALLOWED` - a permission bypass. Checking in `executeImpl` instead would not help: at execution time only the construction context is available, which is the scope that already passed the check. Mark the function `isDeterministicInScopeOfQuery() == false` - its behavior depends on the scope-local setting - so every scope builds and permission-checks its own function. Add a sibling-subquery regression with one branch enabled and one disabled, in both orders.
|
Why closed? |
…ibuted scopes The analyzer's `functions_cache` shares a built `FunctionBase` between syntactically identical calls of non-deterministic functions within a query. Server-constant functions (`hostName`, `tcpPort`, `serverUUID`, ...) capture `context->isDistributed()` when built, and it decides whether they are folded to a constant. When the outer query and a sub-SELECT over `clusterAllReplicas` shared one base, the shard query and the local plan disagreed on the header, failing with `THERE_IS_NO_COLUMN` (or `NOT_FOUND_COLUMN_IN_BLOCK` with `prefer_localhost_replica = 0`). Include the scope's `isDistributed` flag in the cache key. This is the minimal part of ClickHouse#107775. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Regression introduced by #86967, which moved the resolved-function cache to be
per-
QueryAnalyzerand keyed by the function node's tree hash, so thatnon-deterministic calls like
randConstantfold to the same constant withina query.
getSettingandrowNumberInAllBlockswere excluded by name becausethey depend on scope-local state.
Server-constant functions (
hostName,serverUUID,tcpPort,tcpPortSecure,timezone,serverTimezone,uptime,version,revision,getMacro,getScalar, ...) suffer from the same problem. TheirFunctionBasecapturescontext->isDistributedat construction viaFunctionConstantBase, and thatboolean gates
isSuitableForConstantFolding. Reusing aFunctionBasebuiltin one scope for a sibling scope with a different
is_distributedlets thewrong scope decide whether to fold the call. The plan produced for the
distributed shard then disagrees with the local plan header and
addConvertingActionsthrows:Minimal repro (needs a multi-replica cluster, the new analyzer, and an outer
UNION ALLwithhostNameprojected in both branches wrapping a sub-SELECTover
clusterAllReplicasthat groups byhostName):With
prefer_localhost_replica = 0the same defect surfaces on the remoteside as
NOT_FOUND_COLUMN_IN_BLOCKinstead. Reproduced on docker imagesclickhouse/clickhouse-server:25.6.13.41,25.7.8.71,25.8.24.21,26.3.12.3and on a local
masterbuild (v26.4.1.1). Bisected by docker image; theintroducer is the single shared backport across the
25.6.12.10 → 25.6.13.41and
25.7.7.68 → 25.7.8.71bumps that touches the analyzer:Backport #86967 to 25.6(#87637) /Backport #86967 to 25.7(#87638). Untilnow the workaround is to wrap each
hostNamecall inmaterializeto suppressfolding.
Related work that was on adjacent paths but did not cover this one: #66433
introduced
isServerConstantforGROUP BYconstant handling; #93286addressed the same symptom in
StorageMerge.What the change does
Analyzer cache boundary (
src/Analyzer/Resolve/resolveFunction.cpp).The hardcoded name list is replaced by a property that already carries
exactly this meaning, so the boundary no longer drifts as functions are
added: a
FunctionBaseis shared only when the function isisDeterministicInScopeOfQuery. Using the property instead of a name listalso picks up
getSettingOrDefault, which shares thegetSettingimplementation and was silently missing from the list. Because
server-constant bases capture
context->isDistributed()at construction(it gates
isSuitableForConstantFolding), the cache key now also includesthe scope's
isDistributedflag: scopes that disagree on it (the innerclusterAllReplicassub-SELECT versus the outer query) never share a base,which fixes the header mismatch, while identical calls in scopes that agree
still deduplicate - a time-dependent server constant such as
uptimesnapshots its value at build time, and
isDeterministicInScopeOfQuerypromises a single constant per query, so dropping the deduplication would
turn
SELECT uptime() = uptime()into a timing-dependent result.IFunctionOverloadResolveralready exposes the property through theadaptors in
IFunctionAdaptors.h, so this is a free check that runs beforebuildand keeps the cache forrandConstant-style cases intact.Functions whose resolution depends on scope-local query settings opt out of
the shared cache via
isDeterministicInScopeOfQuery() == false:getSetting/
getSettingOrDefault(already), and nowgetClientHTTPHeader, whoseallow_get_client_http_headerpermission check runs when the function isbuilt for a scope - sharing a base built under an enabled sibling scope with
a disabled one would be a permission bypass. (
getMergeTreeSettingwasaudited for the same risk and is safe to share:
Context::getMergeTreeSettingsis computed once per server from the default profile's
compatibilityandcached in the shared context, so a scope-local
compatibilitydoes notchange its result.)
isServerConstanton the functions that are server-local but did notadvertise it:
getServerPort(both overloads),getServerSetting,getMergeTreeSetting,getMaxTableNameLengthForDatabase,hasColumnInTable,getClientHTTPHeader,showCertificate,filesystemAvailable/filesystemCapacity/filesystemUnreserved, andthe transaction counters (
transactionID,transactionLatestSnapshot,transactionOldestSnapshot).No initiator-side folding for those functions. Each of them now gates
isSuitableForConstantFoldingon thecontext->isDistributed()captured atconstruction, so the initiator ships the call to the shards instead of
replacing it with a literal computed from its own state. Without this, a
query like
SELECT getServerSetting('max_server_memory_usage') FROM clusterAllReplicas(...)reports the initiator's value for every shard.Functions whose value is not propagated to secondary queries but is
meaningful shard-locally build a
ColumnConstdirectly inexecuteImpl,which the analyzer folds regardless of
isSuitableForConstantFolding.connectionId,currentQueryID,getFuzzerDataandhasThreadFuzzernowreturn a full column so each shard observes its own value, matching
queryID.tidreturns the id of the thread processing the current block, so itvaries between blocks of a single query. It is now marked
isDeterministicInScopeOfQuery() == falseand not foldable, instead ofbeing replaced during analysis by the analysis thread's id.
localtimewas checked and deliberately left folding on the initiator: it isthe SQL-standard
LOCALTIME, documented as equivalent toCAST(now() AS Time),so like
now()it must evaluate once on the initiator and ship the same literalto every shard.
04651_localtime_distributed_constantpins that behaviour.The session-identity family -
authenticatedUserand thecurrentRoles/enabledRoles/defaultRolesandcurrentProfiles/enabledProfiles/defaultProfilesfamilies - was also checked and deliberately left folding onthe initiator. None of that state is propagated to secondary queries
(
ClientInfoserializes onlyinitial_userand, with a cluster secret,current_roles;authenticated_userand the profile state are never sent),and without a secret the shard even runs the secondary query as a different
user. Executing these functions on the shards would return empty values
(
authenticatedUser) or paircurrentUser's initiator identity with theshard account's roles/profiles. So, consistent with
currentUser(whichreports the propagated
initial_usereverywhere), they keep returning theinitiator's values in distributed queries until that state gets a transport.
The structured documentation of these functions now states this contract
explicitly, and
04544/04612pin it at the query-shape and value level.Tests
Stateless regression tests covering the cache shape (identical calls in a local
outer scope and an inner
clusterAllReplicasscope) and the folding gate (theshipped shard query must still contain the call, not a
_CASTliteral):04356(hostName,tcpPort,getServerPort),04357(getSetting/getSettingOrDefaultper-scopeSETTINGS),04501(queryID/currentQueryID),04538(getServerSetting),04539(
getMergeTreeSetting),04540(filesystem*),04541(connectionId),04542(getMaxTableNameLengthForDatabase,hasColumnInTable),04543(
tid),04545(getClientHTTPHeader),04546(hasThreadFuzzer),04547(
showCertificateas aGROUP BYkey),04669(identicaluptimecallsmust keep resolving to a single constant within one query, pinning the
deduplication that the
isDistributed-keyed cache preserves for serverconstants) and
04671(getClientHTTPHeadersibling scopes with thepermission enabled in one branch and disabled in the other must throw
FUNCTION_NOT_ALLOWEDin both orders).04544(authenticatedUser),04612(roles and profiles) and04651(
localtime) pin the opposite, deliberate contract: the initiator folds thecall and ships its own value to the shards, because the underlying state is
not propagated to secondary queries.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
THERE_IS_NO_COLUMNexception (orNOT_FOUND_COLUMN_IN_BLOCKwhenprefer_localhost_replica = 0) raised by the analyzer for queries that combinehostName(or any other server-constant function such astcpPort,serverUUID, ...) in an outerUNION ALLwith a sub-SELECT overclusterAllReplicasthat groups by the same function on a multi-replicacluster. Also fix server-local functions returning the initiator's value on
every shard of a distributed query:
getServerSetting,getMergeTreeSetting,getServerPort,getMaxTableNameLengthForDatabase,hasColumnInTable,getClientHTTPHeader,showCertificate,filesystemAvailable,filesystemCapacity,filesystemUnreserved,connectionId,currentQueryID,hasThreadFuzzer, andtid.authenticatedUserand thecurrentRoles/currentProfilesfamilies keep returning the initiator'svalues in distributed queries (that state is not propagated to the shards);
this contract is now documented explicitly.
Documentation entry for user-facing changes