Skip to content

Fix *Cluster table functions sending the replicas a CTE name without its definition - #122931

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:cluster-functions-forward-self-contained-query
Oct 19, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:cluster-functions-forward-self-contained-query

Conversation

@groeneai

@groeneai groeneai commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122791

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 cluster table functions (s3Cluster, urlCluster, fileCluster, azureBlobStorageCluster, hdfsCluster, the data lake *Cluster functions, and url/s3 reads distributed by parallel_replicas_for_cluster_engines) returning no rows or wrong rows, and INSERT ... SELECT from them inserting nothing, when a subquery reads a CTE, e.g. WITH t AS (...) SELECT ... WHERE x IN (SELECT ... FROM t): the replicas received the CTE name without its definition. GROUP BY ROLLUP/CUBE/GROUPING SETS with grouping() and SELECT *, x + 1 AS x over these functions no longer fail with UNKNOWN_IDENTIFIER and MULTIPLE_EXPRESSIONS_FOR_ALIAS.

Description

On 26.8.2.7 and master, a cluster table function query whose IN subquery reads a CTE returns no row, with no error:

WITH t AS (SELECT arrayJoin([2, 3]) AS id)
SELECT sum(n), count() FROM fileCluster('test_cluster_one_shard_three_replicas_localhost', 'f.tsv', 'TSV', 'n UInt64')
WHERE n IN (SELECT id FROM t); -- f.tsv holds 0..3: no row; file() gives 5 2

IStorageCluster::read sent the replicas query_info.query, the initiator's own rendering of the query tree. It writes a CTE subquery as the bare CTE name, and keeps the analyzer's grouping specializations and duplicate projection aliases. A replica cannot resolve the name and throws UNKNOWN_TABLE, and the forced skip_unavailable_shards then drops every replica. So the query returns nothing, INSERT ... SELECT inserts nothing, and a table named like the CTE in the replica's database is read instead.

The query is now rendered the way Distributed and parallel replicas render it for a remote server (clone, removeGroupingFunctionSpecializations, queryNodeToDistributedSelectQuery), and the header is computed from that same text.

The new test fails on master and on 26.8.2.7 and passes here.

Not covered: INSERT ... SELECT with parallel replicas (same symptom, fails loudly), a MATERIALIZED CTE used twice (read from a temporary table), replicas still dropped silently on UNKNOWN_TABLE, and a cluster function inside a subquery of a cluster read (#46646).


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

Version info

  • Merged into: 26.11.1.217-master (included in 26.11 and later)

`IStorageCluster::read` forwarded `query_info.query` to the replicas and
re-analyzed it for the header. That AST is the initiator's local rendering
of the query tree (`queryNodeToSelectQuery` with `set_subquery_cte_name`),
so a subquery that reads a CTE is written as the bare CTE name, and the
analyzer's `grouping` specializations and duplicate projection aliases are
kept. A replica cannot resolve the CTE name and throws `UNKNOWN_TABLE`,
which the forced `skip_unavailable_shards` turns into a skipped replica. So
`WITH t AS (...) SELECT ... FROM fileCluster(...) WHERE n IN (SELECT id
FROM t)` returned no row, an `INSERT ... SELECT` of it inserted nothing,
and a table named like the CTE in the replica's database was read instead.
`ROLLUP`, `CUBE` and `GROUPING SETS` with `grouping()` failed with
`UNKNOWN_IDENTIFIER` (`__grouping_set`), and `SELECT *, n + 10 AS n` with
`MULTIPLE_EXPRESSIONS_FOR_ALIAS`, already in the header re-analysis.

Render the query the way the other remote fan-outs do (`Distributed`,
`SelectStreamFactory`, parallel replicas): clone the query tree, remove the
grouping function specializations, and convert it with
`queryNodeToDistributedSelectQuery`, which prints CTE bodies and
deduplicates projection aliases. The header is computed from the same AST,
since that is what the replicas analyze.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 29, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 1 finding).

# Sev Finding Verdict Evidence / action
1 ⚠️ The ROLLUP check does not pin group_by_use_nulls or force_grouping_standard_compatibility, which the stress test randomizes DISAGREE Only the stress job (ci/jobs/scripts/stress/stress.py:494, :549) and the AST fuzzer vary them, and neither compares a test's output with its reference (stress waits on the workers' return codes only, stress.py:838-848; 0 of 3838 Stress/Upgrade failure rows in CIDB over 30 days name a stateless test). tests/clickhouse-test randomizes neither. 145 of the 200 ROLLUP/CUBE/GROUPING SETS tests, e.g. 00701_rollup, rely on the same defaults.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20260929-172200

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f841544]

Summary: ✅


AI Review

Summary

IStorageCluster::read now renders queries for remote re-analysis, preserving CTE definitions, generalizing grouping specializations, and deduplicating projection aliases. It derives the remote header from the same AST. No actionable findings remain after reviewing the current code and all prior discussion; the database-rebinding concern is a pre-existing issue tracked separately in #122985.

Missing context / blind spots
  • ⚠️ Latest-head targeted and bugfix CI reports do not yet contain results. The regression test passed all 50 targeted ASan runs on the preceding head, 94ef94724931c35675106a23bc25cc69876a83e9 (report). Completed latest-head CI would close this remaining validation gap.
Final Verdict

Status: ✅ Approve. No code changes requested. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 29, 2026
/// The replicas re-analyze this query, so it must not name CTEs or `grouping` specializations of the initiator's query tree.
auto query_tree_to_send = query_info.query_tree->clone();
removeGroupingFunctionSpecializations(query_tree_to_send);
ASTPtr query_to_send = queryNodeToDistributedSelectQuery(query_tree_to_send);

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.

The forwarded query is still not fully self-contained for CTEs whose body reads through a database-sensitive table function. queryNodeToDistributedSelectQuery now inlines the CTE body, but the normalization that follows still calls AddDefaultDatabaseVisitor with only_replace_in_join = true, so non-JOIN table expressions inside that inlined subquery are never canonicalized. TableFunctionNode::toASTImpl only qualifies parameterized views, so a case like WITH t AS (SELECT * FROM merge('^foo')) ... IN (SELECT ... FROM t) will still be rebound on each replica against that replica's current database instead of the initiator's, which can produce wrong rows or UNKNOWN_TABLE. This needs a full table-expression normalization pass on the forwarded AST after CTE inlining (for example visitTableExpressions), not just the join side.

@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit f841544f5807819449b68ba77b6396a2f70f1e59 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

Comment thread src/Storages/IStorageCluster.cpp Resolved
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai check the bot comments

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim I checked both; neither needs a change in this PR. Measured on this head and on today's master (371b23a):

  1. merge('^foo') inside an inlined CTE: real, but not caused by this PR and not specific to CTEs or *Cluster. On master the same subquery without a CTE over fileCluster, and remote() with or without the CTE, also match the regexp against the replica's default database (0 1 instead of 5 2). This PR makes the CTE form behave like those. The fix for every fan-out is in my open PR Fix the one-argument merge table function reading the default database of other servers in distributed queries #122985 (at resolve time, in QueryAnalyzer); a pass only in IStorageCluster::read would leave remote() and Distributed wrong.

  2. Header from the sent AST: the described effect does not happen. SELECT *, n + 10 AS n FROM fileCluster(...) returns the same names and values as file(...), also via DESCRIBE, JSON metadata, INSERT SELECT and an outer SELECT * / SELECT n / GROUP BY over it; master rejects all of these fileCluster queries with MULTIPLE_EXPRESSIONS_FOR_ALIAS. The suggested change (header from query_tree) makes the outer SELECT *, SELECT n and GROUP BY shapes, and the FROM subquery case of this PR's test, fail with NOT_FOUND_COLUMN_IN_BLOCK: the replicas name their columns from the query they receive, so the header has to come from the same rendering.

@PedroTadim

Copy link
Copy Markdown
Member

query_info.query_tree->clone() dereferences a null pointer when enable_analyzer = 0. The old interpreter (InterpreterSelectQuery) never sets SelectQueryInfo::query_tree, so it keeps its nullptr default. That path still reaches IStorageCluster::read: on master, SELECT sum(n), count() FROM fileCluster('test_cluster_one_shard_two_replicas', 'f.tsv', 'TSV', 'n UInt64') SETTINGS enable_analyzer = 0 returns 6 4. With this change, the same query would bring the server down. I found this by reading the code and running the query on master, not by building the PR. CI doesn't catch it because no stateless job runs with the old analyzer any more.

Could the old rendering stay as the fallback when there is no query tree, the same way StorageDistributed checks if (!query_info.query_tree)? For example:

ASTPtr query_to_send;
if (query_info.query_tree)
{
    auto query_tree_to_send = query_info.query_tree->clone();
    removeGroupingFunctionSpecializations(query_tree_to_send);
    query_to_send = queryNodeToDistributedSelectQuery(query_tree_to_send);
}
else
    query_to_send = query_info.query->clone();

A line with SETTINGS enable_analyzer = 0 in the test would cover it. A CTE query on the old analyzer still returns no row, as on master; it could go in the "Not covered" list.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim I measured it: on the CI build of this head (88d46cf0c48, the merge of 94ef947 into master) and on today's master (2cb89c8b71c) your query returns 6 4, and the server stays up.

On master enable_analyzer = 0 no longer reaches InterpreterSelectQuery: the value is rewritten to 1 (executeQuery.cpp), and InterpreterFactory sends every SELECT to InterpreterSelectQueryAnalyzer (InterpreterFactory.cpp). system.query_log shows allow_experimental_analyzer = 1 for that query. The remaining InterpreterSelectQuery uses only analyze or read a given input pipe (aggregate projections), so none of them calls IStorage::read. The !query_info.query_tree check in StorageDistributed is in getKeyColumns; StorageDistributed::read dereferences query_tree unconditionally (StorageDistributed.cpp).

So a SETTINGS enable_analyzer = 0 line would pass with or without the fallback, and the else branch would be unreachable; I have left the code as is. With enable_analyzer = 0 the CTE query returns 5 2 on this build (no row on master), so the "Not covered" list does not change. On 26.8 and 26.3 the old interpreter is still reachable, but IStorageCluster::read there keeps its own allow_experimental_analyzer branch, so a backport of this change goes into the analyzer branch only.

If you still want the fallback, I'll add it.

…orward-self-contained-query

Master marks the header analysis in `IStorageCluster::read` with `positionalArgumentsAlreadyResolved`;
apply it to the `query_to_send` printed from the query tree, which is also resolved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 19, 2026
Merged via the queue into ClickHouse:master with commit 48dfd29 Oct 19, 2026
178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
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-distributed Distributed table engine & query routing across shards (sharding/load balancing). groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants