Repository navigation
Short-circuit constant-false JOINs at the query-plan level - #110234
alexey-milovidov merged 6 commits into
Conversation
Add a query-plan pass that detects a JOIN whose result (or one input) is provably empty and avoids reading the non-contributing side: - INNER/CROSS/SEMI with a constant-false ON condition (or an empty input) is replaced by an empty source. - LEFT/RIGHT (ALL/ANY/ANTI) with a constant-false ON condition has its null-side input replaced by an empty source; the join still synthesizes the NULLs, so results are unchanged. - FULL collapses to empty only when both inputs are already empty. A constant-false ON condition arises from generated SQL and from predicate folding (e.g. ON a.x = b.y AND a.t = 'A' AND a.t = 'B'). Previously the plan executed the join and read the non-contributing side in full only to produce an empty (or NULL-extended) result. The pass runs before filter push-down so the folded condition is still visible on the logical join step, and only a genuine ReadNothing input is treated as empty (a constant-false FilterStep is not, because a WITH TOTALS/ROLLUP/CUBE aggregation below it still emits the totals row). Gated by the new setting query_plan_short_circuit_constant_false_join (default enabled). Related: ClickHouse#110225 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
cc @vdimir @novikd — could you review? Query-plan pass on |
|
Workflow [PR], commit [c7e7859] Summary: ✅
AI ReviewSummaryThis PR adds a first-pass query-plan optimization that replaces non-contributing Findings
Final Verdict
|
|
Agreed, waiting on #108289 makes sense. Two reasons:
I'll hold this PR and rebase onto the |
…uit-constant-false-join
…ouse#108289 design Detect the constant-false ON condition and empty inputs on the logical join step (where they are still visible, before splitFilter lowers them), but keep the JoinStep in place and only replace the input sides that cannot contribute a row with an empty ReadNothing source. This preserves join validation (an invalid constant join over a Join-engine table still throws instead of being silently short-circuited, fixing the 02498_storage_join_key_positions regression the previous whole-join-replacement approach introduced) while still avoiding the read of the non-contributing side. The runtime ConstantJoin from ClickHouse#108289 only cancels the probe side after the build side is filled, so the build side of a LEFT/LEFT ANTI join over a large right table was fully read; this optimization removes it from the plan (read_rows 20000010 -> 10 for such queries). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…harden test
- Move the query_plan_short_circuit_constant_false_join settings-history entry to
the 26.8 block with {false, true} so `compatibility` before 26.8 restores the
pre-feature behavior (it was mis-recorded as 26.7 {true, true}).
- Drop the empty-input trigger: an empty JOIN input rarely reaches the pass as a
bare ReadNothingStep (it is wrapped in Filter/BuildRuntimeFilter steps), so the
branch was effectively dead and untestable. Scope the optimization to the
constant-false ON condition, which is what issue ClickHouse#110225 is about.
- Test: add an assertion that the setting = 0 disables the pass, drop the dead
empty-input rows, and fix the declaration comment (the JoinStep is kept, inputs
are emptied - it is not replaced wholesale).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
ReadNothingStep is not serializable to remote workers, so inserting it into a plan built with make_distributed_plan makes a valid constant-false join fail with SUPPORT_IS_DISABLED. Skip the optimization when make_distributed_plan is set (the pass still runs on each fragment's local plan), mirroring the existing guards in optimizeTopK and useVectorSearchWithQuantizedCodes. Add a distributed regression test over a populated table, and fix the two stale test comments. Also trim the function doc comment to the local invariant (per-kind behavior moved here): a "preserved" side is one whose unmatched rows are still emitted (left of LEFT/FULL, right of RIGHT/FULL, none for SEMI). INNER/CROSS/SEMI empty both inputs; LEFT/RIGHT ALL/ANY/ANTI empty only the non-preserved side; FULL drops nothing. A JoinStepLogicalLookup input is never detached (it drives physical build and StorageJoin/dictionary validation). Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@antaljanosbenjamin #108289 merged, so I rebased and reworked this. One thing worth flagging: reading the folded value from So I kept detection on Also gated off for distributed plans ( |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-1:20260724-161200 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 11 findings across 4 rounds; bounded: 1 full pass + fix rounds + delta rechecks).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-1:20260724-161200 |
…istributed_plan query The functional-test users profile (tests/config/users.d/limits.yaml) sets max_rows_to_group_by = 10G by default. make_distributed_plan refuses any aggregation when max_rows_to_group_by != 0 (makeDistributed.cpp: a global GROUP BY limit cannot be enforced once aggregation is split per bucket), so the test's SELECT count() distributed-plan query threw SUPPORT_IS_DISABLED. This was deterministic under the test profile (Fast test runs with --no-random-settings), not a randomization flake. Pin max_rows_to_group_by=0 on that query, mirroring the existing parallel-replica pins. Co-Authored-By: Claude Opus 4.8 <[email protected]>
| auto * side_node = parent_node->children[side]; | ||
| if (typeid_cast<const ReadNothingStep *>(side_node->step.get())) | ||
| return 0; | ||
| if (typeid_cast<const JoinStepLogicalLookup *>(side_node->step.get())) |
There was a problem hiding this comment.
This blanket JoinStepLogicalLookup skip still leaves the non-contributing side readable for key-value/direct lookups. tryMakeDirectJoinWithMergeTree and dictionary/RocksDB joins also wrap the right side in JoinStepLogicalLookup, but for a constant-false ON the planner picks ConstantJoin before the direct-join path (PlannerJoins.cpp), and ConstantJoin keeps the default FillRightFirst pipeline. Because this branch leaves the lookup child attached, we still execute the whole lookup child plan instead of dropping it, so queries like LEFT JOIN ... SETTINGS join_algorithm = 'direct' ON 1 = 2 still scan the right MergeTree/dictionary side. That breaks the PR's stated "non-contributing side is not read" contract for this family of joins. I think this needs a narrower skip (storage_join only) or a separate fast path for storage_key_value lookups, plus a regression test on the JoinStepLogicalLookup/DIRECT path.
There was a problem hiding this comment.
Verified this against the code and a local build (head c7e7859). The headline is not accurate for MergeTree, but there is a real, narrow point for KV/dict sources.
Layering: JoinStepLogicalLookup is a logical plan node built in the planner; ConstantJoin is the runtime algorithm chosen later. They are different layers.
- MergeTree "direct" case is already fixed.
tryMakeDirectJoinWithMergeTreeonly fires for a single equi-predicate (join_operator.expression.size() != 1 -> return,predicate_type != Equals -> return), so a constant-falseONnever produces aJoinStepLogicalLookupfor a MergeTree right side. The right side is a plain read and my pass empties it:
LEFT JOIN r_bt(MergeTree, 2M) ON k=k AND 1=2, join_algorithm='direct'
fix ON : right = ReadNothing
fix OFF: right = ReadFromMergeTree (Parts: 2, Granules: 245)
-
StorageJoin (
Engine=Join) must keep the lookup step. A constant-falseONthere throwsINCOMPATIBLE_TYPE_OF_JOINboth with the fix on and off. Keeping theJoinStepLogicalLookupis what preserves that validation (this is the 02498_storage_join_key_positions case). -
Dictionary / RocksDB / other key-value sources: you are right. The right child stays
JoinStepLogicalLookup -> ReadFromStorage(...)andConstantJoin's FillRightFirst still fills it. Results are correct (I checked on/off), so this is a missed micro-optimization, not a contract/correctness bug, and the build side there is in-memory and cheap.
The narrow skip you suggest is not a plain child swap, though: buildPhysicalJoinImpl recovers the storage via typeid_cast<JoinStepLogicalLookup *>(children.back()) and calls table_join->setStorageJoin(...). Replacing that child with ReadNothing makes the cast null and drops the storage metadata plus its validation - the exact regression the keep-JoinStep design avoids. Emptying the KV data source while still threading prepared_join_storage into TableJoin is a separate fast path.
Given the primary issue (#110225) is fixed and the KV case is correct + cheap, I would keep it out of this PR and do the KV-source short-circuit as a scoped follow-up rather than expand this change. Fine to do it here instead if you prefer.
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds a query-plan pass that short-circuits a JOIN whose ON condition folds to constant false, so a non-contributing input side is not read. ClickBench queries are single-table scans with no joins, so the optimization never fires on any flagged query. Q15's flagged -19.9% improvement is therefore off-path and was downgraded to not-sure, and Q4's -27.6% shift is correctly suppressed within master's current variance band. No real PR-attributable change is visible in these benchmarks. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 65/66 (98.48%) · Uncovered code |
CI finish ledger — c7e7859CI is fully finished and GREEN on this head (Finish Workflow SUCCESS, mergeable=CLEAN, 0 failing checks). The PR-caused No outstanding failures — every check passes or skips. The post-#108289 rework (keep the JoinStep, replace only the non-contributing input subtrees with a header-preserving Session id: cron:our-pr-ci-monitor:20260725-020000 |
| /// Must run before `splitFilter`/`pushDownFilter`, which lower the constant off the join step. | ||
| size_t tryShortCircuitConstantFalseJoin(QueryPlan::Node * parent_node, QueryPlan::Nodes & nodes, const Optimization::ExtraSettings & settings) | ||
| { | ||
| /// `ReadNothingStep` is not serializable to remote workers, so skip distributed plans. |
There was a problem hiding this comment.
Acknowledged. I will send a separate PR making ReadNothingStep serializable (isSerializable() plus serialize/deserialize and registry entry, with round-trip test coverage), and link it here.
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is a very good change, LGTM.
ReadNothingStep never overrode isSerializable(), so it inherited the conservative false default from IQueryPlanStep and was absent from QueryPlanStepRegistry. assertFragmentSerializable therefore rejected any multi-stage distributed plan fragment containing it: Code: 344. make_distributed_plan cannot distribute this query: step 'ReadNothing' in stage 'stage_0' is not serializable for remote execution. The step is planted whenever a source provably yields no rows (PlannerJoinTree, InterpreterSelectQuery, StorageFromMergeTreeProjection, ReadFromMergeTree), so this was not specific to the const-false JOIN short-circuit pass: a distributed aggregation over an empty MergeTree table failed on master. The step's entire state is its output header, which QueryPlan::serialize already writes generically per node before calling step->serialize, so its own payload is empty. Wire it into the existing mechanism following ExtremesStep, taking the header from ctx.output_header as source steps do (ReadFromTableStep), plus the registry entry. No serialization version bump. The step-name registry is self-describing and fail-closed: an older receiver throws UNKNOWN_IDENTIFIER before reading any step body, and the payload is empty so no field can be misparsed. The same query already failed loudly before this change, earlier on the initiator, so a loud failure is replaced by a loud failure and nothing that worked stops working. Every step name added so far landed without touching ProtocolDefines.h; the two existing version constants gate a payload bit inside an existing step, which a name cannot express. Bumping instead would make old receivers reject every plan from a newer initiator, and RemoteQueryExecutor disconnects replicas below the minimum plan version. Scope is serialization only: the make_distributed_plan early return in shortCircuitConstantFalseJoin stays, because a ReadNothing leaf changes what the distributed planner sees on that side (shard list, read-rows estimate, join strategy) and deserves its own change. Its comment and 04512's prose are corrected, since both asserted the claim this commit falsifies. One sibling gap is left deliberately: ReadFromSystemOneStep is equally stateless and fails the same way, but system.one reached via ReadFromStorageStep is already special-cased as serializable, and that step lives in clickhouse_storages_system, which is not linked to the query-plan module, so registering it is a layering decision. Follow-up to ClickHouse#110234.
…cuit-constant-false-join Short-circuit constant-false JOINs at the query-plan level
The constant-false ON short-circuit (ClickHouse#110234) replaces every input the join kind does not preserve with ReadNothing. No row of such an input reaches the output, but the join builds its totals row from the totals of both inputs (joinPipelinesRightLeft), and that stream does not go through ON. So a `WITH TOTALS` input lost its totals row (or got defaults for it) since 26.8. The pass now keeps an input whose plan can produce totals: TotalsHavingStep, ReadFromRemote whose shards send totals (stage Complete and a WITH TOTALS shard query, the predicate addPipe/addLazyPipe already used, now one helper), a query result cache hit whose pipe has totals, any of these in a nested plan the step owns (a SQL SECURITY DEFINER view), and ReadFromMerge, whose child plans are built on request and so are not inspected here. The walk stops below AggregatingStep and MergingAggregatedStep, which drop incoming totals, and does not ask LazyReadReplacingFinalStep (one source, no totals). Inputs without totals keep the fast path. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
JOINwhoseONcondition is constant-false (e.g.ON 1 = 2,ON NULL, or a condition that folds to false such asa.t = 'A' AND a.t = 'B') no longer reads the non-contributing side. A new query-plan optimization replaces the input sides that cannot contribute a row with an empty source. Controlled by the settingquery_plan_short_circuit_constant_false_join(default enabled).Description
Closes: #110225
Before this change, a constant-false
JOINstill read the non-contributing side in full. The runtime join can only cancel the probe side once the build side has been filled, so e.g.small LEFT JOIN big ON falsescanned the wholebig(build) side before discovering nothing matches.This adds a first-pass query-plan optimization that detects a constant-false
ONcondition on the logical join step and replaces each input side that cannot contribute a row with an empty source:INNER/CROSS/COMMAandLEFT/RIGHT SEMI: no row can survive, so both inputs are emptied;LEFT/RIGHTALL/ANY/ANTI: only the non-preserved (null) side is emptied; the preserved side still emits its rows with NULL/default columns;FULL: both sides are preserved, so nothing is dropped;ASOF/PASTE/correlated joins are skipped.The logical
JoinStepis deliberately kept in place (never replaced by an empty source), so the logical-to-physical conversion still performs join validation. An invalid constant join (for example over aJoin-engine table) keeps throwing exactly as before.Example (20M-row right side,
ON 1 = 2):read_rowsdrops from 20000010 to 10 forLEFT/LEFT ANTI.The optimization runs before
splitFilter/pushDownFilterlower the constant onto an input, and is gated byquery_plan_short_circuit_constant_false_join(default true, underquery_plan_enable_optimizations).