Skip to content

Fix CURRENT_DATABASE and other functions written without parentheses being evaluated on remote servers - #128517

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-niladic-function-remote-folding
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-niladic-function-remote-folding

Conversation

@groeneai

@groeneai groeneai commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixed wrong results when CURRENT_DATABASE, DATABASE, SCHEMA or another function written without parentheses is used in a query that reads through remote, a Distributed table or a *Cluster table function, and NOT_FOUND_COLUMN_IN_BLOCK / THERE_IS_NO_COLUMN errors when such a function is a GROUP BY key over several shards. The function was evaluated on every remote server, which for CURRENT_DATABASE returned that server's database, instead of once on the initiator like the same function written with parentheses.

Description

Related: #95949 (added functions without parentheses).

On 26.3.60.2 and 26.10.2.103, with a non-default session database, SELECT count() FROM remote('127.0.0.2', numbers(4)) WHERE SCHEMA = currentDatabase() returns 0 instead of 4, and SELECT CURRENT_DATABASE FROM remote(...) returns the remote server's default. With two shards, a GROUP BY key over such a function fails with NOT_FOUND_COLUMN_IN_BLOCK (THERE_IS_NO_COLUMN when one shard is local). The same queries with currentDatabase() are correct.

resolveFunction constant-folds currentDatabase(), so remote servers receive a literal. A function written without parentheses is built by the fallback in QueryAnalyzer::tryResolveIdentifier and in tryResolveIdentifierFromAliases, and was left unfolded: it was sent as currentDatabase() and evaluated in each remote server's own database, and the shards named the folded column differently from the initiator.

Both places now take the built function from the cache that resolveFunction uses for the call <canonical name>() and fold it with the existing foldConstantCast, so the node is the constant the call with parentheses produces, and NOW, CURRENT_TIMESTAMP and now() keep one value in a query. Inside ASOF JOIN ... ON, where resolveFunction does not fold the call either, the node stays unfolded.

The new test fails on master and passes with the fix (100 runs, with and without random settings); reverting either place alone reddens its own case. 04545 and 04906 relied on database staying unfolded to reach their bugs; they now use arrayExists(x -> x > 0, [1]), which only ActionsDAG folds, with unchanged references. Other stateless tests that use such functions without parentheses give the same results with and without the change.


Workflow [PR]
Sync PR [sync-upstream/pr/128517]

`currentDatabase()` written as a call is constant-folded by
`resolveFunction`, so a remote server receives a literal. The same
function written without parentheses (`CURRENT_DATABASE`, `DATABASE`,
`SCHEMA`, ...) is resolved by the niladic fallback of
`QueryAnalyzer::tryResolveIdentifier` and by the alias fallback of
`tryResolveIdentifierFromAliases`, which returned an unfolded function
node. It was sent to remote servers as `currentDatabase()` and evaluated
in each server's own database, so `remote`, `Distributed` and `*Cluster`
reads returned wrong results (`WHERE SCHEMA = currentDatabase()` matched
nothing), and with several shards `GROUP BY CURRENT_DATABASE` failed with
`NOT_FOUND_COLUMN_IN_BLOCK` because the shards named the folded key
column differently from the initiator.

Fold the node at both places with `foldConstantCast`, which already
folds a resolved function with constant arguments exactly like
`resolveFunction` (suitability gate, type check, 1 MiB guard,
determinism propagation, function kept as the source expression). The
result is the same node the call with parentheses produces. Like the
call, it is not folded inside `ASOF JOIN ... ON`, using the check of
`resolveFunction`, moved to `IdentifierResolveScope::isResolvingAsofJoinExpression`.
The doc comment of `foldConstantCast` now says it is not limited to
`_CAST`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 rounds; 2 findings, both fixed; the last round found nothing).

# Sev Finding Verdict Evidence / action
1 ⚠️ The function written without parentheses was folded inside ASOF JOIN ... ON, where resolveFunction does not fold the call, so CURRENT_DATABASE = currentDatabase() there compared the initiator's database with the remote server's AGREE, fixed Both places skip the fold there with the check resolveFunction uses, moved to IdentifierResolveScope::isResolvingAsofJoinExpression; new ASOF JOIN case (1 on master, 0 with the first revision of this PR)
2 ⚠️ No case reached that check in the alias fallback AGREE, fixed New case: an outer alias used inside a subquery's ASOF JOIN ... ON; removing that check alone turns it from 1 to 0
3 💡 foldConstantCast now also folds functions other than _CAST noted, not blocking Renaming it would touch unrelated passes, so only its doc comment is widened

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-self-slot-58:20261101-210500

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05480_niladic_function_remote_server fails every run on master (0 0 0 0, then THERE_IS_NO_COLUMN).
b Root cause explained? Yes. The fallback that resolves a function written without parentheses returned an unfolded function node, so it was sent to remote servers as currentDatabase() and evaluated in their database; resolveFunction folds the call form into a literal.
c Fix matches root cause? Yes. Both places that build the node now fold it with foldConstantCast, like resolveFunction does for the call, and skip the fold inside ASOF JOIN ... ON where resolveFunction skips it too (one shared predicate).
d Test intent preserved / new tests added? Yes. New SQL test: WHERE, SELECT, alias, alias inside a lambda, multi-shard GROUP BY, ASOF JOIN ... ON over remote, directly and through an outer alias in a subquery. No existing test changed.
e Both directions demonstrated? Yes. Fails on master, passes with the fix (50 runs with random settings, 50 without); reverting either place alone reddens its own case, and removing either ASOF JOIN ... ON check reddens its own case.
f Fix is general across code paths? Yes. These are the only two places that build such a node; every consumer already handles the folded call form.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. All functions that allow omitting parentheses go through the same code; checked remote, Distributed, urlCluster, prefer_localhost_replica 0/1 and serialize_query_plan = 1.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; the result is what the call with parentheses already returns. EXPLAIN QUERY TREE now shows a constant.
i Invariants and contracts preserved? Yes. The function stays the constant's source expression, the result is non-deterministic as for the call, and the type and 1 MiB checks of resolveFunction apply.

Session id: cron:clickhouse-impl-self-slot-57:20261101-205500

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir, could you review this and add the can be tested label so CI runs? A function written without parentheses (CURRENT_DATABASE, SCHEMA, ...) was built by the identifier-resolution fallback without the constant folding resolveFunction applies to the call form, so remote servers received currentDatabase() and evaluated it in their own database; both fallback sites now fold it with foldConstantCast, except inside ASOF JOIN ... ON where the call form is not folded either.

@clickhouse-gh

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6b403e2]

Summary: ✅


AI Review

Summary

Reviewed #128517 at 6b403e23d2d904bd150f064f746c8d4cdb96c4bb. The change evaluates functions written without parentheses on the initiator, preserving the existing ASOF JOIN behavior. The earlier finding about inconsistent values across spellings of now is fixed and its thread is resolved. No remaining findings. Using the head commit's CI binary, the new remote-query regression and both modified regression tests match their references; additional time-function and column-shadowing checks also pass.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 1, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 2, 2026
Both tests used the parenthesis-less `database` as an expression the
analyzer did not constant-fold while ActionsDAG did. 04545 needs a GROUP BY
key that only ActionsDAG folds to reach the `wrap_with_nullable` result-type
mismatch of ClickHouse#110551, and 04906 needs a PREWHERE that reads `ver` until
ActionsDAG folds it, so that pruning drops `ver`. Now that the niladic form
folds like `database()`, neither test reached its code path any more (Fast
test: the 04906 pruning control arm printed 1, and 04545 lost the NULL row
of its positional key, which was a non-constant key only because of the
missing fold).

Use `arrayExists(x -> x > 0, [1])` instead: the analyzer does not fold a
function with a lambda argument, ActionsDAG does. The references are
unchanged. They match on the base commit and on this branch. With the
original fixes reverted (the ActionsDAG reconcile of ClickHouse#110551 disabled, the
`output_header->has` filter of the 04906 fix removed), the new versions
abort with the original LOGICAL_ERRORs, while the bare-`database` versions
pass on that binary.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6b403e23d with master 1df150bae (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

24 translation units recompiled, 180 s compile time in total, 24 of them have a recent master baseline.

Job report

The niladic fallbacks of `tryResolveIdentifier` and
`tryResolveIdentifierFromAliases` built a separate function for each
spelling, and since the previous commit fold it right away. A scalar
subquery executed during analysis between two spellings therefore gave
them different values:

    SELECT NOW AS a, (SELECT sleep(2)) AS pause, CURRENT_TIMESTAMP AS b, a = b

returned 0 (1 on master, where the unfolded nodes share the planner name
`now()`). The same held for `LOCALTIME` / `localtime` and for an alias of
such a function referenced from a subquery.

Both fallbacks now call `QueryAnalyzer::resolveNiladicFunction`, which
takes the built function from `functions_cache` under the key that
`resolveFunction` uses for the call `<canonical name>()`. So `NOW`,
`CURRENT_TIMESTAMP` and `now()` share one value per query, as repeated
calls `now()` already did.

The test gets one case per fallback, with a scalar `sleep(1)` between the
spellings so that the analysis always crosses a second boundary.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
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 comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants