Skip to content

Read object storage tables (S3, Iceberg, DeltaLake, ...) with parallel replicas - #127138

Merged
alexey-milovidov merged 17 commits into
ClickHouse:masterfrom
groeneai:parallel-replicas-object-storage-tables
Oct 24, 2026
Merged

alexey-milovidov merged 17 commits into
ClickHouse:masterfrom
groeneai:parallel-replicas-object-storage-tables

Conversation

@groeneai

@groeneai groeneai commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #127052

Changelog category (leave one):

  • Improvement

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

A table with the S3, AzureBlobStorage, HDFS, Iceberg*, DeltaLake, DeltaLakeS3, DeltaLakeAzure, Hudi, Paimon, PaimonS3, PaimonAzure or PaimonHDFS engine is now read over the replicas of cluster_for_parallel_replicas when parallel replicas are enabled, as the table functions of these engines already are with parallel_replicas_for_cluster_engines. A replica takes part only if it has the table. The new setting parallel_replicas_for_object_storage_tables turns it off. Closes #127052.

Description

With parallel replicas enabled, icebergS3(...) is read over the replicas, but a table created with ENGINE = IcebergS3(...) was always read by the initiator alone: the storage of a persistent table is created once at CREATE/ATTACH, so it cannot decide per query.

Change: when the FROM of a query is such a table alone (possibly with ARRAY JOIN), the analyzer reads it through a transient StorageObjectStorageCluster that shares the table's configuration and metadata, so the existing cluster read handles it. The swap is in the analyzer, not in read: the planner picks the processing stage and collects the _path/_file pruning predicate from the storage type before read runs. The replicas receive SELECT ... FROM db.t and read their own db.t with the initiator's read tasks. The query is analyzed as a local read, so hostName() and other server constants are computed on the initiator. A replica without the table, or one older than the new cluster function protocol version 13 (it would read every file), is not used. The read stays local for a row policy, a SQL SECURITY DEFINER/NONE view body, an explicit PREWHERE, a correlated subquery, a JOIN, a materialized view source, max_parallel_replicas = 1, the system database, and a query that also reads a table function or a table not read this way (on a replica it could take this table's read tasks).

No speed-up is claimed (#126036, #127051, #127060). ProfileEvents['ParallelReplicasUsedCount'] stays 0 for these reads, as for icebergS3(): it counts only MergeTree reads.

Validation: the new stateless tests and the integration test (skipped replicas) fail without the change and pass with it. Eight existing tests assert on ProfileEvents or EXPLAIN of the initial query and are tagged no-parallel-replicas.

Protocol version 13 is new here; please tell me if the private repository already uses it.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 8 commits October 21, 2026 00:46
A table created with `ENGINE = S3/AzureBlobStorage/HDFS/Iceberg*/DeltaLake*/Hudi/Paimon*`
was always read by the initiator alone, while the table functions and `DataLakeCatalog`
tables of the same engines are read over the replicas of `cluster_for_parallel_replicas`
when `parallel_replicas_for_cluster_engines` is enabled. A persistent table's storage is
created once, at `CREATE`/`ATTACH`, so it cannot make that decision itself.

The analyzer now makes it per query: when the `FROM` of a query is such a table alone
(possibly with `ARRAY JOIN`), the table node reads through a transient
`StorageObjectStorageCluster` that shares the table's configuration and metadata, so the
existing `IStorageCluster` path handles the read (processing stage, row policies, task
iterator pruning). The replicas receive `SELECT ... FROM db.t` and read their own `db.t`
with the initiator's read tasks; a replica recognizes that from the query being the
secondary query of a cluster read whose whole `FROM` is that table, not from settings,
because the initiator may change the parallel replicas settings after the analysis.

A replica without the table, or one older than the new cluster function protocol
version 13 (which would read all of the files), is not used. A query is read locally, as
before, for a row policy, a `SQL SECURITY` view body, a materialized view source, an
explicit `PREWHERE`, a correlated subquery, a `JOIN`, a partition strategy other than
hive, a Delta Lake CDF read, and tables of the `system` database. The new setting
`parallel_replicas_for_object_storage_tables` (default `true`, `false` for
`compatibility` 26.10 and older) turns the feature off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nitial-query counters

The integration test reads a persistent `S3` table with parallel replicas over a
cluster of two current servers and one at `CLICKHOUSE_CI_MIN_TESTED_VERSION`: the older
server is not used (it would read every file), and neither is a server without the table.

With parallel replicas enabled server-side (the `ParallelReplicas` stateless job) six
tests now read their object storage table on the replicas, so the `ProfileEvents` and
`EXPLAIN` of the initial query they assert on no longer describe the file reads; their
results are unchanged. Tag them `no-parallel-replicas`.

Write the protocol version 13 entry of the native protocol specification as its own
sentence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ITY NONE view

For a lazily loaded table the analyzer builds the cluster storage from the
loaded table and a snapshot taken after the metadata refresh, but recorded the
lazy stand-in and the pre-refresh snapshot for the rollback of a correlated
query, so planning could see other metadata than the one the columns were
resolved against. Record the storage and snapshot the replacement was built
from instead.

Skip the refresh for a lazily loaded table that is not an object storage table,
which saves a discarded storage snapshot per query (e.g. a MergeTree table in a
`lazy_load_tables` database with parallel replicas enabled).

The test now also checks that the body of a `SQL SECURITY NONE` view reads the
table locally.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`parallel_replicas_prefer_local_replica = 0` with `max_parallel_replicas = 1`
passes `canReplaceClusterEngineWithClusterVariant`, but `ReadFromCluster` caps
the replicas only when `max_parallel_replicas > 1`, so the cluster read went to
every replica of `cluster_for_parallel_replicas` instead of reading locally.
Return no cluster storage for such a query, and cover it in 05441.

Also reword the identity-guard comment: without an interserver secret the
replicas authenticate as the cluster's configured user, not as the initial one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On a replica, `isReadOnReplicaForInitiator` took any `QueryNode` that is not a
subquery or a CTE for the root of the query the initiator sent. `UNION` arms are
built with `is_subquery = false` and every nested interpreter has a root of its
own, so an `IN` subquery with `UNION ALL` arms over the table pulled files from
the initiator's task stream: a cluster read returned a wrong count, and under
MergeTree parallel replicas the follower's `ReadTaskRequest` failed with
`BAD_ARGUMENTS`.

`executeQuery` now marks the query it receives from an initiator with
`SelectQueryOptions::is_secondary_query_root`, which `subquery()` clears and the
planner copies into `SelectQueryInfo`; the follower rule tests that flag.

05441 covers both shapes. The MergeTree table has no primary key, so the `IN`
set does not prune it and the followers read it too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A replica forwards the whole query of the swapped table, including its IN
and scalar subqueries, and the initiator answers every read-task request on
that connection from this table's iterator. A cluster table function, a
DataLakeCatalog table, or a view or table over other tables in the forwarded
query then takes this table's files on the replica, so
`t IN (SELECT a FROM s3Cluster(...))` returned a wrong count. The table
functions avoid this shape by counting table functions before resolution,
which never sees a named table.

The post-resolution rollback now also restores the swapped tables when the
resolved tree has another table or table function whose storage is a cluster
read, a view, reads other tables, or is not loaded yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The r4 rollback enumerated the storage kinds that may send read-task
requests on a replica (cluster reads, views, tables over other tables), but
any storage that runs a query of its own during read escapes such a list:
an `Executable` table whose input query is `SELECT a FROM s3Cluster(...)`
took the swapped table's files on the replicas, so
`t IN (SELECT a FROM e WHERE a < 50)` returned 0 instead of 50. The rule is
now closed: a query that also reads a table function or any table that is
not one of the swapped ones reads the swapped tables itself. A table inside
a subquery is never swapped (the query is distributed once its root table
is), so a subquery that reads a table now keeps the read local as well.

A scalar subquery is executed while it is resolved, before the rollback at
the end of `resolve`, so `SELECT (SELECT count() FROM t WHERE a IN vc)` with
`vc` a view over `s3Cluster` still forwarded the view. The rollback now also
runs for the subquery right before `evaluateScalarSubqueryIfNeeded` executes
it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop five self-describing comments on new declarations and shorten the isClusterVariantDisabledForQuery doc to one line.

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

mintlify Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 808baeb.

Approve preview

@groeneai

groeneai commented Oct 21, 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; 11 rounds) plus my own review (6 notes).

# Sev Finding Verdict Evidence / action
1 ⚠️ A correlated query over a lazily loaded table rolled back to the snapshot taken before the metadata refresh (QueryAnalyzer.cpp) AGREE, fixed the rollback keeps the storage and snapshot the resolution used
2 ❌ The initiator's header analysis and the replicas resolve the current data-lake snapshot, not the pinned one DISAGREE shared cluster read path: the same holds for DataLakeCatalog cluster reads and, on the replicas, for icebergS3(); files and delete files come from the initiator's snapshot in the read tasks, so a concurrent schema change fails the query
3 ❌ Protocol version 13 may mean something else in the private repository DISAGREE private numbers are reserved in ProtocolDefines.h (see 7); 13 is not; the PR body asks
4 ⚠️ No test for the SQL SECURITY NONE and materialized-view-source guards AGREE for NONE, fixed; DISAGREE for MV MV pushes already run with enable_parallel_replicas = 0 (InterpreterInsertQuery::buildInsertPipeline), so that guard is not observable from SQL
5 ⚠️ max_parallel_replicas = 1 with parallel_replicas_prefer_local_replica = 0 fanned the read out to every replica AGREE, fixed such a query reads the table itself; the table functions' fan-out under that setting is unchanged
6 ❌ On a replica, a UNION arm or a non-inlined view inside a subquery was taken for the forwarded query and read the initiator's tasks AGREE, fixed wrong result under the new read, BAD_ARGUMENTS under MergeTree parallel replicas; the replica now uses the tasks only for the query it received
7 ❌ Without a cluster <secret>, the replicas apply the row policy of the cluster's user DISAGREE every parallel-replicas read (MergeTree too) and every Distributed read runs as the cluster's user without a secret (ClusterProxy/executeQuery.cpp:367); not specific to these tables
8 💡 No replica qualifies and the initiator is outside the cluster: an error instead of a local read noted the error names the table and the cluster; parallel_replicas_for_object_storage_tables = 0 opts out
9 💡 One TablesStatus round trip per replica per read noted the price of skipping replicas without the table
10 💡 The header analysis of the forwarded query refreshes the table metadata once more on the initiator noted same as for the table functions; no speed-up is claimed
11 ❌ On a replica, a cluster table function (s3Cluster, ...), a DataLakeCatalog table or a view over one inside the query took this table's read tasks AGREE, fixed the initiator answers every read-task request from this table's iterator; a query with another source now reads the table itself, as the table functions already do (TableFunctionsWithClusterAlternativesVisitor)
12 ❌ A scalar subquery over the table and another cluster read ran before that rollback AGREE, fixed scalar subqueries are executed during analysis; the read of their tables is now decided before they run
13 ⚠️ An Executable table whose input query is a cluster read escaped the storage-kind check AGREE, fixed the check is now closed: any table function, or any table not read this way (also the same table in a subquery), keeps the read local
14 💡 Two section headings of the new test still describe replica reads for queries that now stay local AGREE, fixed retitled; the assertions were already right
15 ⚠️ A table function in a subquery with its own SETTINGS is not turned into its -Cluster variant when the query also reads such a table AGREE, fixed a query with a subquery that reads a source no longer has its table replaced, so nothing in it is resolved as distributed (05441 checks an s3 in such a subquery); a subquery that reads nothing or a constant set keeps the parallel read
16 ⚠️ The test does not pin enable_analyzer = 1 DISAGREE the analyzer cannot be disabled since v26.9 (enable_analyzer = 0 is replaced with 1)
17 💡 DeltaLake* and Paimon* in the changelog entry also match DeltaLakeLocal and PaimonLocal, which have no -Cluster variant AGREE, fixed the entry lists the engines
18 ❌ CREATE VIEW ... ON CLUSTER stored the view body without parallel_replicas_for_object_storage_tables, so the view ignored the opt-out AGREE, fixed the distributed DDL text keeps that setting; 05444 checks the stored body and that the view reads its table itself
19 ❌ Keeping that setting in the DDL text and settings sends it to older workers as UNKNOWN_SETTING DISAGREE a worker runs the DDL's own SELECT (e.g. CREATE TABLE ... AS SELECT) as its query and honors the setting (measured: 3 replicas with it on, none with = 0), so it is not initiator-only there; an older worker rejects any newer changed setting the DDL entry carries
20 ⚠️ A replica skipped for a missing table or an old protocol stays a task owner, so a nonzero cluster_function_wait_for_replica_ms waits for it DISAGREE pre-existing in the task distributor, which takes every host of the cluster: an explicit s3Cluster (not changed here) with max_parallel_replicas = 2 on 3 replicas and a 3000 ms wait takes 3170 ms vs 159 ms; a separate fix
21 ⚠️ An IN operand that is an alias of a table name (WITH ids AS s ... IN s) still skips the guard, so a catalog table loses its parallel read AGREE, fixed in 7131a0b measured with a DataLakeCatalog current database: 0 vs 3 secondary queries with the setting on vs off before, 3 vs 3 after; a view over plain s3 is not affected
22 ⚠️ A table-qualified column as an IN set (a IN t.vals) is taken for a table, so the query reads locally DISAGREE the guard is conservative: a false refusal gives the local read of master and of the setting off; resolving qualifiers here would duplicate the analyzer's identifier rules for a rare shape; moot since 808baeb, which removes the guard
23 ⚠️ A source read in a WITH lambda or SQL UDF body still loses its cluster read (bot) AGREE, fixed in 808baeb measured 0 vs 3 replicas with the setting on vs off, also over the catalog table; the root cause is fixed instead of adding a 6th case: a replaced table no longer marks the query distributed, so every other source resolves as without the setting and the pre-check of rows 15 and 21 is removed

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

Session id: cron:clickhouse-review-slot-8:20261021-080500 (rows 14-17: cron:clickhouse-maint-slot-13:20261021-143400; rows 15, 18-20: cron:clickhouse-maint-slot-14:20261023-002000; rows 21-22: cron:clickhouse-maint-slot-12:20261023-040500; row 23: cron:clickhouse-maint-slot-12:20261023-060500)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. With enable_parallel_replicas = 1, cluster_for_parallel_replicas set and a table ENGINE = S3(...) over 6 Parquet files, EXPLAIN SELECT sum(a) FROM t WHERE a > 10 has no ReadFromCluster on master and the read sends no query to the replicas; with the change it has ReadFromCluster, 3 replicas run it, and the result is unchanged.
b Root cause explained? A persistent table's storage is created once, at CREATE/ATTACH, so it cannot make the per-query decision the table functions and DataLakeCatalog make when their storage is built; and a replica reading its own db.t would read every file.
c Fix matches root cause? Yes. The analyzer makes the decision per query and reads the table through the existing cluster storage; a replica reads its db.t with the initiator's tasks only for the root table of the query it received. A query that also reads a table function or any table not read this way reads the table itself, and a scalar subquery is decided before it is executed, so no other source can take its read tasks.
d Test intent preserved / new tests added? New stateless test (S3, Iceberg with deletes, hive partitioning, lazily loaded table, and the cases that stay local) and an integration test for replicas without the table and older replicas. Six existing tests that assert on ProfileEvents/EXPLAIN of the initial query are tagged no-parallel-replicas.
e Both directions demonstrated? Yes. On master the read-with-replicas lines print 0 instead of 1 and the integration test fails; with the change both pass (50/50 randomized runs; integration 3 consecutive passes). Removing each guard breaks its own test case.
f Fix is general across code paths? One code path for every engine with a -Cluster table function (S3, Azure, HDFS, Iceberg, DeltaLake, Hudi, Paimon variants). Writes, mutations, materialized view sources and table functions are unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Query shapes covered: single table, ARRAY JOIN, JOIN, comma join, IN subquery, correlated subquery, PREWHERE, SQL SECURITY DEFINER and NONE views, row policy; both opt-out settings; parallel_replicas_allow_in_with_subquery = 0; an IN subquery with UNION ALL arms, also under MergeTree parallel replicas; an IN subquery over s3Cluster, over a view of it and over a MergeTree table; a scalar subquery with IN over a view of s3Cluster.
h Backward compatible? (maintainer-approved exception only) Yes. New setting parallel_replicas_for_object_storage_tables, false for compatibility 26.10 and older; replicas older than cluster protocol version 13 are not used; the setting is initiator-only.
i Invariants and contracts preserved? Every file is read once, by the replicas the initiator hands it to, under the caller's identity and filters; the shared table configuration is not re-initialized (verified with a hive-partitioned INSERT after a read).

Session id: cron:clickhouse-impl-slot-5:20261021-071900

@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [808baeb]

Summary: ✅


AI Review

Summary

PR #127138 enables eligible persistent object storage tables to use parallel replicas, with an opt-out setting and checks for replica availability and protocol support. Reviewed head 808baeb86945fe254c3d4804d99bc6a333f21e9e; no unresolved findings. The previously reported loss of parallel reads for sources behind identifiers, CTEs, lambdas and SQL UDFs is addressed in the current code, with regression coverage, and its review thread has been resolved.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @novikd @SmitaRKulkarni, could you review this and add the can be tested label so CI runs? When the FROM of a query is a single S3/Iceberg/DeltaLake/... table, the analyzer reads it through a transient StorageObjectStorageCluster, and each replica reads its own copy of the table with the initiator's read tasks (cluster protocol version 13).

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Oct 21, 2026
@scanhex12 scanhex12 added the can be tested Allows running workflows for external contributors label Oct 21, 2026
@scanhex12 scanhex12 self-assigned this Oct 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 808baeb86 with master 44cf9c049 (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.

Object file sizes

388 object files changed (+275.57 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Resolve/QueryAnalyzer.cpp.o 1.58 MiB 1.61 MiB +27.76 KiB (+1.71%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/StorageObjectStorage.cpp.o 600.16 KiB 619.46 KiB +19.30 KiB (+3.22%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

The test started about 80 `clickhouse client` processes, three per check
(EXPLAIN, the query with parallel replicas, the query without them). Under
ASan a client start costs ~0.4 s, so starting clients was most of the run
time, and the ASan flaky check failed it with "Test runs too long (> 180s)"
(p50 161 s, max 213 s).

Each check now sends its three queries, byte for byte the same, to one
client and splits the output on a separator line. That leaves 36 client
starts. With an ASan client against a local server the run time drops from
~44 s to ~21 s (24 runs, 12 in parallel); the old and the new check print
the same output for differing, multi-line, empty and ReadFromCluster
results.

Also retitle two sections whose headings still described a replica read,
while their EXPLAIN lines show the table is read locally.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). and removed comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. labels Oct 21, 2026
alexey-milovidov and others added 5 commits October 22, 2026 20:32
It runs a dozen parallel replicas queries over S3 and Iceberg tables and takes
more than 180 seconds in the flaky check under ASan with S3 storage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…bject-storage-tables

# Conflicts:
#	src/Storages/ObjectStorage/StorageObjectStorage.h
#	src/Storages/ObjectStorage/registerStorageObjectStorage.cpp
With parallel replicas a read of a persistent Iceberg table is now
distributed, so the counters of the initial query change while the
results do not:

- `05339_iceberg_top_k_query_condition_cache`: the replicas use the
  query condition cache, so the initial query records no lookups (the
  same as the three other query condition cache tests already tagged).
- `05407_iceberg_metadata_s3_requests`: the initiator resolves the
  table again when `IStorageCluster::read` analyzes the query it sends
  to the replicas, so the table read makes 2 LIST requests instead of 1.

Both pass with `parallel_replicas_for_object_storage_tables = 0` and in
the other configurations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two cases where reading a persistent object storage table with parallel
replicas changed something it should not:

- The cluster read marks the query distributed as soon as its table is
  replaced, and a subquery inherits that state. So a plain `s3` in a
  subquery with its own `SETTINGS` (whose context the table function
  uses) was no longer converted to `s3Cluster`, while the query was then
  rolled back to a local read because it has another source. The same
  holds for a `DataLakeCatalog` table in a subquery or on the right side
  of `IN`, which is resolved with that context too. A query with a
  subquery or with a table on the right side of `IN` always reads its
  table itself, so do not replace the table in such a query at all,
  instead of replacing it and rolling it back. Measured with
  `SELECT count() FROM t WHERE a IN (SELECT a FROM s3(...) WHERE a < 50
  SETTINGS max_threads = 2)`: 0 remote queries before, 3 now, the same as
  with `parallel_replicas_for_object_storage_tables = 0`.

- `parallel_replicas_for_object_storage_tables` is stripped from the text
  of a distributed DDL query with the other initiator-only settings, so
  `CREATE VIEW ... ON CLUSTER` stored the view body without it, and the
  view was then read with parallel replicas despite the opt-out. Keep it
  in the DDL text: in a view body it decides how the view reads its
  table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commit kept the table of every query with a subquery or with
an identifier on the right side of `IN`, which also kept local the queries
that read nothing else, e.g. `WHERE a > (SELECT 1)`, `exists(SELECT 1)` or
`WITH (1, 2) AS s ... WHERE a IN s`, which read the table with parallel
replicas before. Only a subquery that reads a source is affected by the
distributed state it inherits, and a query with such a subquery is read
locally in any case, so refuse the replacement only for it. The seven
shapes measured before and after this commit read the same way, and the
`s3` in a subquery with its own `SETTINGS` is still read with parallel
replicas.

05444 now also reads the views, and checks that the one created ON CLUSTER
with the opt-out reads its table itself while the one without it does not.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
groeneai and others added 2 commits October 23, 2026 04:34
…lacing the table

The table is replaced while the FROM is resolved, and the replacement marks the
query context distributed. A source the query resolves afterwards inherits that
state, so its own cluster read is disabled (`canReplaceClusterEngineWithClusterVariant`),
and the final rollback restores only the replaced table. The check before the
replacement saw subqueries in the query tree only, but `resolveQuery` has already
moved the CTEs and the `WITH` aliases out of it, and `x IN name` is an identifier
until it is resolved. So each of these lost an existing parallel read as soon as
`parallel_replicas_for_object_storage_tables` was enabled (measured, 3 replicas,
secondary queries with the setting on vs off; results equal):

- `(a, b) IN catalog.ids`, a DataLakeCatalog (Iceberg REST) table: 0 vs 3
- `WITH c AS (SELECT a FROM s3(...) SETTINGS max_threads = 2) ... a IN c`: 0 vs 3
- a CTE over the catalog table, `a IN c`: 0 vs 3
- `WITH (SELECT max(a) FROM s3(...) SETTINGS ...) AS m ... a <= m`: the s3 read
  became local and `t` was read with parallel replicas instead

Follow the identifiers of the query to the CTEs and expression aliases of the
scope chain and check their nodes the same way, and treat an `IN` over a name
that is neither an alias, a CTE nor a column of the table as a table. All the
shapes above now read like with the setting disabled. Shapes without another
source keep the parallel read: `WITH (1, 2) AS s ... IN s`, `WITH 5 AS x`,
`b IN b`, `(SELECT 1)`, `exists(SELECT 1)`, `IN (1, 2)`.

Reported by the automated review on ClickHouse#127138.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`WITH ids AS s SELECT ... WHERE x IN s` resolves the body of the alias as a
table expression, so with a DataLakeCatalog database as the current database
the catalog table lost its parallel read the same way as `x IN ids` did before
the previous commit (measured, 3 replicas: 0 secondary queries with
`parallel_replicas_for_object_storage_tables = 1` vs 3 with 0; the same for a
chain `ids AS s, s AS s2`). An alias to a column (`WITH b AS s ... b IN s`)
still keeps the parallel read of the table.

Found by the second-model review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reading the table with parallel replicas marked the query context
distributed as soon as the table was replaced, and everything the query
resolves afterwards inherits that state, so another source of the query
lost its own cluster read (`canReplaceClusterEngineWithClusterVariant`)
while the query was then rolled back to a local read anyway. The check
before the replacement tried to find such sources in advance, but every
expansion the analyzer does later hides one: after the subqueries, CTEs,
aliases and `IN` table names of the previous commits, the automated
review found a `WITH` lambda and a SQL UDF (measured on 7131a0b, 3
replicas, `Shards` of the initial query with
`parallel_replicas_for_object_storage_tables` 1 vs 0, results equal):

- `WITH x -> x IN (SELECT a FROM s3(...) SETTINGS max_threads = 2) AS f
  SELECT count() FROM t WHERE f(a)`: 0 vs 3
- the same lambda passed to `arrayExists(f, [a])`: 0 vs 3
- a SQL UDF with that body, and a UDF calling it: 0 vs 3
- a lambda over a DataLakeCatalog (Iceberg REST) table: 0 vs 3

A replaced table is now read like the table itself during analysis: it
does not mark the query distributed, so the other sources resolve
exactly as without the setting, and the final rollback keeps deciding on
the fully resolved tree. The check before the replacement is removed.
A subquery of a query with a replaced table still reads its tables
itself, as before. All the shapes above now read like with the setting
disabled, and so do the subquery/CTE/alias/`IN` shapes of the previous
commits (also over the catalog table).

As for MergeTree parallel replicas, server constants of such a query are
now computed on the initiator, so `SELECT hostName(), count() FROM t
GROUP BY 1` returns the same row as a local read instead of one row per
replica. Marking the query distributed only once the replacement is kept
was tried first and does not work: the constants are already folded
then, and the initiator keeps the folded `hostName()` as a GROUP BY key
while the shipped query drops it (`NUMBER_OF_COLUMNS_DOESNT_MATCH`).

A scalar subquery over another source no longer prevents the parallel
read: it is executed during analysis, so
`WITH (SELECT max(a) FROM s3(...)) AS m SELECT count() FROM t WHERE a <= m`
now reads both with parallel replicas (05441 line 82: 0 -> 1).

05441 adds the lambda and the SQL function shapes, which fail without
this commit, and a server constant in GROUP BY.

Reported by the automated review on ClickHouse#127138.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
if (table_node->isTemporaryTable() || !scope.context->canReplaceClusterEngineWithClusterVariant())
return;

/// The cluster read does not support `PREWHERE`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Because the cluster read rejects it: IStorageCluster does not override supportsPrewhere() (false in IStorage), so the planner throws ILLEGAL_PREWHERE on the swapped storage. Without this check, SELECT ... FROM t PREWHERE ... that works today would fail once parallel replicas are enabled.

Master already behaves this way for the table functions (measured on 44cf9c0, Parquet source):

SELECT count() FROM s3('.../data.parquet', 'NOSIGN', 'Parquet', 'a UInt64') PREWHERE a > 10
-- OK: ReadFromObjectStorage, Prewhere filter a > 10

-- same query + SETTINGS enable_parallel_replicas = 1, cluster_for_parallel_replicas = 'pr', parallel_replicas_for_cluster_engines = 1
-- Code: 182. Storage S3 (table _table_function.s3) does not support PREWHERE. (ILLEGAL_PREWHERE)

s3Cluster(...) PREWHERE fails the same way. The replicas read through StorageObjectStorage, which supports PREWHERE, so the cluster read could forward it instead. That would fix both; I can do it in a separate PR and then remove this check.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

While the replacement is rather mechanical, it is inline with automatic cluster table functions, and this is a good change overall.

@alexey-milovidov alexey-milovidov self-assigned this Oct 24, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 24, 2026
Merged via the queue into ClickHouse:master with commit 5ca96fa Oct 24, 2026
179 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 24, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 24, 2026
Since ClickHouse#127138 the `ParallelReplicas` job reads S3 engine tables with parallel replicas.
The S3 reads of the test then run on the replicas, which consult the query condition
cache and skip the row blocks as expected (run 2: one hit, 82497 rows read), but the
initial query's `ProfileEvents` that the test asserts on stay 0. Same tag and reason as
the tests ClickHouse#127138 itself tagged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 26, 2026
…d with parallel replicas

After #127138, a table with an object storage
engine is read over the replicas of `cluster_for_parallel_replicas` through a transient
`StorageObjectStorageCluster`. That read does not go through `ReadFromObjectStorageStep`, so
the objects it consumed were not recorded into `QueryConsumedObjectSets` and nothing marked a
pruned, unpinned or zero-object read. The finalization check fell back to a fresh listing and
cached results that must not be cached, which broke `04545`, `04822`, `04846` and `05411` in
the `ParallelReplicas` stateless tests.

Read the table itself when the query has a consumed-object capture, so the consistent cache
keeps working, and fail closed in `getTaskIteratorExtension` of a parallel replicas table read
if a capture appears after the analysis (a subquery-level cache).

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108721&sha=e10b04b3fc1dd20759dca60d95d7e439b2628c9a&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 28, 2026
…llel replicas

Since ClickHouse#127138 a persistent `S3` table is read over the replicas when parallel replicas are
enabled, so in the `ParallelReplicas` job the `ProfileEvents` of the initial query no longer
count the query condition cache lookups and the skipped row groups of the `t_05339_s3` and
`t_05339_s3_glob` reads, and four lines of the reference read 0. Pin
`enable_parallel_replicas = 0` for every server read of the test, as the `IcebergLocal` reads
already did, instead of tagging the whole test `no-parallel-replicas`.

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 comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-improvement Pull request with some product improvements 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.

Parallel replicas are not used for persistent object storage tables (ENGINE = IcebergS3, S3, ...), only for table functions and DataLakeCatalog tables

4 participants