Skip to content

Analyzer: exclude server-constant functions from shared function cache - #107775

Closed
josemimbre wants to merge 38 commits into
ClickHouse:masterfrom
josemimbre:jmimbrero/fix-analyzer-hostname-function-cache
Closed

josemimbre wants to merge 38 commits into
ClickHouse:masterfrom
josemimbre:jmimbrero/fix-analyzer-hostname-function-cache

Conversation

@josemimbre

@josemimbre josemimbre commented Jun 17, 2026 •

Copy link
Copy Markdown

Regression introduced by #86967, which moved the resolved-function cache to be
per-QueryAnalyzer and keyed 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 by name 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 via FunctionConstantBase, and that
boolean gates isSuitableForConstantFolding. Reusing a FunctionBase built
in one scope for a sibling scope with a different is_distributed 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()]

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. Reproduced on docker images
clickhouse/clickhouse-server:25.6.13.41, 25.7.8.71, 25.8.24.21, 26.3.12.3
and on a local master build (v26.4.1.1). Bisected by docker image; the
introducer is the single shared backport across the 25.6.12.10 → 25.6.13.41
and 25.7.7.68 → 25.7.8.71 bumps that touches the analyzer:
Backport #86967 to 25.6 (#87637) / Backport #86967 to 25.7 (#87638). Until
now the workaround is to wrap each hostName call in materialize to suppress
folding.

Related work that was on adjacent paths but did not cover this one: #66433
introduced isServerConstant for GROUP BY constant handling; #93286
addressed the same symptom in StorageMerge.

What the change does

  1. 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 FunctionBase is shared only when the function is
    isDeterministicInScopeOfQuery. Using the property instead of a name list
    also picks up getSettingOrDefault, which shares the getSetting
    implementation and was silently missing from the list. Because
    server-constant bases capture context->isDistributed() at construction
    (it gates isSuitableForConstantFolding), the cache key now also includes
    the scope's isDistributed flag: scopes that disagree on it (the inner
    clusterAllReplicas sub-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 uptime
    snapshots its value at build time, and isDeterministicInScopeOfQuery
    promises a single constant per query, so dropping the deduplication would
    turn SELECT uptime() = uptime() into a timing-dependent result.
    IFunctionOverloadResolver already exposes the property through the
    adaptors in IFunctionAdaptors.h, so this is a free check that runs before
    build and keeps the cache for randConstant-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 now getClientHTTPHeader, whose
    allow_get_client_http_header permission check runs when the function is
    built for a scope - sharing a base built under an enabled sibling scope with
    a disabled one would be a permission bypass. (getMergeTreeSetting was
    audited for the same risk and is safe to share: Context::getMergeTreeSettings
    is computed once per server from the default profile's compatibility and
    cached in the shared context, so a scope-local compatibility does not
    change its result.)

  2. isServerConstant on the functions that are server-local but did not
    advertise it
    : getServerPort (both overloads), getServerSetting,
    getMergeTreeSetting, getMaxTableNameLengthForDatabase,
    hasColumnInTable, getClientHTTPHeader, showCertificate,
    filesystemAvailable / filesystemCapacity / filesystemUnreserved, and
    the transaction counters (transactionID, transactionLatestSnapshot,
    transactionOldestSnapshot).

  3. No initiator-side folding for those functions. Each of them now gates
    isSuitableForConstantFolding on the context->isDistributed() captured at
    construction, 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.

  4. Functions whose value is not propagated to secondary queries but is
    meaningful shard-locally
    build a ColumnConst directly in executeImpl,
    which the analyzer folds regardless of isSuitableForConstantFolding.
    connectionId, currentQueryID, getFuzzerData and hasThreadFuzzer now
    return a full column so each shard observes its own value, matching
    queryID.

  5. tid returns the id of the thread processing the current block, so it
    varies between blocks of a single query. It is now marked
    isDeterministicInScopeOfQuery() == false and not foldable, instead of
    being replaced during analysis by the analysis thread's id.

localtime was checked and deliberately left folding on the initiator: it is
the SQL-standard LOCALTIME, documented as equivalent to CAST(now() AS Time),
so like now() it must evaluate once on the initiator and ship the same literal
to every shard. 04651_localtime_distributed_constant pins that behaviour.

The session-identity family - authenticatedUser and the currentRoles /
enabledRoles / defaultRoles and currentProfiles / enabledProfiles /
defaultProfiles families - was also checked and deliberately left folding on
the initiator. None of that state is propagated to secondary queries
(ClientInfo serializes only initial_user and, with a cluster secret,
current_roles; authenticated_user and 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 pair currentUser's initiator identity with the
shard account's roles/profiles. So, consistent with currentUser (which
reports the propagated initial_user everywhere), they keep returning the
initiator's values in distributed queries until that state gets a transport.
The structured documentation of these functions now states this contract
explicitly, and 04544 / 04612 pin 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 clusterAllReplicas scope) and the folding gate (the
shipped shard query must still contain the call, not a _CAST literal):

04356 (hostName, tcpPort, getServerPort), 04357 (getSetting /
getSettingOrDefault per-scope SETTINGS), 04501 (queryID /
currentQueryID), 04538 (getServerSetting), 04539
(getMergeTreeSetting), 04540 (filesystem*), 04541 (connectionId),
04542 (getMaxTableNameLengthForDatabase, hasColumnInTable), 04543
(tid), 04545 (getClientHTTPHeader), 04546 (hasThreadFuzzer), 04547
(showCertificate as a GROUP BY key), 04669 (identical uptime calls
must keep resolving to a single constant within one query, pinning the
deduplication that the isDistributed-keyed cache preserves for server
constants) and 04671 (getClientHTTPHeader sibling scopes with the
permission enabled in one branch and disabled in the other must throw
FUNCTION_NOT_ALLOWED in both orders).

04544 (authenticatedUser), 04612 (roles and profiles) and 04651
(localtime) pin the opposite, deliberate contract: the initiator folds the
call and ships its own value to the shards, because the underlying state is
not propagated to secondary queries.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix THERE_IS_NO_COLUMN exception (or NOT_FOUND_COLUMN_IN_BLOCK when
prefer_localhost_replica = 0) raised by the analyzer for queries that combine
hostName (or any other server-constant function such as tcpPort,
serverUUID, ...) in an outer UNION ALL with a sub-SELECT over
clusterAllReplicas that groups by the same function on a multi-replica
cluster. 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, and tid. authenticatedUser and the
currentRoles / currentProfiles families keep returning the initiator's
values in distributed queries (that state is not propagated to the shards);
this contract is now documented explicitly.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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.
@thevar1able thevar1able added the can be tested Allows running workflows for external contributors label Jun 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3b68a9a]

Summary: ❌

job_name test_name status info comment
Stress test (arm_release) FAIL
Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-6673) FAIL cidb

AI Review

Summary

This 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: getMergeTreeSetting still violates the cache contract for sibling scopes that share isDistributed but differ in SETTINGS compatibility, so the PR is not ready to merge yet.

Findings

❌ Blockers

  • [src/Functions/getMergeTreeSetting.cpp:29] getMergeTreeSetting still reads getContext()->getMergeTreeSettings() from the build-time scope, and Context::getMergeTreeSettings() derives defaults from the scope-local compatibility setting. After resolveFunction switched the cache key to {tree hash, isDistributed}, two identical calls in sibling scopes with the same isDistributed value but different SETTINGS compatibility can still reuse one cached FunctionBase, so one branch observes the other branch's compatibility-adjusted MergeTree setting.
    Suggested fix: keep this function out of the shared analyzer cache (for example by overriding isDeterministicInScopeOfQuery() to false) or extend the cache key to include the extra scope-local state it captures. Add a focused regression like 04357, but with getMergeTreeSetting(...) under two sibling subqueries that set different compatibility values.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 128/144 (88.89%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 17, 2026
…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.
@CLAassistant

CLAassistant commented Jun 17, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

…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.
Comment thread src/Functions/getServerSetting.cpp Resolved
Comment thread src/Functions/getServerSetting.cpp Resolved
…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.
Comment thread src/Functions/currentQueryID.cpp Resolved
`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.
Comment thread src/Functions/getServerSetting.cpp Resolved
…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.
`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
Comment thread src/Functions/authenticatedUser.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 98/110 (89.09%) · Uncovered code

Full report · Diff report

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.
Comment thread src/Functions/currentRoles.cpp Resolved
Comment thread src/Functions/currentProfiles.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

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.
Comment thread src/Functions/currentRoles.cpp Resolved
…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()) {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/Functions/getClientHTTPHeader.cpp Resolved
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.
@alexey-milovidov

Copy link
Copy Markdown
Member

Why closed?

eoger-ant pushed a commit to eoger-ant/ClickHouse that referenced this pull request Nov 17, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants