Skip to content

Do not read a JOIN input that cannot contribute under a WHERE no row passes - #123829

Merged
vdimir merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-123702-join-input-under-false-where
Oct 6, 2026
Merged

vdimir merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-123702-join-input-under-false-where

Conversation

@groeneai

@groeneai groeneai commented Oct 4, 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 WHERE that no row passes is pushed to every JOIN input again, including the non-preserved side of an OUTER JOIN and a side with no column used above the join, so that input is no longer read and hash-built for nothing. For example, a UNION ALL branch whose constant column fails the outer WHERE is skipped as in 26.6. Closes #123702, closes #123878.

Description

Since #107084 (26.7) a filter conjunct that reads no column is kept off a join input that push-down is disabled for: pushing it there and dropping it from the post-join filter changes the result when it is NULL (04335) or true but pruning (indexHint). In #123702 such a conjunct comes from a UNION ALL branch whose constant column fails the outer WHERE. It is false for every row, yet the right side of the LEFT JOIN in that branch is read, aggregated and hash-built.

Change, local to that guard: tryPushDownOverJoinStep tells splitActionsForJOINFilterPushDown when no row passes the filter (filterResultForNotMatchedRows with no input defaulted, as the OUTER JOIN conversions use, and the filter is not sensitive to its evaluation count) and the join kind allows filtering one input. That input receives the conjunct, so the join output is empty whatever the other input holds, and the guard is skipped: the disabled input is filtered too, as before 26.7.

Validation, rows read on a debug build: the issue query with compatibility = '24.6' reads 190,104 instead of 22,084,104; the issue's LEFT JOIN view and INNER JOIN branch reproducers read 0 instead of 10,000,000 and 20,000,080, like 26.6. 05320 fails on master and passes 50/50 randomized; its indexHint arm returns 958 instead of 150 when the guard is removed. An A/B over 2,185 join, filter, union and EXPLAIN+JOIN tests changes no reference.

The earlier version of this PR also restored a WITH TOTALS row lost by the constant-false ON short-circuit; that is unrelated to #107084 and goes to a separate PR.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/123829]

Version info

  • Merged into: 26.10.1.1661-master (included in 26.10 and later)
  • Backported to: 26.9.13.10, 26.8.20.12

groeneai and others added 2 commits October 4, 2026 05:35
…passes

Since the constant-conjunct guard of ClickHouse#107084, a no-input conjunct of a filter
above a JOIN is kept off the side the filter cannot be pushed to (the
non-preserved side of an OUTER join, or a side none of whose columns is used
above the join). A UNION ALL branch made false by an outer WHERE on its
constant column (`materialize(k4)` from the UNION conversion) therefore read,
aggregated and hash-built that side in full (issue ClickHouse#123702).

When the filter above a JoinStepLogical is false for every row, replace each
input it cannot be pushed to with ReadNothing, using the helper extracted from
the constant-false ON short-circuit. A `FULL JOIN` under such a `WHERE` has
both inputs replaced. The helper keeps an input that carries more than rows: a
JoinStepLogicalLookup, also below single-child wrappers, a subtree that can
produce totals (TotalsHavingStep, a remote read, or a query result cache read),
since a join joins its inputs' totals, or a subtree holding one half of a
shared subplan (`CommonSubplanStep` / `CommonSubplanReferenceStep`, which
decorrelation pairs across a join). The totals case also restores the totals
row the ON short-circuit dropped since 26.8.

Join-order estimation now treats ReadNothing as an exact empty relation, as it
already does for an exact empty MergeTree read, so a replaced input keeps its
exact zero estimate. `04516_join_reorder_duplicate_names_merge_expression` now
ignores the `[0]` row estimate an empty table gets in its EXPLAIN label.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the JoinStepLogicalLookup comment to one line and drop the comment above carriesMoreThanRows, which restated its own doc.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 4, 2026
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 5 findings over 3 rounds) plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ A JOIN input served from the query result cache could lose its WITH TOTALS row on a cache hit AGREE, fixed the cached read is kept like other totals sources
2 ❌ A correlated subquery under a WHERE no row passes failed with "Subplan cannot be used to build pipeline" AGREE, fixed an input holding one half of a shared subplan is kept; test arm added
3 ⚠️ FULL JOIN bypassed the rule AGREE, fixed both inputs are replaced; master throws TOO_MANY_ROWS at plan time there with query_plan_convert_outer_join_to_inner_join = 0
4 ⚠️ The cache test did not prove its second run is a cache hit AGREE, fixed query_log check on QueryCacheHits
5 ⚠️ No test covers the zero estimate for ReadNothing DISAGREE 04516_join_order_estimation_pruned_parts fails without it (f[0] ⋈ d[0] becomes f ⋈ d)
6 💡 A remote input is also kept by the constant-false ON short-circuit, even without totals noted performance only, the 26.7 behaviour

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261004-054000

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Issue query on a debug build: 22,084,104 rows / 29 parts read on master; minimal l/r repro 1,107,072 rows; ON constant false with a right WITH TOTALS side returns no totals row. New test 05320 fails on master with TOO_MANY_ROWS.
b Root cause explained? The pushed filter has a conjunct that reads no input (materialize of the branch constant) and is false for every row. Since #107084 such a conjunct is kept off a side the filter cannot be pushed to, so that side is read in full. Since 26.8 the constant-false ON short-circuit also empties a side that has totals.
c Fix matches root cause? Yes. A join input that cannot contribute under a filter no row passes is replaced by ReadNothing at plan level. The #107084 guard is kept, because it prevents wrong results (and keeps indexHint off a non-preserved side: 150, not 958).
d Test intent preserved / new tests added? New test 05320: row-limit arms (LEFT, INNER, FULL, aggregated right side) and plan arms, including the refusals and the totals row, also when the side is read from the query result cache (a query_log check proves the second run is a cache hit). A correlated subquery under a false WHERE must still run. The 04516_join_reorder oracle now ignores the row-estimate annotation; it still yields 1/0 for merge on/off on both binaries.
e Both directions demonstrated? Yes. 05320: master fails 3/3, fix passes 50/50 randomized. Issue query reads 190,104 rows / 1 part, same result. Totals row missing on master, present with the fix, also on a query result cache hit (deleting that refusal drops it again). The FULL arm fails with TOO_MANY_ROWS on master; the correlated arm failed with Subplan cannot be used to build pipeline before the shared-subplan refusal. 04516_join_order_estimation_pruned_parts: fails 3/3 without the estimator change, passes 20/20 with it.
f Fix is general across code paths? Both callers (WHERE rule and ON short-circuit) share the helper's refusals: join lookups, also below single-child steps, subtrees that can produce totals (TotalsHavingStep, remote reads, query result cache reads), and one half of a shared subplan (CommonSubplanStep / CommonSubplanReferenceStep, as convertJoinToIn refuses). All JOIN kinds go through the rule, FULL included; PASTE is positional and skipped. The estimator returns 0 for every ReadNothing, and every executed producer of it is empty.
g Fix generalizes across inputs (params/datatypes/wrappers)? LEFT, INNER, RIGHT, FULL (outer-to-inner conversion off), aggregated right side, totals on one or both sides, a cached subquery side (cache miss and hit), direct key-value join, correlated subquery side (equality and non-equality, buffer mode on and off), side-effecting filter (skipped), WHERE 0, materialize(0), constant AND non-constant conjunct. Type wrappers are N/A: the rule evaluates the filter on an empty header.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting; the rule is part of query_plan_filter_push_down, so compatibility = '24.6' gets the 26.6 behaviour back. Results are unchanged; EXPLAIN may show ReadNothing and a [0] estimate for empty inputs.
i Invariants and contracts preserved? The replaced input keeps its header and the JoinStepLogical stays (join validation still runs). The filter above the join is unchanged and still applies in full. Totals and lookups are never replaced, filters sensitive to evaluation count are skipped, and the estimate stays a true number.

Session id: cron:clickhouse-impl-slot-4:20261004-044100

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [57a85fb]

Summary: ✅


AI Review

Summary

This PR narrows the JOIN filter-pushdown guard so a no-input conjunct that is provably always false can be pushed onto an otherwise disabled join input again, which avoids reading and building that input when another pushed copy of the same conjunct already makes the whole join result empty. I reviewed the current diff and prior PR discussion and did not find a remaining correctness, safety, or test-gap issue in the changed code.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 57a85fb.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.60% -0.10%

Changed lines: Changed C/C++ lines covered: 27/28 (96.43%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Oct 4, 2026
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9d0b68d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test / 05218_text_index_substreams_opened_lazily not from this PR, which changes the JOIN filter push-down: selective_below_threshold is 0 because the measured query ran on cold caches after a concurrent cache clear. The same test fails on master and on other PRs since 2026-10-04 #123823 (mine, open)
Finish Workflow / Post Hooks, Mergeable Check, PR cascade: both functional Bugfix validation jobs were dropped after the Fast test failure, so nothing validated the bug #123823 (mine, open)

The Fast test failure dropped the remaining jobs, so this head has no other test signal yet. CIDB has no other FAIL or ERROR row on this head, and CH Inc sync passed.

Session id: cron:our-pr-ci-monitor:20261004-090143

@fm4v

fm4v commented Oct 5, 2026

Copy link
Copy Markdown
Member

@groeneai check CI failures

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

The only failed test was 05218_text_index_substreams_opened_lazily in Fast test. It is flaky and not related to this change. #123823 fixed it, but that PR merged after CI ran on this head. Because Fast test failed, CI dropped the remaining jobs, so Finish Workflow, Mergeable Check and PR failed only as a consequence.

I merged master, which includes #123823, at 3808f74, and full CI is running again. On a local build of the merged head, this PR's test 05320_join_under_always_false_where_reads_nothing and the two 04516_join_* join-order tests passed 20/20.

@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: 5eb66cae-1806-4c76-b806-192861ec966d
  • MIRAI run: 1aefe3ad-ccfa-47a6-a611-b558858de1c8
  • PR check IDs:
    • clickbench_3426554_1791234187
    • clickbench_3426560_1791234186
    • clickbench_3426571_1791234187
    • tpch_adapted_1_official_3426582_1791234187
    • tpch_adapted_1_official_3426610_1791234187
    • tpch_adapted_1_official_3426624_1791234187

…07084

Review on ClickHouse#123702 asked to keep the fix local to ClickHouse#107084, so the plan-level
ReadNothing rule is replaced by an exception in that guard.

The guard keeps a conjunct that reads no column off a join input that
push-down is disabled for: pushing it there and dropping it from the
post-join filter changes the result when it is NULL (04335) or true but
pruning (`indexHint`). When no row passes the filter and the join kind
allows filtering one input, that input receives the conjunct and the join
output is empty whatever the other input holds, so the guard is skipped
and the disabled input is filtered too, as before 26.7.

"No row passes" is `filterResultForNotMatchedRows` with no input
defaulted, which the outer join conversions already use, and the filter
must not be sensitive to its evaluation count.

This also drops the ReadNothingStep row estimate and the oracle change in
04516_join_reorder_duplicate_names_merge_expression, which only the
ReadNothing rule needed. The WITH TOTALS row lost by the constant-false
ON short-circuit is unrelated to ClickHouse#107084 and goes to a separate PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 57a85fbed with master 29e0e201c (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

1239 translation units recompiled, 8850 s compile time in total, 1239 of them have a recent master baseline.

Job report

@vdimir vdimir self-assigned this Oct 6, 2026
@vdimir
vdimir added this pull request to the merge queue Oct 6, 2026
Merged via the queue into ClickHouse:master with commit 99d818c Oct 6, 2026
149 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 6, 2026
robot-ch-test-poll added a commit that referenced this pull request Oct 6, 2026
Cherry pick #123829 to 26.8: Do not read a JOIN input that cannot contribute under a WHERE no row passes
robot-clickhouse added a commit that referenced this pull request Oct 6, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 6, 2026
/// With no input given only the conjuncts that read no column are evaluated, so FALSE means no row passes.
const bool filter_is_always_false
= (left_stream_filter_push_down_input_columns_available || right_stream_filter_push_down_input_columns_available)
&& !isSensitiveToEvaluationCount(filter->getExpression())

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.

Why do we use isSensitiveToEvaluationCount but now dagContainsNonDeterministicFunction for example?

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.

dagContainsNonDeterministicFunction would be a no-op here: filterResultForNotMatchedRows already returns UNKNOWN for such a DAG (Utils.cpp:175), and a filter with a stateful function returns from tryPushDownFilter before it reaches the join (filterPushDown.cpp:1175). So at this spot isSensitiveToEvaluationCount only adds hasObservableSideEffects, i.e. sleep/sleepEachRow: with the flag set, the conjunct is also evaluated on every block of the side #107084 keeps it off. It is the predicate the merge gate in optimizeJoin.cpp uses for the same situation (an expression evaluated in an extra place).

The effect is narrow. With default settings, the outer-to-inner conversion and use_join_disjunctions_push_down already push such a sleep into the right input. With both off:

CREATE TABLE l (k UInt64) ENGINE = MergeTree ORDER BY k;
CREATE TABLE r (k UInt64) ENGINE = MergeTree ORDER BY k;
INSERT INTO l SELECT number FROM numbers(1000);
INSERT INTO r SELECT number FROM numbers(1000000);

SELECT count() FROM l LEFT JOIN r ON l.k = r.k WHERE sleep(0.0001) = 1
SETTINGS query_plan_join_swap_table = 'false', query_plan_convert_outer_join_to_inner_join = 0, use_join_disjunctions_push_down = 0;

SleepFunctionCalls: 19 on 26.6.2.158, 1 on 26.8.2.7 and on this PR (18 or 19 on all three with default settings). Dropping the term would only affect sleep/sleepEachRow in an always-false filter.

For the backports, removing it is the simplest fix: 26.8 has neither IFunctionBase::hasObservableSideEffects nor allNodeFunctions (the errors on 34f42da), and sleep carries no flag there, so nothing is lost. On 26.9 the error on 13578f3 is the old static copy at optimizeJoin.cpp:771; it has the same body, so deleting it is enough.

vdimir pushed a commit that referenced this pull request Oct 7, 2026
The previous commit declares `isSensitiveToEvaluationCount` in
`Optimizations/Utils.h`, but the file-static copy with the same body is
still in `optimizeJoin.cpp`, so that file does not compile ("static
declaration follows non-static declaration"). Remove the copy and keep
its comment for `canMergeExpressionIntoJoinGraph`, as #120510 does on
master.

Related: #123829

Co-Authored-By: Claude Opus 5.5 <[email protected]>
vdimir pushed a commit that referenced this pull request Oct 7, 2026
…123829

The previous commit copies master's body, which uses `allNodeFunctions`
and `IFunctionBase::hasObservableSideEffects`; 26.8 has neither, so
`Utils.cpp` does not compile. Check the same properties with what 26.8
has: a function that is non-deterministic within the query or stateful,
`sleep` and `sleepEachRow` by name (the only functions master reports as
having observable side effects), and any lambda, since on 26.8 neither
this check nor `dagContainsNonDeterministicFunction` looks into a lambda
body.

Related: #123829

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh Bot added a commit that referenced this pull request Oct 7, 2026
Backport #123829 to 26.9: Do not read a JOIN input that cannot contribute under a WHERE no row passes
clickhouse-gh Bot added a commit that referenced this pull request Oct 7, 2026
Backport #123829 to 26.8: Do not read a JOIN input that cannot contribute under a WHERE no row passes
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 9, 2026
…not contribute under a WHERE no row passes
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport v26.9-must-backport

Projects

None yet

5 participants