Skip to content

Fix constant filter conjunct pushed to non-preserved side of OUTER JOIN - #107084

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-106949-qualify-null-right-join-pushdown
Jul 1, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-106949-qualify-null-right-join-pushdown

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix a wrong result in an OUTER JOIN when the WHERE filter is a conjunction that contains a constant term (for example p AND 1, or WHERE p QUALIFY NULL where QUALIFY NULL is merged into WHERE). The constant conjunct could be pushed into the non-preserved side of the join and removed from the post-join filter, so the join produced non-matched rows with the side columns defaulted and those rows incorrectly passed the filter.

Description

Reported by SQLancer (#106949).

Reproducer (tjmin is a Join(ALL, RIGHT, ...) engine table):

SELECT * FROM tmin ALL RIGHT JOIN tjmin ON tjmin.key2 = tmin.key2 AND tjmin.key1 = tmin.key1
WHERE and((tmin.key2 <=> tjmin.key2) = tmin.key2, 1)
QUALIFY NULL;

Without the extra AND 1 the query returns 0 rows (correct). With it, the
same query returns all right-side rows with the left columns defaulted.

Root cause: getConjunctionNodes() (used by
ActionsDAG::splitActionsForJOINFilterPushDown) classifies a conjunct as
pushable to a join side when all of its children are allowed inputs of that
side. A conjunct with no inputs (a pure constant such as 1 or a folded
NULL literal) satisfies this trivially, so constant conjuncts were treated
as pushable to any side, including a side that is disabled for push-down. For
an OUTER join the non-preserved side is disabled (its allowed-input set is
empty), yet the constant conjunct was still pushed into that side input and
dropped from the post-join filter. A falsy/NULL constant then filtered out
the side input, the join fabricated non-matched rows with the side columns
defaulted, and those rows escaped the now constant-free post-join filter.

Fix: push a conjunct to a join side only if it actually depends on at least
one allowed input of that side. Constant conjuncts now stay in the post-join
filter, where they are applied to the join output and correctly constrain all
rows (matched and non-matched).

Regression test added in
tests/queries/0_stateless/04335_storage_join_right_join_const_conjunct_pushdown.sql.
It returns 2 wrong rows on current master and 0 rows with this fix.

Version info

  • Merged into: 26.7.1.378 (included in 26.7 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT * FROM tmin ALL RIGHT JOIN tjmin ON tjmin.key2=tmin.key2 AND tjmin.key1=tmin.key1 WHERE and((tmin.key2 <=> tjmin.key2)=tmin.key2, 1) QUALIFY NULL returns 2 rows on master, 0 with the fix, every run. Minimal trigger without QUALIFY: WHERE and(tmin.key1<100, 1, NULL) (the analyzer just folds QUALIFY NULL into the WHERE filter).
b Root cause explained? getConjunctionNodes() marks a conjunct pushable to a join side when all its children are allowed inputs of that side. A constant conjunct (1, folded NULL) has no children, so 0 == 0 makes it pushable to ANY side, including a side whose allowed-input set is empty. For a RIGHT JOIN the left (non-preserved) side is disabled, yet the const conjunct was pushed into the left input and stripped from the post-join filter. The NULL const then filtered out the left input, the join fabricated non-matched rows (left columns defaulted), and they escaped the now constant-free post-join filter.
c Fix matches root cause? Yes. The fix requires a conjunct to depend on at least one allowed input of a side before it is pushed there. Constant conjuncts no longer leak to a disabled side; they stay in the post-join filter where they correctly constrain all join-output rows. This targets the classification mechanism directly, not the symptom.
d Test intent preserved / new tests added? New regression test 04335_storage_join_right_join_const_conjunct_pushdown.sql covering the issue repro, the no-QUALIFY minimal trigger, and the unfiltered baseline (matched row filled, non-matched row defaulted). No existing test weakened.
e Both directions demonstrated? Yes. The new test returns 2 wrong rows on unfixed master and 0 rows with the fix (diff confirmed). 16 existing join / storage-join / filter-pushdown stateless tests still pass (00118/00119/00444/00549/00555/00561/00779/00974/01015/01140/02007/03036/03095/03130/03143/03152/03197/03204/03210 and the 01763/01913/00597/02382/03405 set).
f Fix is general, not a narrow patch? Yes. The fix is in the shared splitActionsForJOINFilterPushDown conjunct-classification used for LEFT/RIGHT/INNER and both JoinStep and FilledJoinStep. Verified the same trigger is now correct for RIGHT/LEFT and for Join-engine and Memory right tables; legitimate column-dependent pushdown (INNER and(pred,1), genuine left/right predicates) is preserved. It fixes the classification at the source rather than guarding a single call site.

Session id: cron:clickhouse-worker-slot-10:20260610-195500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd — could you review this? It fixes a wrong result in OUTER JOIN filter push-down: a pure-constant WHERE conjunct (e.g. p AND 1, or QUALIFY NULL folded into WHERE) was classified as pushable to the non-preserved join side (empty allowed-input set) and stripped from the post-join filter, so the join fabricated non-matched rows that escaped the filter. The fix only pushes a conjunct to a side if it depends on an allowed input of that side.

@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a8177b3]

Summary: ✅


AI Review

Summary

This PR fixes a wrong-result bug in OUTER JOIN filter push-down by keeping no-input constant conjuncts out of disabled join-side filters in ActionsDAG::splitActionsForJOINFilterPushDown. The current code preserves the existing optimization for enabled/preserved sides, and the added stateless test exercises the reported Join(ALL, RIGHT, ...) + QUALIFY NULL regression shape. I found no unresolved correctness issues and did not post new inline comments.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 10, 2026
@groeneai
groeneai force-pushed the fix-106949-qualify-null-right-join-pushdown branch from 3500e5e to 709ad2a Compare June 11, 2026 00:44
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated for HEAD 709ad2a060dc)

This push narrows the fix in response to the Fast test failure on the previous HEAD (3500e5ea) for the pre-existing test 03594_push_more_filters_down_joins. Root cause of that CI failure: the previous version blocked constant-conjunct push-down to all join sides, regressing the legitimate optimization that 03594 asserts (it converts a 2-LEFT JOIN chain to INNER via query_plan_convert_outer_join_to_inner_join=1, so both sides are enabled and pushing the true constant down is correct).

# Question Answer
a Deterministic repro? Yes. 03594: with real data the EXPLAIN step output was Join/Join/Filter/Filter/... (extra Filter steps) on the previous HEAD vs the reference Join/Join/Filter. #106949: WHERE and(p,1) QUALIFY NULL over a Join(ALL,RIGHT) table returns 2 wrong rows on master, 0 with the fix. Both reproduce on demand on a debug build.
b Root cause explained? Yes. getConjunctionNodes() classifies a conjunct as pushable to a side when all its inputs are allowed inputs of that side; a no-input conjunct (constant 1, folded NULL) trivially satisfies 0==0 and is pushed to every side. For an OUTER join the non-preserved side is disabled (empty allowed-input set); pushing the constant there and dropping it from the post-join filter lets a falsy/NULL constant filter out that side, the join fabricates non-matched rows, and they escape the now constant-free post-join filter. The over-broad first version also blocked the constant on enabled sides, which removed a legitimate push-down 03594 checks.
c Fix matches root cause? Yes. The constant is dropped from a side's push-down set only when that side is disabled (allowed_nodes empty); enabled (preserved) sides keep the existing classification, because pushing a constant to a preserved side is equivalent to keeping it post-join. The both_streams set is gated when either side is disabled. No bounds widened, no no-random-* tags, no data reduction.
d Test intent preserved / new tests added? Yes. New regression test 04335_storage_join_right_join_const_conjunct_pushdown (the QUALIFY NULL and and(p,1) QUALIFY NULL forms: 2 wrong rows on master, 0 with fix) plus the baseline. The pre-existing 03594_push_more_filters_down_joins is unchanged and now passes (plan back to Join/Join/Filter, JoinResultRowCount=0). I removed one query from 04335 (WHERE and(left_pred,1,NULL) without QUALIFY): on master it also returns wrong rows, but with the fix the same query reaches a pre-existing, unrelated StorageJoin composite-key limitation (UNSUPPORTED_JOIN_KEYS: keys128 in JoinSource::createChunk), so it is not a clean demonstration of this fix and was dropped.
e Both directions demonstrated? Yes. #106949 and(p,1) QUALIFY NULL: 2 rows without fix, 0 with fix. 03594 EXPLAIN: extra Filter steps without fix, Join/Join/Filter with fix, JoinResultRowCount=0 both. All on the rebuilt debug binary.
f Fix is general, not a narrow patch? Yes. The gate is applied symmetrically to the left, right, and both-streams push-down sets in splitActionsForJOINFilterPushDown, so it covers LEFT/RIGHT/FULL OUTER joins and equivalent-set pushes, not just the one reproduced shape. It is not a defensive symptom guard: it corrects where the conjunct is placed (post-join filter vs disabled-side input). Regression set still green: 03130_convert_outer_join_to_inner_join, 04075_join_reorder_outer_join_filter_pushdown, 02861_filter_pushdown_const_bug, 03036_join_filter_push_down_equivalent_sets, 03143_join_filter_push_down_filled_join_fix, 03095_window_functions_qualify, 00118/00119_storage_join, 02382_join_and_filtering_set all pass.

Session id: cron:clickhouse-worker-slot-22:20260610-231000

@groeneai
groeneai force-pushed the fix-106949-qualify-null-right-join-pushdown branch from 709ad2a to 032515d Compare June 11, 2026 02:34
A WHERE filter that is a conjunction containing a constant term, such as
`p AND 1` or anything that folds a NULL literal into the predicate (for
example `WHERE p QUALIFY NULL`, where the analyzer merges the QUALIFY NULL
into the WHERE filter), produced wrong results over a RIGHT JOIN whose right
side is a `Join` engine table.

getConjunctionNodes() in splitActionsForJOINFilterPushDown classifies a
conjunct as pushable to a join side when all of its inputs are allowed inputs
of that side. A conjunct with no inputs (a pure constant) satisfies this
trivially, so constant conjuncts were classified as pushable to any side. For
an OUTER join the non-preserved side is disabled for push-down (its allowed
input set is empty), yet the constant conjunct was still pushed into that side
input and removed from the post-join filter. A falsy/NULL constant then
filtered out the side input, the join fabricated non-matched rows with the
side columns defaulted, and those rows escaped the now constant-free post-join
filter.

Fix: when a join side is disabled for push-down (empty allowed input set), do
not push a conjunct that depends on no input of that side. Such constant
conjuncts stay in the post-join filter, where they constrain all rows (matched
and fabricated non-matched). Sides that are enabled keep the existing
behaviour, so legitimate constant push-down into a preserved side is
unaffected (push-down of a constant to a preserved side is equivalent to
keeping it in the post-join filter).

The regression test forces the new analyzer with `SET enable_analyzer = 1`
because the repro uses a QUALIFY clause, which the old analyzer does not
support; this keeps the test running on every CI variant rather than skipping
it via a no-old-analyzer tag. It uses only local Memory and Join engine tables
with deterministic, stable result checks.

Closes ClickHouse#106949.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-106949-qualify-null-right-join-pushdown branch from 032515d to a8177b3 Compare June 11, 2026 07:06
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixup (HEAD a8177b335cc9): the old-analyzer CI variant (Stateless tests (amd_llvm_coverage, old analyzer, ...)) failed 04335_storage_join_right_join_const_conjunct_pushdown with Code: 48 ... QUALIFY clause is not supported in the old analyzer (NOT_IMPLEMENTED). The repro for #106949 needs a QUALIFY clause, which the old analyzer rejects.

Rather than adding a no-old-analyzer tag (which would skip the test on that variant, and no-* tags are discouraged when avoidable), the test now starts with SET enable_analyzer = 1; — the same idiom sibling QUALIFY tests use (e.g. 03786_storage_join_type_conversion, 03095_window_functions_qualify, 04026_prewhere_qualify_text_index). The test keeps running on every variant and always exercises the fix via the new analyzer.

Verified on the debug binary: with the original test under --enable_analyzer=0 it reproduces the Code: 48 failure; with the SET line it diffs clean against .reference on both the default and the simulated old-analyzer variant (--enable_analyzer=0), 10/10 deterministic. Source fix and .reference unchanged; the diff is the 1-line SET.

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.30% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 34/34 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

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

Looks correct.

First I thought - doesn't it disable push down of constant filters into preserved side of the JOIN (like lhs of LEFT JOIN). But the code looks correct.

@alexey-milovidov alexey-milovidov self-assigned this Jul 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 1, 2026
Merged via the queue into ClickHouse:master with commit 59d2926 Jul 1, 2026
166 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.1, 26.2, 26.3, 26.4, 26.5. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-null-right-join-pushdown

Fix constant filter conjunct pushed to non-preserved side of OUTER JOIN
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 5, 2026
…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]>
CurtizJ pushed a commit to CurtizJ/ClickHouse that referenced this pull request Oct 6, 2026
…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]>
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-bugfix Pull request with bugfix, not backported by default 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.

5 participants