Skip to content

Send the filter on a table read by a cluster function to the replicas - #125615

Merged
scanhex12 merged 7 commits into
masterfrom
cluster-function-filter-pushdown-to-replicas
Oct 31, 2026
Merged

scanhex12 merged 7 commits into
masterfrom
cluster-function-filter-pushdown-to-replicas

Conversation

@scanhex12

@scanhex12 scanhex12 commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

In a query with several tables, the replicas of a cluster function read the whole table and sent all rows to the initiator, which applied the filter only after receiving them. The initiator now serializes the deterministic conjuncts of the filter over the read columns as an ActionsDAG, together with the ready sets of IN, and sends it in the internal setting cluster_table_function_pushed_down_filter. The replicas add it as a FilterStep after reading. The initiator still applies the whole filter.

Part 3: #124890

Changelog category (leave one):

  • Improvement

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

...


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

Version info

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

In a query with several tables, the replicas of a cluster function read the
whole table and sent all rows to the initiator, which applied the filter only
after receiving them. The initiator now serializes the deterministic conjuncts
of the filter over the read columns as an `ActionsDAG`, together with the ready
sets of `IN`, and sends it in the internal setting
`cluster_table_function_pushed_down_filter`. The replicas add it as a
`FilterStep` after reading. The initiator still applies the whole filter.

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

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [92f0153]

Summary: ✅


AI Review

Summary

The PR sends eligible object-storage cluster-function filters to replicas to reduce transferred rows. Four previously reported concerns remain at head 92f0153486629ef13f2011a90849ee71dd84e9fa: valid queries can fail during deserialization, client-supplied payloads bypass the binary type-complexity limit, and ready subquery sets are still excluded. These concerns remain in this summary following the author's silent thread resolutions; no duplicate inline comments were posted.

PR Metadata

Improvement is appropriate and requires a changelog entry. The current entry, ..., is insufficient. Replace it with: “Object-storage cluster table functions now apply eligible table-local filters on replicas in queries with multiple tables, reducing data sent to the initiator.”

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available, so the failure cases below were verified by tracing the current code, without fresh runtime reproductions. Focused regression runs would close this gap. CI for the current head was still in progress.
Findings

❌ Blockers

  • src/Storages/IStorageCluster.cpp:118: Compiled lambda bodies are accepted for serialization. Ordinary cluster-function planning does not set PlannerContext::mayBeSerializedForRemoteExecution, so PlannerActionsVisitorImpl::visitLambda can JIT compile a body before this call. With compile_expressions = 1, min_count_to_compile_expression = 0, a predicate such as arrayExists(x -> x > 100 AND x < 1000, [t.id]) can serialize a compiled expression dump as a function name; the replica reconstructs it through FunctionFactory and raises UNKNOWN_FUNCTION. Mark this planning path as serializable before constructing lambdas, or exclude compiled bodies, including constant ColumnFunction carriers. [dismissed by author -- Send the filter on a table read by a cluster function to the replicas #125615 (comment)] The serialization path and lambda compilation guard still leave this case exposed.

  • src/Storages/IStorageCluster.cpp:102: Determinism does not establish deserializability. Deterministic executable and WebAssembly UDFs pass this predicate check, but ActionsDAG::deserialize resolves ordinary function nodes exclusively through FunctionFactory; these UDFs belong to separate factories. A joined cluster-function query with local_udf(t.id) > 0 can therefore start failing with UNKNOWN_FUNCTION, even with the UDF installed on every replica. Require supported function reconstruction recursively, including lambda bodies, and keep unsupported predicates on the initiator. [dismissed by author -- Send the filter on a table read by a cluster function to the replicas #125615 (comment)] The current acceptance check still tests determinism without checking reconstruction support.

  • src/Storages/ObjectStorage/StorageObjectStorage.cpp:914: Client-controlled binary types bypass the configured decoding budget. The new string setting is client-settable. Forwarding it through remote to a view containing a cluster function reaches this deserializer during planning, before task acquisition. ActionsDAG::deserialize receives its default unlimited budget, and QueryPlan::deserializeAndMakeSets explicitly passes zero at SetsSerialization.cpp:347. Thus input_format_binary_max_type_complexity does not constrain these types or nested constant/set data. Pass getBinaryTypeDecodingComplexityLimit through both deserializers and their nested data. [dismissed by author -- Send the filter on a table read by a cluster function to the replicas #125615 (comment)] Neither decoding call now supplies the effective limit, and resetting the setting in ReadFromCluster::updateSettings does not protect this alternate entrypoint.

⚠️ Majors

  • src/Storages/IStorageCluster.cpp:80: The ready-subquery-set acceptance branch is unreachable for normal subquery carriers. PlannerActionsVisitorImpl::makeSetForInFunction marks their constant columns non-deterministic, and building the set does not change that flag. This early rejection runs before the readiness check at lines 92–95, so even complete, already-materialized subquery sets cannot benefit from the promised pushdown. Check immutable ready-set eligibility before rejecting non-deterministic constants, while retaining the deliberate exclusion of mutable Set tables. [dismissed by author -- Send the filter on a table read by a cluster function to the replicas #125615 (comment)] The early rejection and the planner's constant flag remain unchanged.

💡 Nits

  • PR body: replace the required changelog placeholder with the user-facing entry supplied above.
Tests
  • ⚠️ Extend focused stateless coverage with a joined cluster-function predicate containing a compilable lambda and a deterministic UDF; both must preserve successful execution and results.
  • ⚠️ Supply an encoded payload exceeding input_format_binary_max_type_complexity and assert rejection, including nested constant/set types.
  • ⚠️ Exercise an already-built subquery set and verify that its predicate reaches replicas. The added test covers tuple-backed sets only.
Final Verdict

❌ Block. Preserve valid-query execution for compiled lambdas and deterministic UDFs, enforce the decoding limit on both payload components, and address or explicitly narrow the ready-subquery-set contract. Add the focused regression evidence and complete the changelog entry.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). labels Oct 13, 2026
The secondary queries of a cluster function run in the `default` database, so
they are tied to the test through their initial query, which runs in the
current database. Fixes the style check.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125615&sha=797c0c9e561db8719d6261bf06aeea479f53835a&name_0=PR&name_1=Style%20check
PR: #125615

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/IStorageCluster.cpp Resolved
@arsenmuk arsenmuk self-assigned this Oct 14, 2026
scanhex12 and others added 2 commits October 14, 2026 15:30
…pt built subquery sets

Only `StorageObjectStorage` applies `cluster_table_function_pushed_down_filter` on
the replicas, so do not serialize it for `fileCluster` and `urlCluster`.

Also accept `IN (subquery)` sets that are already built with explicit elements:
`serializeReadySets` ships them as values. Sets from `Set` tables are still not
shipped, because the replicas of a cluster function do not necessarily have
the table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/IStorageCluster.cpp Resolved
Comment thread src/Storages/IStorageCluster.cpp Resolved
scanhex12 and others added 3 commits October 23, 2026 15:40
With a randomized `max_insert_threads` > 1, the `INSERT SELECT` into the
`IcebergLocal` table runs several sinks, each committing its own snapshot.
They conflict on `vN.metadata.json`, the loser retries, and
`writeMetadataFile` logs the conflict at `<Error>`, which fails the test
because of stderr. The result is correct. The test is about the filter
pushdown, so insert with a single thread.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125615&sha=b63ba4600a9e2d1d280b641f8de91588e480dcaa&name_0=PR
PR: #125615

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lter-pushdown-to-replicas

# Conflicts:
#	src/Storages/ObjectStorage/StorageObjectStorage.h
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 92f015348 with master 6a363630e (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of db92feff7; 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

7 object files changed (+80.12 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/IStorageCluster.cpp.o 335.32 KiB 376.25 KiB +40.94 KiB (+12.21%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/StorageObjectStorage.cpp.o 600.17 KiB 636.24 KiB +36.07 KiB (+6.01%)

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

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

Job report

@aadant

aadant commented Oct 28, 2026

Copy link
Copy Markdown

@scanhex12 do you think we need to report this Altinity#2602 upstream or this PR addresses the same issue ?

@scanhex12
scanhex12 enabled auto-merge October 31, 2026 18:15
@scanhex12
scanhex12 added this pull request to the merge queue Oct 31, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 31, 2026
@scanhex12
scanhex12 added this pull request to the merge queue Oct 31, 2026
Merged via the queue into master with commit 525761e Oct 31, 2026
178 checks passed
@scanhex12
scanhex12 deleted the cluster-function-filter-pushdown-to-replicas branch October 31, 2026 20:08
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 31, 2026
alexey-milovidov added a commit to ianton-ru/ClickHouse that referenced this pull request Nov 2, 2026
…n-through-rename

Resolve the conflict in `IStorageCluster.cpp`: master (ClickHouse#125615) added
serialization of the filter for replicas in `ReadFromCluster::applyFilters`,
while this branch removed `applyFilters` and builds the task iterator extension
once in `initializePipeline`. Keep `applyFilters` only to compute
`pushed_down_filter`, and keep creating the extension in `initializePipeline`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
scanhex12 added a commit that referenced this pull request Nov 4, 2026
…tting-improvements

Most of this branch landed through separate PRs:
#125611
#125615
#125636
Their versions are kept. Bucket splitting by `min_buckets` is applied on
top of the greedy splitter of master, the weight of a byte range bucket is
capped by the file size, byte ranges are gated by
`cluster_table_function_split_by_split_offsets`, and the duplicate test of
the filter pushdown is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to hinata34/ClickHouse that referenced this pull request Nov 5, 2026
…tion

Since ClickHouse#125615, ReadFromCluster::applyFilters serializes the filter conjuncts
that isSerializableFilterNode accepts into cluster_table_function_pushed_down_filter,
and each replica rebuilds them with ActionsDAG::deserialize. The gatekeeper
also accepted lambda carriers: a constant-folded lambda
(ColumnConst(ColumnFunction)) and a capturing lambda (FunctionCapture). A
lambda body is an ExpressionActions built while the initiator plans the query,
and its constructor JIT-compiles the DAG in place, replacing the nodes with an
LLVMFunction named after CompileDAG::dump(). The serialized filter then carries
that name, and the replica's FunctionFactory::get throws UNKNOWN_FUNCTION once
the body has been compiled (after min_count_to_compile_expression runs).

The planner keeps lambda bodies uncompiled only for plans that are shipped as
a whole (ClickHouse#119332, mayBeSerializedForRemoteExecution). This plan is executed on
the initiator, so refuse Function-typed nodes in the gatekeeper instead. The
check runs before the recursion, so the whole atom stays on the initiator and
the other conjuncts are still sent. The initiator applies the full filter, so
results do not change; the replicas only stop pre-filtering by lambda
conjuncts, as before ClickHouse#125615.

Extend 05394_cluster_function_filter_pushdown_to_replicas with a folded and a
capturing lambda case.

Closes ClickHouse#128422

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 12, 2026
…able function

`ReadFromCluster::applyFilters` (added by ClickHouse#125615) renames the inputs of the
filter it sends to the replicas (`cluster_table_function_pushed_down_filter`)
by pairing output-header column `i` with select expression `i` of the query
sent to them. The initiator reads a `*Cluster` function at
`WithMergeableState`, and for an aggregation the header there is the GROUP BY
keys followed by the aggregate states, not the select list. A key predicate
pushed through `MergingAggregated` (HAVING, or an outer WHERE over the
aggregation) was therefore renamed onto another column: in
`SELECT b, a + 0 AS x, count() ... GROUP BY x, b HAVING x = 2` the replicas
got `b = 2`, filtered the rows of the group `x = 2` out before aggregating,
and the query returned nothing.

Build the filter only when the header is the select list: `WithMergeableState`
with no aggregation and no window functions, the condition under which the
planner's first stage ends with the projection (the same one `StorageMerge`
uses). The initiator applies the whole filter anyway; the replicas no longer
pre-filter an aggregation by a key predicate, which is the behaviour before
ClickHouse#125615. The JOIN case ClickHouse#125615 targets is planned as a projection and keeps
its pre-filtering (05394 still checks that the replicas get the filter there).
The name map keys a column by its own name instead of its select alias: the
filter inputs of the read are renamed to the storage names, so an alias that
is the name of another column (`SELECT a AS b, t.b AS c`) mapped a filter on
`t.b` onto `a`.

Closes ClickHouse#128421

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 15, 2026
…-serialized-plan

Conflicts: `ProtocolDefines.h` (both sides' version 21 entries kept; plan version stays 21, the 26.11 value),
`ActionsDAG.cpp` (master's post-order node walk and `isConstantValueInCacheKey`, with the `IndexHintActions`
parameter), `SelectQueryInfo.h` (master's `QueryPlanStepSerialization` spelling).

Two new call sites of `ActionsDAG::serialize` on master need the parameter: the filter that
`ReadFromCluster` sends to the replicas of a cluster table function (ClickHouse#125615) writes the predicate of
`indexHint` (the replica rebuilds the filter with the same release), and the ActionsDAG deserialization
gtest refuses it (the DAG has no `indexHint`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 15, 2026
…able function

The filter that a cluster table function sends to its replicas (ClickHouse#125615) is built from the conjuncts that
`isSerializableFilterNode` accepts. That check walks the children of a node, but the predicate of `indexHint`
is a separate DAG it does not walk. Writing the predicate there made a query fail that works on master:

    SELECT count() FROM icebergLocalCluster(...) AS t, (SELECT number AS k FROM numbers(1000)) AS n
    WHERE t.a = n.k AND t.a % 2 = 0 AND indexHint(t.a IN (SELECT number FROM numbers(10)))
    -- Code: 344. Cannot ship an IN-subquery set to distributed-plan worker tasks (the set is not built)

On rows `indexHint` is always true, so before this PR the replicas got a hint rebuilt without its predicate
that filtered nothing. Leaving the conjunct out keeps the rows each replica sends unchanged, and the filter is
now serialized with `Refuse`, so a hint that reaches it fails instead of being dropped.

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

comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). 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.

4 participants