Repository navigation
Conversation
…mpty A join whose result must be empty because an input it needs rows from is filtered by an `in` conjunct whose set is built and empty no longer reads or builds its other input. Those inputs are the left one of an INNER, LEFT, CROSS or COMMA join and the right one of an INNER, RIGHT, CROSS or COMMA join, in either physical orientation (`swap_streams`, flipped kinds), through nested joins of such kinds. A plan pass at the end of `optimizeTreeSecondPass` collects those sets (walking Expression, Sorting, CreateSetAndFilterOnTheFly and Filter steps, nested JoinStep or IEJoinStep nodes and INNER or LEFT FilledJoinStep nodes down to the PREWHERE of a local source step: MergeTree, Memory, File, URL, S3; including `nullIn` under `transform_null_in`) and stores them on the `JoinStep` or `IEJoinStep`. A RIGHT or FULL filled join is not walked: it also emits the stored rows nobody matched. A remote source is not read: it evaluates its PREWHERE on other servers, each with its own set. Both steps add `EmptySetShortCircuitTransform` to the main streams of the joined pipeline through `addEmptySetShortCircuit`: it finishes without pulling when one set is built and empty, so the join never builds or reads its other input. Totals are never gated. The set collector shared with `FilterTransform` skips sets that can grow while the query runs (`ENGINE = Set`, see `PreparedSets.h`), so neither the gate nor the filter's own empty-set exit, which this change also extends to `nullIn`, takes a one-time decision from them. The filter used to stop on an empty `ENGINE = Set` set for plain `in`; it now reads and filters every block, as `in` evaluation and index analysis already do for such sets. This restores the early stop that a `WHERE x IN (subquery)` above the join had before the filter could be pushed below a window step to the join's input (ClickHouse#110114, issue ClickHouse#123875). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove the hasBuiltEmptySet declaration comment, which repeated the function name. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 7 findings over 1 full pass and 3 delta rechecks) plus my own review. The final delta recheck of this head found nothing.
Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20261004-234300 |
|
Workflow [PR], commit [a917148] Summary: ❌
AI ReviewSummaryThis PR adds a join-output short-circuit so an immutable empty Findings
Final Verdict
|
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…ilds A SEMI join keeps only the rows with a match on the other side, so an empty input on either side makes its result empty, not only the input its kind names. `HashJoin::alwaysReturnsEmptySet` already handles a built empty right side of a LEFT SEMI join, but a RIGHT SEMI join with a left-only `IN (empty set)` condition, a swapped LEFT SEMI join, `ie_join` SEMI joins and a chain over a RIGHT SEMI `Join` table still read the other side. The walk also passes `BuildRuntimeFilterStep`, which join runtime filters (on by default) insert above a hash join's build input and which preserves its input rows. Without it, an empty set filtering the build side of an inner join nested in another join did not reach the outer join, which then built its own right side. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…BY and GROUP BY Filter push-down moves a WHERE condition below these steps when it uses only their pass-through or key columns, so a join input such as `(SELECT DISTINCT ...)`, `(... ARRAY JOIN ...)`, a window subquery (the ClickHouse#110114 push-down), `LIMIT n BY k` or `GROUP BY k` hid the empty `IN` set from the walk and the other side was still read. Each of these steps outputs no rows for an empty input, so the walk now passes them. The filter `query_plan_fuse_filter_into_array_join` moves into a (non-LEFT) ARRAY JOIN is read like a FilterStep. Aggregation is passed only with keys and without grouping sets: keyless aggregation and a `()` grouping set output one row for an empty input (measured: `GROUP BY GROUPING SETS ((k), ())` over an empty table returns 1 row). No query reaches those exclusions today (push-down never moves a filter below them, and an `IN` subquery written inside such a subquery adds a CreatingSets step that stops the walk), so they are kept for the invariant, not covered by a test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…H TOTALS `filterPushDown` moves the `IN` filter below `MergingAggregatedStep` and `TotalsHavingStep` too, so the walk now passes them: a keyed, non-grouping-sets merge of partial aggregates outputs nothing for an empty input (the same rule as `AggregatingStep`), and `TotalsHaving` emits rows on its main output only for input rows; its totals row goes to the totals port, which the gate leaves open. Covered: a two-stage `GROUP BY` subquery over remote shards (`MergingAggregated` -> `Filter` -> `ReadFromRemote`), and a `WITH TOTALS` subquery whose totals an outer aggregation drops. Still building the other side, unchanged: a `WITH TOTALS` subquery whose totals reach the join (the join's totals row is joined against the other side), and a distributed read mixing local and remote shards (`Union` stops the walk; its output is empty only when every branch is). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes17 object files changed (+113.11 KiB total), 2 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units111 translation units recompiled, 905 s compile time in total, 109 of them have a recent master baseline. Translation units without a recent master baseline:
|
A row policy such as `k IN (SELECT k FROM t_empty)` on a local MergeTree or Memory table is pushed into the read as its row-level filter, next to PREWHERE, so the walk stopped at the source and the join still read its other input. Read the row-level filter the same way as PREWHERE. A policy kept as a separate filter step (serialized query plan) was already covered, and FINAL (with the policy deferred or not) behaves the same. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| if (array_join->hasElementFilter() && !array_join->isLeft()) | ||
| append(getSetsRequiredByFilter(*array_join->getElementFilter(), array_join->getElementFilterColumnName())); | ||
| } | ||
| else if (const auto * source = dynamic_cast<const SourceStepWithFilter *>(step)) |
There was a problem hiding this comment.
SourceStepWithFilter can also hide the deciding predicate in filter_actions_dag, not only in row_level_filter / PREWHERE. filterPushDown removes the visible FilterStep entirely for ReadFromMerge (src/Processors/QueryPlan/Optimizations/filterPushDown.cpp:1438) by calling ReadFromMerge::addFilter, and that pushed predicate then lives on the step (src/Storages/StorageMerge.cpp:821, src/Storages/StorageMerge.cpp:2533).
In that shape an immutable empty IN / nullIn on the preserved join side still makes the Merge read empty, but collectSets returns here without ever looking at the pushed-down filter, so the outer join still builds/reads its other input. Please also inspect source->getFilterActionsDAG() here (or otherwise descend into ReadFromMerge's hidden filters / child plans) and add a focused stateless ENGINE = Merge case.
There was a problem hiding this comment.
Fixed in c71b311: the walk now reads the filters pushed into ReadFromMerge, with an ENGINE = Merge arm in 05321.
There was a problem hiding this comment.
This fixes the ReadFromMerge-specific path, but the generic hidden-source-filter case from the original finding is still present. In src/Processors/QueryPlan/Optimizations/setJoinEmptyResultSets.cpp:105 the source branch still only inspects row-level filters, PREWHERE, and ReadFromMerge::getPushedDownFilters(): it never looks at source->getFilterActionsDAG() (src/Processors/QueryPlan/SourceStepWithFilter.h:81).
That matters because optimizeLazyFinal can absorb the deciding predicate into exactly that field by calling non_final_reading->addFilter(...) and applyFilters() (src/Processors/QueryPlan/Optimizations/optimizeLazyFinal.cpp:243 and src/Processors/QueryPlan/SourceStepWithFilter.cpp:90) before setJoinEmptyResultSets runs (src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:840 / src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:933). So a join input like SELECT ... FROM t FINAL ... WHERE k IN (SELECT ... FROM t_empty) can still miss the short-circuit and build/read the other join side.
Please also collect sets from source->getFilterActionsDAG() here and add a focused stateless FINAL arm.
`filterPushDown` moves a WHERE above `ReadFromMerge` into the step (`ReadFromMerge::addFilter`), which applies it in every child read, so no filter step was left for the walk to see and the join still read its other input. Read those pushed-down filters like PREWHERE. A Merge table over a remote table stays excluded by the existing remote check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| if (prewhere && prewhere->need_filter) | ||
| append(getSetsRequiredByFilter(prewhere->prewhere_actions, prewhere->prewhere_column_name)); | ||
| /// `ReadFromMerge` applies the filters pushed into it to every table it reads. | ||
| if (const auto * merge = typeid_cast<const ReadFromMerge *>(source)) |
There was a problem hiding this comment.
ReadFromMerge row-policy filters with IN subqueries are still invisible here. This branch only inspects getPushedDownFilters(), but ReadFromMerge::RowPolicyData::addFilterTransform installs the effective policy as a FilterStep plus DelayedCreatingSetsStep in each child plan (src/Storages/StorageMerge.cpp:2106 and src/Storages/StorageMerge.cpp:2352) specifically so the set builders also exist for FINAL and engines that cannot apply the predicate as a source filter.
So an ENGINE = Merge join input whose row policy is USING k IN (SELECT ... FROM t_empty) can still be deterministically empty while the join continues to build/read the other side. Please surface that filter here too, or explicitly narrow the advertised row policy / Merge support and tests.
The `assert_full_read` arms assert `read_rows = 100000`. When `merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability` fires on a multi-stream read (it is skipped when `use_query_condition_cache` is on), the part is split into primary key layers and the granule on each layer border is read by both neighbouring layers, so `read_rows` exceeds the row count while the result stays exact. A 100000-row table only gets several streams on object storage, hence the failure in the s3 storage job only (101870 = 2 extra granules of 935 rows). Clamp the injection probability to 0 for this test, as 05255_statistics_part_pruning_row_policy does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| if (!leftInputEmptiesJoin(table_join.kind(), table_join.strictness())) | ||
| return; | ||
| } | ||
| else if (!emptyInputEmptiesOutput(step)) |
There was a problem hiding this comment.
collectSets still misses the ReadFromLocalParallelReplicaStep wrapper, so the new join gate disappears as soon as the filtered input is executed through local parallel replicas. filterPushDown can sink the deciding predicate into that wrapper (src/Processors/QueryPlan/Optimizations/filterPushDown.cpp:1440), and ReadFromLocalParallelReplicaStep::addFilter stores it inside the nested local QueryPlan instead of as a normal child (src/Processors/QueryPlan/ReadFromLocalReplica.h:22, src/Processors/QueryPlan/ReadFromLocalReplica.cpp:34). Since setJoinEmptyResultSets runs after considerEnablingParallelReplicas (src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:967) but this walk only follows node.children, a join on a parallel-replica read still builds or reads its other side even when an immutable empty IN already forces this side empty.
Please descend into read_from_local->getQueryPlan()->getRootNode() here, and add a focused coverage case without the no-parallel-replicas escape hatch.
CI finish ledger - 447af39Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261011-053007 |
…n-left-in-set-is-empty Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Fixing PR for Performance Comparison (amd_release, master_head, 3/6) This is code placement, not this PR: |
CI finish ledger - a917148Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261011-110002 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
JOINwhose result has to be empty because the query'sWHERE ... IN (subquery), or a row policy with such anIN, filters an input it needs rows from (the left side ofINNER,LEFTandCROSS JOIN, the right side ofINNER,RIGHTandCROSS JOIN, either side of aSEMI JOIN, also through a chain of such joins) no longer reads or builds its other input when the subquery returns no rows, for every join algorithm. This restores the 26.6 speed of queries that filter a windowPARTITION BYkey with such anINabove a join, which 26.8 pushes below the window to the join. Closes #123875.Description
#123875: with
WHERE c1 IN (subquery)on a windowPARTITION BYkey above aLEFT JOINand an empty subquery, 26.6 returns at once; 26.8 first builds the right side.FilterTransformstops once aninconjunct's set is built and empty, but only when its output is needed. On 26.6 theWHEREstayed above the window, closing the join's output first. #110114 lets it pass the window; join push-down moves it to the join's left input, which a hash join reads only after building its right side. A plainLEFT JOINof this shape was already slow on 26.6.Change:
JoinStepandIEJoinStepthe immutablein/nullInsets whose emptiness empties the join: those filtering its left (INNER/LEFT/CROSS/SEMI) or right input (INNER/RIGHT/CROSS/SEMI), throughExpression,Sorting,Filter,DISTINCT,ARRAY JOIN(with its element filter), window,LIMIT BY,GROUP BYkeys (also two-stage),WITH TOTALS, runtime filter builds,full_sorting_merge's set filter and nested such joins (direct/ENGINE = Joinincluded) to a local table'sPREWHERE, row policy orMergetable filter.EmptySetShortCircuitTransformto their main outputs: if one set is built and empty when first pulled, it finishes unread. Totals are not gated; anENGINE = Setset can grow during the query, so neither the gate norFilterTransform's empty-set exit uses it (master's did, forin).INinside a FROM subquery or aMergechild table's row policy; keyless/grouping-sets aggregation, partial aggregate projections,LIMITorUNIONbelow the join; filtered-side totals reaching the join; block nested loop joins.Validation: the issue queries build 0 instead of 2,000,000 right rows. The new test fails on master for 39 shapes, passes 50/50 randomized; 28 mutations fail it. A 1,488-test join/
INA/B changes nothing else. Perf testjoin_left_in_empty_set.xml.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/123927]