Skip to content

Short-circuit constant-false JOINs at the query-plan level - #110234

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/short-circuit-constant-false-join
Jul 26, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/short-circuit-constant-false-join

Conversation

@groeneai

@groeneai groeneai commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

A JOIN whose ON condition is constant-false (e.g. ON 1 = 2, ON NULL, or a condition that folds to false such as a.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 setting query_plan_short_circuit_constant_false_join (default enabled).

Description

Closes: #110225

Before this change, a constant-false JOIN still 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 false scanned the whole big (build) side before discovering nothing matches.

This adds a first-pass query-plan optimization that detects a constant-false ON condition on the logical join step and replaces each input side that cannot contribute a row with an empty source:

  • INNER/CROSS/COMMA and LEFT/RIGHT SEMI: no row can survive, so both inputs are emptied;
  • LEFT/RIGHT ALL/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 JoinStep is 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 a Join-engine table) keeps throwing exactly as before.

Example (20M-row right side, ON 1 = 2): read_rows drops from 20000010 to 10 for LEFT/LEFT ANTI.

The optimization runs before splitFilter/pushDownFilter lower the constant onto an input, and is gated by query_plan_short_circuit_constant_false_join (default true, under query_plan_enable_optimizations).

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd — could you review? Query-plan pass on JoinStepLogical that short-circuits constant-false / empty-input joins (fixes #110225). Runs before filter push-down so the folded ON false is still visible; only a genuine ReadNothing input is treated as empty (a const-false FilterStep is not, to preserve WITH TOTALS rows). Results verified identical with the optimization on vs off across all join kinds.

@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c7e7859]

Summary: ✅


AI Review

Summary

This PR adds a first-pass query-plan optimization that replaces non-contributing JOIN inputs with ReadNothing when the ON condition is constant-false, while keeping the JoinStep alive so later validation still runs. The main remaining issue is that the blanket JoinStepLogicalLookup exclusion leaves a real performance hole: lookup-backed key-value/direct joins still execute the full right-side plan, so the advertised "non-contributing side is not read" contract does not hold for that path.

Findings

⚠️ Majors

  • src/Processors/QueryPlan/Optimizations/shortCircuitConstantFalseJoin.cpp:77 The unconditional JoinStepLogicalLookup skip is too broad. For storage_key_value / direct-lookup joins, this leaves the right child attached; buildPhysicalJoinImpl then marks the join as constant and chooseJoinAlgorithm selects ConstantJoin before the direct-join path, so the plan keeps the default FillRightFirst pipeline and still executes the entire lookup child plan. A constant-false LEFT/INNER join over a direct MergeTree/dictionary lookup therefore still reads the supposedly non-contributing right side.
    Suggested fix: keep the skip only for storage_join lookups that are already filled, or add a separate path for storage_key_value lookups that preserves required validation but detaches the unused child. Add a regression test that exercises the JoinStepLogicalLookup / join_algorithm = 'direct' path.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 13, 2026
@antaljanosbenjamin antaljanosbenjamin self-assigned this Jul 13, 2026
@antaljanosbenjamin

Copy link
Copy Markdown
Member

@groeneai what do you think waiting with this until #108289 is merged? Then we can easily read the value from TableJoin making it easier to detect.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, waiting on #108289 makes sense. Two reasons:

  1. Reading the folded constant from TableJoin is cleaner than my current approach (scanning the JoinStepLogical ON conjuncts and folding each with getFilterResult).

  2. More importantly, doing the short-circuit at the query-plan stage runs it before join validation, so it can bypass ON-expression checks that some storages require. The Fast test here caught exactly that: 02498_storage_join_key_positions expects queries like ... ON key... AND 0, ON 0, ON NULL, ON 1 != 1 against a StorageJoin to throw INCOMPATIBLE_TYPE_OF_JOIN / INVALID_JOIN_ON_EXPRESSION, but collapsing the join to ReadNothing makes them succeed. Detecting the constant after TableJoin is built (past validation) avoids this whole class.

I'll hold this PR and rebase onto the TableJoin-based detection once #108289 lands.

groeneai and others added 4 commits July 24, 2026 16:17
…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]>
@groeneai groeneai changed the title Short-circuit constant-false and empty-input JOINs Short-circuit constant-false JOINs at the query-plan level Jul 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@antaljanosbenjamin #108289 merged, so I rebased and reworked this.

One thing worth flagging: reading the folded value from TableJoin post-validation turned out to be lossy for the primary INNER case. splitFilter's trySplitJoin pushes a source-free const-false conjunct (fromNone()) into a left FilterStep and empties JoinOperator::expression before buildPhysicalJoinImpl runs, so getJoinExpressionValue() reads back true there and the INNER ... ON 0 case is missed.

So I kept detection on JoinStepLogical (it runs first, before splitFilter), but fixed the original regression differently: the pass no longer replaces the whole join. It keeps the JoinStep and only swaps the non-preserved input subtrees for ReadNothing. Physical conversion then still runs join validation, so 02498_storage_join_key_positions (INNER JOIN <StorageJoin> ON 0 must throw) stays green by construction, and the non-contributing side is still not read (read_rows 20000010 -> 10 for LEFT/LEFT ANTI over a 20M right side).

Also gated off for distributed plans (ReadNothingStep is not serializable) and scoped to constant-false only (dropped the empty-input branch as unreachable in practice). Details and the validation gate are in the PR description and the comments below.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. small LEFT JOIN big ON <keys> AND 1=2 over a 20M-row right table: read_rows = 20000010 with the pass off, 10 with it on. On demand, every run.
b Root cause explained? The runtime join cancels only the probe side, and only after the build side isFinished() (JoiningTransform), so the build (right) side of a LEFT/LEFT ANTI join over a large table is read in full even though a const-false ON means no row can match. It is a missing plan-level optimization.
c Fix matches root cause? Yes. A first-pass plan optimization detects the const-false ON on JoinStepLogical and replaces each non-contributing input side with ReadNothing, so that side is never scanned.
d Test intent preserved / new tests added? New test 04512_short_circuit_constant_false_join: EXPLAIN-fires per kind (incl. LEFT/RIGHT SEMI = 2 ReadNothing), setting=0 disables it, read_rows < 1000 perf check, on/off result identity across all kinds, StorageJoin validation preserved, distributed plan not broken.
e Both directions demonstrated? Yes. Without the pass the non-contributing side reads 20000010 rows; with it, 10. Results verified identical on-vs-off across INNER/LEFT/RIGHT/FULL/SEMI/ANTI and join_use_nulls.
f Fix is general across code paths? Yes. One strategy covers all kinds x strictnesses via the preserved/non-preserved rule; ASOF/PASTE/correlated are skipped; a JoinStepLogicalLookup input is never detached (physical build + StorageJoin/dict validation preserved).
g Fix generalizes across inputs? Yes. Const-false is detected via getFilterResult (covers ON 0, ON NULL, 1 != 1, and folded a.t='A' AND a.t='B'); verified across join algorithms (hash/partial_merge/grace_hash/full_sorting_merge/auto) and join_use_nulls in 50/50 randomized runs.
h Backward compatible? Yes. Gated by query_plan_short_circuit_constant_false_join (default true, under query_plan_enable_optimizations); SettingsChangesHistory 26.8 entry {false, true} so compatibility before 26.8 disables it (verified on/off identical).
i Invariants and contracts preserved? Yes. The JoinStep is never dropped, so physical conversion still validates (INCOMPATIBLE_TYPE_OF_JOIN/INVALID_JOIN_ON_EXPRESSION still thrown — 02498 stays green). ReadNothingStep preserves the input header, and only non-preserved sides are emptied, so no emitted (unmatched/defaulted) row is lost.

Session id: cron:clickhouse-author-slot-1:20260724-161200

@groeneai

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ⚠️ Reading the folded value from TableJoin post-validation is lossy: splitFilter pushes a source-free const-false conjunct into a left filter before buildPhysicalJoin, so INNER ... ON 0 is missed AGREE Kept detection on JoinStepLogical (runs first, before splitFilter); did not move detection post-physical
2 ⚠️ Empty inputs never reach the pass as an immediate ReadNothingStep (they are wrapped in Filter/ExpressionStep) AGREE Verified empirically (empty table INNER over 5M read 5M on==off); dropped the empty-input branch, scoped to const-false
3 ❌ Guarding only JoinStepLogicalLookup still bypasses physical join validation (whole-join replacement) AGREE Redesigned: never drop the JoinStep; only replace non-preserved input subtrees with ReadNothing; validation now runs by construction
4 ⚠️ Class-level lookup guard over-excludes dict/KV, not just StorageJoin AGREE Fell out for free: no validation guard needed once the JoinStep is kept; only the pre-existing narrow "don't detach a lookup input" rule remains
5 ⚠️ SettingsChangesHistory entry mis-recorded as 26.7 {true,true} — compatibility can't restore pre-feature behavior AGREE Moved to the 26.8 block as {false,true}
6 ⚠️ Test's WHERE 1=2 empty-input rows don't exercise the optimization AGREE Removed the dead rows (empty-input branch dropped)
7 ⚠️ Test never verifies setting=0 disables the pass AGREE Added an EXPLAIN assertion with query_plan_short_circuit_constant_false_join=0 (no ReadNothing)
8 💡 Declaration comment says "replace the whole join" AGREE Rewrote to "empty non-preserved inputs, keep the JoinStep"
9 💡 PR body used Closes #NNNNN not the full linkage form AGREE Changed to Closes: <full url>
10 ❌ The default-on pass inserts non-serializable ReadNothingStep into distributed plans → SUPPORT_IS_DISABLED AGREE Reproduced; added if (settings.make_distributed_plan) return 0; (mirrors optimizeTopK / useVectorSearchWithQuantizedCodes); added a populated-table distributed regression test
11 ⚠️ The distributed regression test itself can fail under randomized parallel-replica settings (incompatible with make_distributed_plan) AGREE Pinned enable_parallel_replicas=0, automatic_parallel_replicas_mode=0 in that query; 50/50 randomized incl. parallel-replica settings pass
12 ⚠️ Optimization is analyzer-only and skips distributed plans, but the setting doc is unrestricted AGREE Documented the scope in the setting description (analyzer + non-distributed); legacy analyzer rejects the const-false ON syntax outright so nothing to optimize there
13 ⚠️ SEMI branch not proven (test only checks empty SEMI result) AGREE Added explicit EXPLAIN assertions for LEFT SEMI and RIGHT SEMI (2 ReadNothing each)

Severity: ❌ blocker / ⚠️ major / 💡 nit. Every source fix was re-verified (Build-ID changed + both-directions repro + 50/50 randomized). No DISAGREEs this PR.

Session id: cron:clickhouse-author-slot-1:20260724-161200

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements and removed pr-improvement Pull request with some product improvements labels Jul 24, 2026
…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()))

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  1. MergeTree "direct" case is already fixed. tryMakeDirectJoinWithMergeTree only fires for a single equi-predicate (join_operator.expression.size() != 1 -> return, predicate_type != Equals -> return), so a constant-false ON never produces a JoinStepLogicalLookup for 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)
  1. StorageJoin (Engine=Join) must keep the lookup step. A constant-false ON there throws INCOMPATIBLE_TYPE_OF_JOIN both with the fix on and off. Keeping the JoinStepLogicalLookup is what preserves that validation (this is the 02498_storage_join_key_positions case).

  2. Dictionary / RocksDB / other key-value sources: you are right. The right child stays JoinStepLogicalLookup -> ReadFromStorage(...) and ConstantJoin'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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 15 not_sure 234 187 -19.9% <0.0001 This PR only short-circuits JOINs with a constant-false ON condition, but ClickBench Q15 has no join, so the flagged -19.9% improvement is off-path run-to-run variance, not a PR effect.

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
  • StressHouse run: e82d72d7-87c0-4ec6-8943-4d225f47a448
  • MIRAI run: 4c1aa4d1-6b46-432e-8d69-d3b4228370b0
  • PR check IDs:
    • clickbench_227560_1784934900
    • clickbench_227566_1784934899
    • clickbench_227577_1784934900
    • tpch_adapted_1_official_227588_1784934900
    • tpch_adapted_1_official_227603_1784934900
    • tpch_adapted_1_official_227629_1784934900

@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 65/66 (98.48%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c7e7859

CI is fully finished and GREEN on this head (Finish Workflow SUCCESS, mergeable=CLEAN, 0 failing checks). The PR-caused Fast test failure on the prior head (the new 04512_short_circuit_constant_false_join distributed-plan query colliding with the max_rows_to_group_by profile default) was fixed at c7e7859 by pinning max_rows_to_group_by = 0 on that query; it now passes.

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 ReadNothingStep) is CI-green.

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.

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.

@groeneai, send another PR to make it serializable.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alexey-milovidov alexey-milovidov left a comment

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.

This is a very good change, LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Jul 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 26, 2026
Merged via the queue into ClickHouse:master with commit 5cab6f0 Jul 26, 2026
180 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 26, 2026
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Jul 27, 2026
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.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…cuit-constant-false-join

Short-circuit constant-false JOINs at the query-plan level
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 6, 2026
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]>
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 pr-performance Pull request with some performance 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.

Constant-false / empty-input JOIN is not short-circuited — the non-contributing side is still fully read

5 participants