Skip to content

Fix join filter pushdown - #117542

Open
ianton-ru wants to merge 53 commits into
ClickHouse:masterfrom
ianton-ru:join-filter-pushdown-through-rename
Open

ianton-ru wants to merge 53 commits into
ClickHouse:masterfrom
ianton-ru:join-filter-pushdown-through-rename

Conversation

@ianton-ru

@ianton-ru ianton-ru commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Copy the left-only WHERE of a JOIN onto the subquery that wraps an IStorageCluster table (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) on master for a PREWHERE on a cluster table function on the left side of a JOIN: the PREWHERE moved onto the wrap is folded into its WHERE.

The earlier plan-level JOIN filter push-down part of this PR was removed: master already pushes such a filter below the JOIN and uses PREWHERE for MergeTree (the removed tests 04673 and 04679 pass on master), which is why performance tests showed no difference.

Related: #117542 (comment)

Changelog category (leave one):

  • Performance Improvement

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

A left-only WHERE on 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. A PREWHERE on such a table function in a JOIN no longer throws ILLEGAL_PREWHERE.

icebergCluster file listing

icebergCluster (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 no WHERE, so initiator listing stayed unfiltered. Nested count() of SELECT * … JOIN is the same shape: wrap planning reports WithMergeableState and does not add a FilterStep.

Left-only WHERE / PREWHERE is copied onto the wrap after removeExpressionsThatDoNotDependOnTableIdentifiers and removeExpressionsThatAreUnsafeToDuplicate. Copied columns stay in the wrap projection via collectSourceColumns. Wrap dummy analysis then collects the filter the same way as a single-table icebergCluster read.

The copied wrap WHERE is 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 as canPrefilterJoinSide.

Iceberg min/max lookup is by storage column name. Wrap / analyzer DAGs often use __tableN.col (and wrap subquery planning restarts N). ReadFromCluster remaps listing inputs to storage names and builds the file iterator once at pipeline start, so listing sees bid rather than __table1.bid and prune metrics are not double-counted.

Covered by test_cluster_join_filter_minmax_pruning.py: IcebergMinMaxIndexPrunedFiles for icebergS3Cluster with a plain WHERE, with JOIN … WHERE, and with outer count() of SELECT * … 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]

ianton-ru and others added 20 commits September 1, 2026 11:21
…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]>
@ianton-ru ianton-ru changed the title Fix join filter pushdown- #2249 Fix join filter pushdown Sep 1, 2026
ianton-ru and others added 2 commits September 1, 2026 17:54
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]>
@ianton-ru
ianton-ru marked this pull request as ready for review September 1, 2026 19:22
@zlareb1

zlareb1 commented Sep 1, 2026

Copy link
Copy Markdown
Member

Two observations from reading the diff, both on paths the new tests don't cover.

1. The new alias arm in get_available_columns_for_filter also runs for the partial-predicate path, which cannot remap alias names. The logical_join output-actions loop adds the JOIN-output name (try_add(output_name)) with the comment "fix_predicate_for_join_logical_step remaps it" — true for the main split path, but the same lambda is also called with require_stable_types = true for the disjunctions path, and the pre-existing comment right above those call sites documents that addFilterOnTop builds the partial FilterStep directly against the join input header without fix_predicate_for_join_logical_step. The require_stable_types arm checks that the resolved input exists in input_header and that types are stable, but it still adds output_name, not the resolved input name. So when the two differ (the aliased case, which is the only case where this arm adds anything the plain input loop didn't), tryToExtractPartialPredicate can extract a conjunct against a name that is absent from the child stream header, and ActionsDAG::updateHeader raises a NOT_FOUND_COLUMN_IN_BLOCK exception at plan time. A mixed-side disjunction over an aliased column — the shape SELECT count() FROM t1 JOIN t2 ON ... WHERE (t1.a < 40) OR (t1.a > 90 AND t2.c = 1) with the left side exposing a under a different output name — would go from working to failing, at default use_join_disjunctions_push_down = 1. Since the arm is either redundant (names equal) or unmappable (names differ) under require_stable_types, the simplest fix seems to be skipping the alias arm when require_stable_types is set — or remapping to resolved.getColumnName() and adding a disjunction-plus-alias test either way.

2. isSafeToDuplicateInQueryTree lets IN with a node-local table through. The keep-predicate excludes nondeterministic, stateful, server-constant, dictGet and joinGet functions, and walkOrdinaryFunctions rejects QUERY/UNION subtrees — but the set argument of in/globalIn can be a TABLE or TABLE_FUNCTION node, which passes the walk, and FunctionIn is deterministic. So a conjunct like k IN local_set_table gets copied into the wrap query and shipped to the other nodes. If the table doesn't exist on a worker, a previously working query starts failing with an unknown-table exception; if it exists with different content, the shipped pre-filter drops rows the initiator's own IN would keep — silent row loss. This is exactly the node-local class the comment block gives as the reason for excluding dictGet and joinGet. Suggest dropping in-family conjuncts whose set argument is a table or table function (constant-tuple IN must of course stay — it is the main pruning payload); functionIsInOrGlobalInOperator from Interpreters/misc.h is already available here.

@Algunenano Algunenano added comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... can be tested Allows running workflows for external contributors labels Sep 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e29f89b]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan) FAIL
Logical error: 'this->use_count() == 1' (STID: 2508-3795) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR copies safe, table-local WHERE predicates into remote JOIN wraps so cluster table functions can prune files on the initiator, and preserves supported explicit PREWHERE clauses as wrap WHERE. Review of head e29f89bb828e7da004d56ca4e3636a77c416cb3e found one remaining wrong-result case: copying a predicate can change the input observed by a stateful JOIN ON condition.

Findings

❌ Blockers

  • src/Planner/PlannerJoinTree.cpp:1985–1987: The copy guards inspect stateful functions in WHERE and ARRAY JOIN, but omit intervening JOIN ON expressions. With a single worker, a fileCluster source containing n = 0, 1, 2, and a Memory table r containing the same keys, INNER JOIN r ON l.n = r.n AND rowNumberInAllBlocks() = 1 WHERE l.n = 1 returns 0. Both the explicit-subquery form of the left source and query_plan_filter_push_down = 0 return 1, with max_threads = 1, max_block_size = 100, join_algorithm = 'hash', join swapping and runtime filters disabled. The copied l.n = 1 removes the preceding row, so the ON condition receives row number zero and rejects the matching row. Skip the entire wrap copy when it crosses stateful JOIN conditions.
Tests
  • ⚠️ Add a focused stateless regression for the stateful JOIN ON case, comparing the direct cluster source with its explicit-subquery form. The existing stateful WHERE and ARRAY JOIN tests do not cover this carrier.
Missing context / blind spots
  • ⚠️ Runtime reproduction used the PR's arm_release binary cca502daa8dd; its complete wrap-copy block matches the reviewed head exactly. The existing 05458_cluster_wrap_stateful_input_stream and 05837_cluster_wrap_stateful_array_join tests also matched their references locally. A build of the current head and the Iceberg/Spark integration test were not run locally; current-head CI would close that validation gap.
Final Verdict

Status: ❌ Block

Prevent wrap prefiltering across stateful JOIN ON conditions and add the focused regression.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 2, 2026
Comment thread src/Analyzer/Utils.cpp Resolved
@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

This is a master bug, not caused by this PR. The fix is in progress in #112890 (Closes #124823).

The fuzzer changed id to Date32 (PARTITION BY id) and number to Time64(3). IN casts the key into the set's type, and a Date32 cast to Time64(3) is 00:00:00.000 for every date, so every row matches the element 0. Index analysis casts the elements into Date32 instead: all ten become 1970-01-01, so only that partition is read. The LIMIT without ORDER BY is not a factor: the set has 10 distinct values, and the result is the same without the LIMIT.

Measured with clickhouse local on master 1df150b with the same tables: the IN / NOT IN / isNull arms return 2 / 0 / 0 of 200 rows. With #112890 applied, they return 200 / 0 / 0.

The current head of #112890 has not had a full CI run: the 2026-10-16 master build break (fixed by #126269) failed Build (arm_tidy) there, and the other jobs were skipped.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 4 commits November 3, 2026 10:07
…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]>
alexey-milovidov and others added 2 commits November 14, 2026 16:48
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (2026-11-14). The merge had no textual conflicts, but master changed the node_name_to_input_node_column parameter of ActionsDAG::buildFilterActionsDAG to UnorderedMapWithMemoryTracking, so IStorageCluster.cpp no longer compiled. Fixed in c6ace4a55540. The previous head had green CI and there are no unresolved review threads.

…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`.
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 18, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (2026-11-20) with no conflicts. The files this PR changes compile against the new master.

The only red check on the previous head (2f4a171c) was AST fuzzer (amd_debug): Logical error: Sort order of blocks violated for column number 1 (STID 3413-395e). It was raised in CheckSortedTransform inside a background merge (MergeTreeBackgroundExecutor), not in a query plan. This PR only changes JOIN filter push-down and the IStorageCluster JOIN wrap, so it did not cause this failure. The same class of bug is tracked in #93139.

@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.

@groeneai

Copy link
Copy Markdown
Collaborator

I checked this run's server.log. The merging table is default.t_nullable__fuzz_3 (ts Int128) ORDER BY toDate(ts) DESC: the fuzzer took t_nullable from 05293_key_condition_monotonic_transform_strict_bounds and changed ts from Nullable(DateTime('UTC')) to Int128. toDate of an integer above 65535 reads it as a Unix timestamp in the implicit time zone. The test sets session_timezone = 'UTC' and the server ran in Europe/Amsterdam, so the INSERT sorted the parts by UTC dates, and the merge recomputed the key in Amsterdam time, where the 23:00 UTC rows fall on the next day.

It reproduces on master (debug build ec475edd5e3d) with the server at TZ=Europe/Amsterdam:

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 OPTIMIZE aborts with the same message as CI (left: UInt64_20465, right: UInt64_20466. Chunk 23, rows read 24.). Without session_timezone, the table merges.

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 (b8bb3b0ffb1f3), this repro merges with the server in Amsterdam, Tokyo and New York, where master aborts in all three.

#93139 has a different cause: ALTER TABLE ... MATERIALIZE COLUMN rewrites a MATERIALIZED now() column used in the sorting key without re-sorting the part. Its repro still aborts with the #130066 build, and its open fix is #99647.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks, @groeneai. So the AST fuzzer (amd_debug) failure on 2f4a171c comes from the time zone mismatch between INSERT and merge, it is tracked by #130066, and this PR did not cause it. The current head 017464f0 has green CI and no unresolved review threads. Nothing more to change here.

@alexey-milovidov

Copy link
Copy Markdown
Member

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Why the performance tests showed no difference: the plan-level JOIN filter push-down part of this PR did nothing on current master. On CI arm_release builds of master (463f45f, also builds from 2026-09-01 and 2026-10-10), 04673_join_filter_pushdown_count_subquery and 04679_join_disjunction_pushdown_count_subquery already pass. For count() of SELECT * ... LEFT JOIN ... WHERE foo.a < 1000 over a 10M-row MergeTree table, both master and this PR read 2 marks with PREWHERE, with and without join_use_nulls, query_plan_join_swap_table, and enable_join_runtime_filters. No performance test uses a *Cluster table function, which is the part that does change behaviour.

Pushed 6a2d134, which keeps only the IStorageCluster JOIN wrap part:

  • filterPushDown.cpp reverted to master, 04673 and 04679 removed;
  • the JOIN side check used by the wrap moved from Core/Joins.h into src/Analyzer/Utils.cpp (same semantics).

Checked with a binary built from this tree (the four changed .cpp files compiled on a master build and linked): all *_cluster_wrap_* tests give the same results as with the previous head. 05057, 05480 and 05507 fail on master and pass here (05057 is ILLEGAL_PREWHERE on master); 05449 needs WebAssembly UDFs, which my local server does not have. EXPLAIN actions = 1 of the fileCluster versions of the integration test queries, including the outer WHERE datetime >= ... over the JOIN subquery, is identical to the previous head: the filter ends up right above ReadFromCluster.

Comment thread src/Analyzer/Utils.cpp Resolved
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 23, 2026 03:32

AI review of a later commit does not approve the PR, see the AI Review comment.

@stresshouse

stresshouse Bot commented Nov 23, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

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
  • StressHouse run: 1695b233-7a24-4cd8-ab4d-5f21b6577fbc
  • MIRAI run: 982e02d6-10eb-48e0-a1d2-7bd7f73f0003
  • PR check IDs:
    • clickbench_917430_1795407108
    • clickbench_917444_1795407108
    • tpch_adapted_1_official_917454_1795407108
    • tpch_adapted_1_official_917792_1795407123

…`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]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 23, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @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.

Hung check failed, possible deadlock found in Stress test (arm_release) on cca502da. It is not caused by this PR:

This PR changes only the planner and IStorageCluster::read, not StorageTableFunctionProxy or StorageMerge.

Also merged master (2026-11-23, e29f89b) with no conflicts; the four .cpp files this PR changes compile on the merged tree. There are no unresolved review threads.

Comment thread src/Planner/PlannerJoinTree.cpp Outdated
Comment on lines +1985 to +1987
if (filter_push_down_enabled && can_prefilter_wrapped_table && parent_query->hasWhere()
&& !hasStatefulFunctionInExpression(parent_query->getWhere())
&& !hasStatefulArrayJoinOverTable(parent_query->getJoinTreeNode(), original_table_expression))

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.

[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.

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.

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

@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 23, 2026 10:19

AI review of a later commit does not approve the PR, see the AI Review comment.

@groeneai

Copy link
Copy Markdown
Collaborator

The holder is in this run's c_stacktraces.log (thread #1566): a TCPHandler answering a TablesStatusRequest, processTablesStatusRequest -> castStorage<StorageReplicatedMergeTree>(table, DeferredTable::Load) -> StorageTableFunctionProxy::getNestedImpl (holds nested_mutex) -> TableFunctionURL::executeImpl -> format detection -> ReadWriteBufferFromHTTP::waitBeforeRetry. The table is test_2.tablefunc07 (x String) AS url('http://some_addr:9000/nonexistent') from 02888_system_tables_with_inaccessible_table_function: it has no format, so resolving it reads the URL, and some_addr does not resolve. A failed resolution is not cached, so the waiting TCPHandler threads repeat it one after another (180 TCPHandler errors Not found address of host: some_addr in the server log, about two per minute). A TablesStatusRequest has no process list entry, so nothing cancels it.

The requests come from ATTACH DATABASE ___fuzz_1 ... ENGINE = Remote('127.0.0.{4,5,6}:9000', currentDatabase()), which the server-side AST fuzzer made from 02888's CREATE DATABASE test_2. A table lookup in that database calls getStructureOfRemoteTable, which sets the main table, so the connection first sends a TablesStatusRequest for test_2.tablefunc07 to this same server. #133292 has the same shape: ENGINE = RemoteSecure('127.0.0.{2..4}:9440', currentDatabase()) over test_5, holder again in TableFunctionURL.

It started on 2026-11-21 because #131994 (merged 2026-11-20 18:21 UTC) gives a fuzzed CREATE DATABASE its own name, so these databases now get created. This run's server log has 19 fuzzed CREATE/ATTACH DATABASE ___fuzz_N queries; the Stress test (arm_release) log of #131027 from 2026-11-20 16:51 UTC has none. The server bug is older: processTablesStatusRequest loads a deferred table since #121332 (2026-10-02), and for a table-function proxy that means executing the table function, which can never give a ReplicatedMergeTree. So I would keep #131994 and fix the server.

The fix is in progress in #113389: at its head f8280dd1 it loads the table in processTablesStatusRequest only when its engine supports replication, so a table-function proxy is not resolved there, and it moves tryGetNested / nestedIfResolved (system.replicas, SYSTEM STOP ...) onto a separate resolved_nested_mutex. If you want this before #113389 is merged, I can send the processTablesStatusRequest change alone as a separate PR.

…`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]>

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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants