Repository navigation
Fix join filter pushdown - #117542
Fix join filter pushdown#117542ianton-ru wants to merge 53 commits into
Conversation
…in header Unused-column removal and `JoinStepLogical` aliases can hide a one-sided `WHERE` from `get_available_columns_for_filter`. Include those names so existing split and remap can push the predicate under the JOIN. Co-authored-by: Cursor <[email protected]>
…r can prune files Initiator listing runs on the wrap subquery (`SELECT cols FROM icebergCluster`), which previously had no WHERE. A left-only predicate on `count()` of `SELECT * … JOIN` never reached min/max file listing. Co-authored-by: Cursor <[email protected]>
Drop the duplicated WHERE walker and the PK-walk-through-JOIN remapping. Wrap listing still uses collectFiltersForAnalysis and tryAddClusterWrapFilter. Co-authored-by: Cursor <[email protected]>
…JOIN Copying a table-local WHERE such as `isNull(r.x)` under a LEFT JOIN remote right table changes join semantics. Use the same `isLeftOrFull` / `isRightOrFull` sides as JOIN filter pushdown. Related: Altinity#2249 Co-authored-by: Cursor <[email protected]>
Share the existing `and`-conjunct filter in Analyzer/Utils so wrap copy can drop `rand` and similar after the table-local strip. Those conjuncts stay only in the original WHERE above the JOIN. Related: Altinity#2249 Co-authored-by: Cursor <[email protected]>
…wn test `SET enable_parallel_replicas = 0` already pins the EXPLAIN plan, so skipping the ParallelReplicas suite is not needed. Co-authored-by: Cursor <[email protected]>
Prefiltering those sides changes nearest-match and positional pairing. Skip the same sides for wrap listing so icebergCluster cannot drop the matching file either. Co-authored-by: Cursor <[email protected]>
Functions such as `aiEmbed` and `timeSeriesStoreTags` can be deterministic in a query while still having side effects. Skip them in the cluster wrap the same way JOIN filter pushdown uses `hasStatefulFunctions`. Co-authored-by: Cursor <[email protected]>
Wrap copy restated the same outer/`ASOF`/`PASTE`/`FULL` checks as filter pushdown, and stripped wrap-unsafe conjuncts in two walks. Co-authored-by: Cursor <[email protected]>
…andom settings `EXPLAIN` `Prewhere` is absent when parallel replicas rewrite the plan or when `optimize_move_to_prewhere` / `query_plan_optimize_prewhere` are randomized off. Co-authored-by: Cursor <[email protected]>
`filterConjunctions` skipped a ColumnNode root, so `WHERE r.flag` was copied onto the `IStorageCluster` wrap and planning failed. Related: Altinity#2249 Co-authored-by: Cursor <[email protected]>
`canPrefilterJoinSide` only marks ordinary columns unavailable on the null-producing side. Attaching a rewritten equivalent-key filter to that child is still `allow_push_down_to_right` (dictionary / lookup / `ASOF`). Related: Altinity#2249 Co-authored-by: Cursor <[email protected]>
…te changes The cluster JOIN wrap applies the copied `WHERE` before the optimizer can push an outer filter, so listing used to keep `a` and miss `a AND b`. https: //github.com/Altinity/pull/2249 Co-authored-by: Cursor <[email protected]>
The wrap `WHERE` is sent to remote cluster nodes, where `hostName` can differ from the initiator and drop every row. https: //github.com/Altinity/pull/2249 Co-authored-by: Cursor <[email protected]>
…ion APIs On master, `getLeftTableExpression` / `getJoinTree` return `ITableExpressionNode` references, while `extractTableExpressionsSet` takes `TableExpressionNodePtr`. Co-authored-by: Cursor <[email protected]>
The wrap `WHERE` runs on remote cluster nodes. `dictGet`, `joinGet`, and other non-deterministic functions must stay on the initiator so a missing dictionary or different node-local state cannot drop rows or fail the query. https: //github.com/Altinity/pull/2249 Co-authored-by: Cursor <[email protected]>
…tion `icebergCluster` reports `WithMergeableState`, so wrap planning does not add a `FilterStep`. Dummy analysis of `count()` of `SELECT * … JOIN` can also miss the predicate, leaving listing unfiltered. Co-authored-by: Cursor <[email protected]>
Nested `icebergCluster` JOIN wraps push identifier names after wrap planning restarts table aliases. Iceberg min/max looks up schema names, so listing must see `bid`. Build the file iterator once at pipeline start so a later `applyFilters` does not recount pruned files. Co-authored-by: Cursor <[email protected]>
Wrap JOIN listing copied `__tableN.` stripping and header matching. Share `stripTableQualifier` and `buildFilterActionsDAG` instead. Co-authored-by: Cursor <[email protected]>
Drop extra identifier-map plumbing and overlapping dummy-analysis paths. Wrap dummy analysis of the copied WHERE is enough; listing only strips `__tableN.` locally. Co-authored-by: Cursor <[email protected]>
Ordinary prefilter can change which duplicate `ANY` keeps. Share `isAnyInnerJoin` with filter pushdown so cluster wraps skip that copy while equi-key pushdown stays available. Co-authored-by: Cursor <[email protected]>
|
Two observations from reading the diff, both on paths the new tests don't cover. 1. The new alias arm in 2. |
|
Workflow [PR], commit [e29f89b] Summary: ❌
AI ReviewSummaryThe PR copies safe, table-local Findings❌ Blockers
Tests
Missing context / blind spots
Final VerdictStatus: ❌ Block Prevent wrap prefiltering across stateful |
|
This is a master bug, not caused by this PR. The fix is in progress in #112890 (Closes #124823). The fuzzer changed Measured with The current head of #112890 has not had a full CI run: the 2026-10-16 master build break (fixed by #126269) failed |
…stamps out of the cluster wrap `toUnixTimestamp(String)` and `toDate(UInt64)` use the default time zone of the server that evaluates them, but their types contain no `DateTime`, so the previous guard in `isSafeToDuplicateInQueryTree` let them into the `WHERE` of the `IStorageCluster` JOIN wrap. A worker with a different default time zone then dropped matching rows. Conversions to `Date` / `Date32` (`toDate*`, `CAST`, `accurateCast*`) from a number or a string, and `toUnixTimestamp` of a string or a date without an explicit time zone argument, are now kept on the initiator. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nto the cluster wrap Listing the functions that use the default time zone of the server one by one missed `toRelativeSecondNum(Date)`, `fromUnixTimestamp(UInt64, String)` and others. Now a conjunct is copied into the `WHERE` of the `IStorageCluster` JOIN wrap only when each of its functions belongs to a category that does not use the default time zone (comparison, logical, arithmetic, string, array, ...). Date and time functions, type conversions and functions without a category stay on the initiator, even with an explicit time zone. The check for a zone-less `DateTime` in the argument or result types remains for comparisons such as `dt >= '2024-01-01 00:00:00'`. `05480_cluster_wrap_implicit_timezone_filter` now covers `toRelativeSecondNum`, `fromUnixTimestamp` and a string function that is still copied. Its `log_comment` values get a distinct prefix, so the default `log_comment` of the test (seen with `DatabaseReplicated`) is not counted: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117542&sha=15d0877c228aec2ca05fad1d1879621e9c8051c0&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%202%2F2%29 ClickHouse#117542 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ator `Dynamic` and `JSON` hide the runtime types of their values, so a value can be a `DateTime` without an explicit time zone. A conjunct like `concat(l.v, '') = ...` passed the category allowlist (`String`) and the type check (no visible `DateTime`), so it was copied into the cluster wrap and evaluated in the worker's default time zone. `dependsOnImplicitTimeZone` now treats any `Dynamic` or `Object` in the type tree as depending on the time zone. `05507_cluster_wrap_dynamic_timezone_filter` covers a `Dynamic` column and a `JSON` path. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…for `buildFilterActionsDAG` Master changed the `node_name_to_input_node_column` parameter of `ActionsDAG::buildFilterActionsDAG` to `UnorderedMapWithMemoryTracking`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged |
…n-through-rename Resolve the conflict in `src/Planner/Planner.cpp`: master moved `collectFiltersForAnalysis` into `src/Planner/PlannerSteps.cpp` and exports it from `PlannerSteps.h`, so take master's version, drop the PR's duplicate declaration from `Planner.h`, and include `PlannerSteps.h` in `PlannerJoinTree.cpp`.
|
🕵 Merged The only red check on the previous head ( @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117542&sha=2f4a171c85fe27a71eb2b2f9e731b9db6aecb58a&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. |
|
I checked this run's It reproduces on master (debug build CREATE TABLE t (ts Int128) ENGINE = MergeTree ORDER BY toDate(ts) DESC SETTINGS index_granularity = 1;
INSERT INTO t SELECT toDateTime('2026-01-09 00:00:00', 'UTC') + toIntervalHour(number) FROM numbers(96) SETTINGS session_timezone = 'UTC';
INSERT INTO t SELECT toDateTime('2026-01-09 00:00:00', 'UTC') + toIntervalHour(number) FROM numbers(96) SETTINGS session_timezone = 'UTC';
OPTIMIZE TABLE t FINAL;The The fix is already in progress: #130066 (the INSERT computes the table's keys, skip indexes and TTL in the time zone merges use). With its diff applied on current master ( #93139 has a different cause: |
|
No difference in performance tests, why? |
The plan-level JOIN filter push-down part (`filterPushDown.cpp`) is no longer needed: `master` already pushes a left-only `WHERE` of `count()` over `SELECT * ... JOIN` below the JOIN and uses `PREWHERE` for it. Its tests `04673_join_filter_pushdown_count_subquery` and `04679_join_disjunction_pushdown_count_subquery` pass on `master` without this change (checked with CI builds of `master` from 2026-09-01, 2026-10-10 and 463f45f), and the performance tests show no difference: ClickHouse#117542 (comment) Revert `filterPushDown.cpp` to `master`, drop the two tests, and move the JOIN side check used by the wrap into `src/Analyzer/Utils.cpp` instead of adding it to `Core/Joins.h`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Why the performance tests showed no difference: the plan-level JOIN filter push-down part of this PR did nothing on current Pushed 6a2d134, which keeps only the
Checked with a binary built from this tree (the four changed |
AI review of a later commit does not approve the PR, see the AI Review comment.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…`ARRAY JOIN` Address review: the copied wrap `WHERE` crossed an `ArrayJoinNode` without looking at its expressions. A stateful function in the `ARRAY JOIN` clause (`ARRAY JOIN range(rowNumberInAllBlocks() + 1)`) is evaluated on the rows the wrap returns, so prefiltering the wrapped table changed the number of rows the `ARRAY JOIN` produced: `count()` returned 1 instead of 2. Add `hasStatefulArrayJoinOverTable` and skip copying the `WHERE` when an `ARRAY JOIN` above the wrapped table has a stateful function, the same way it is skipped for a stateful function in the `WHERE` itself. The new test `05837_cluster_wrap_stateful_array_join` returns 1, 2, 1, 2 with the CI binary of 6a2d134 and 2, 2, 2, 2 with this change. ClickHouse#117542 (comment) Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117542&sha=cca502daa8ddf7c290a34c7ea8369c0b7f6aa878&name_0=PR&name_1=Stress%20test%20%28arm_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.
This PR changes only the planner and Also merged |
| if (filter_push_down_enabled && can_prefilter_wrapped_table && parent_query->hasWhere() | ||
| && !hasStatefulFunctionInExpression(parent_query->getWhere()) | ||
| && !hasStatefulArrayJoinOverTable(parent_query->getJoinTreeNode(), original_table_expression)) |
There was a problem hiding this comment.
[Blocker] Preserve the input stream of stateful JOIN ON conditions
These guards inspect WHERE and ARRAY JOIN expressions, but a stateful function in an intervening JOIN ON also observes the rows returned by the wrap. Copying a stateless WHERE below that condition changes its result. The ordinary optimizer leaves the WHERE above the stateful join filter; this rewrite bypasses that barrier.
With one worker, input.tsv containing 0, 1, 2, and a Memory table r (n UInt64) containing the same three keys:
SELECT count()
FROM fileCluster('review_cluster', 'input.tsv', 'TSV', 'n UInt64') AS l
INNER JOIN r ON l.n = r.n AND rowNumberInAllBlocks() = 1
WHERE l.n = 1
SETTINGS max_threads = 1,
max_block_size = 100,
join_algorithm = 'hash',
query_plan_join_swap_table = 0,
enable_join_runtime_filters = 0,
enable_parallel_replicas = 0,
allow_push_predicate_ast_for_distributed_subqueries = 0;This returns 0, while replacing the left source with (SELECT * FROM fileCluster(...)), or setting query_plan_filter_push_down = 0, returns 1. The copied l.n = 1 removes the preceding row, so the ON condition sees row number zero for n = 1 and rejects it.
Please include stateful expressions in intervening JOIN ON clauses in the decision to skip the entire wrap copy, and add a focused stateless regression. Runtime reproduction used PR binary cca502daa8dd; the complete wrap-copy block is identical at head e29f89bb828e.
There was a problem hiding this comment.
Fixed in ce2cacf: the ARRAY JOIN check is now hasStatefulJoinExpressionOverTable and also refuses the wrap WHERE copy when a JOIN that contains the wrapped table has a stateful function in its ON condition. PREWHERE is not affected, because it filters the table read itself, so the stateful condition sees post-PREWHERE rows in either case. Regression: 05871_cluster_wrap_stateful_join_on (your query, plus the (SELECT * FROM fileCluster(...)) variant; both expect 1).
AI review of a later commit does not approve the PR, see the AI Review comment.
|
The holder is in this run's The requests come from It started on 2026-11-21 because #131994 (merged 2026-11-20 18:21 UTC) gives a fuzzed The fix is in progress in #113389: at its head |
…`JOIN ON` A stateful function in a `JOIN ON` condition above the wrapped table (for example `rowNumberInAllBlocks`) sees the rows the wrap returns. Copying a `WHERE` conjunct into the wrap removes rows from that stream and changes the result of the condition. Extend the `ARRAY JOIN` check to `JOIN ON` conditions and rename it to `hasStatefulJoinExpressionOverTable`. Addresses the review comment in ClickHouse#117542 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copy the left-only
WHEREof a JOIN onto the subquery that wraps anIStorageClustertable (icebergCluster,s3Cluster,fileCluster, ...), so the initiator lists only the files that can match (Iceberg min/max and partition pruning) instead of every file of the table.Also fixes
Storage FileCluster ... does not support PREWHERE. (ILLEGAL_PREWHERE)onmasterfor aPREWHEREon a cluster table function on the left side of a JOIN: thePREWHEREmoved onto the wrap is folded into itsWHERE.The earlier plan-level JOIN filter push-down part of this PR was removed:
masteralready pushes such a filter below the JOIN and usesPREWHEREfor MergeTree (the removed tests04673and04679pass onmaster), which is why performance tests showed no difference.Related: #117542 (comment)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A left-only
WHEREon a JOIN with a cluster table function (icebergCluster,s3Cluster, etc.) is now used to prune the list of files on the initiator, including when the JOIN is in a subquery. APREWHEREon such a table function in a JOIN no longer throwsILLEGAL_PREWHERE.icebergClusterfile listingicebergCluster(IStorageCluster) lists files on the initiator. The planner wraps the left cluster table so remotes do not get the JOIN (SELECT cols FROM icebergCluster). That wrap had noWHERE, so initiator listing stayed unfiltered. Nestedcount()ofSELECT * … JOINis the same shape: wrap planning reportsWithMergeableStateand does not add aFilterStep.Left-only
WHERE/PREWHEREis copied onto the wrap afterremoveExpressionsThatDoNotDependOnTableIdentifiersandremoveExpressionsThatAreUnsafeToDuplicate. Copied columns stay in the wrap projection viacollectSourceColumns. Wrap dummy analysis then collects the filter the same way as a single-tableicebergClusterread.The copied wrap
WHEREis also sent to remote nodes, so conjuncts that must stay on the initiator are dropped: nondeterministic, not deterministic in this query, stateful, server-constant (hostName), and node-local (dictGet,joinGet). A bare column from the other JOIN side (WHERE r.flag) is dropped the same way as a function conjunct. Copy is skipped on the same join sides ascanPrefilterJoinSide.Iceberg min/max lookup is by storage column name. Wrap / analyzer DAGs often use
__tableN.col(and wrap subquery planning restartsN).ReadFromClusterremaps listing inputs to storage names and builds the file iterator once at pipeline start, so listing seesbidrather than__table1.bidand prune metrics are not double-counted.Covered by
test_cluster_join_filter_minmax_pruning.py:IcebergMinMaxIndexPrunedFilesforicebergS3Clusterwith a plainWHERE, withJOIN … WHERE, and with outercount()ofSELECT * … JOIN … WHERE. Wrap-copy safety:04674–04678(ASOF/PASTE, stateful, other-side column,hostName,dictGet/joinGet).🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/117542]