Skip to content

Do not pre-filter a join side with a condition that reads no column - #117569

Merged
alexey-milovidov merged 14 commits into
masterfrom
fix-column-free-conjunct-join-push-down-113969
Oct 11, 2026
Merged

alexey-milovidov merged 14 commits into
masterfrom
fix-column-free-conjunct-join-push-down-113969

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 1, 2026 •

Copy link
Copy Markdown
Member

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 to CHANGELOG.md):

Fixed indexHint over the non-preserved side of an OUTER join silently returning extra rows, and join_algorithm = 'direct' failing with NOT_IMPLEMENTED when a column-free conjunct such as materialize(1) is added to the WHERE clause.

Documentation entry for user-facing changes

The partial join filter push-down extracts every conjunct whose columns are available on a side. A conjunct that reads no column at all satisfies that check vacuously, so it was pushed to both sides. Two different things then go wrong.

Wrong results. indexHint carries its condition in a separate inner expression, so in the outer one it reads no column. On the non-preserved side of an OUTER join pushing it is not a no-op: pruning granules there turns matched rows into unmatched ones, the preserved side then gets default values for the right columns, and those defaults pass the accompanying predicate:

SELECT count() FROM jl AS l LEFT JOIN jr AS r ON l.id = r.id
WHERE indexHint(r.id < 150) AND (r.id < 150);
-- 958, while the same query without the hint, and the INNER JOIN, return 150

A failing query. Pre-filtering with a provably-true conjunct removes nothing, but it interposes a Filter step, and that changes what later optimizations recognize: a Filter above a key-value right side hides the prepared storage from the direct-join detection. With join_algorithm = 'direct' there is no fallback, so a working query started failing because of a conjunct that cannot change which rows qualify:

SELECT value2 FROM t2 LEFT JOIN rdb ON rdb.key == t2.k
SETTINGS join_algorithm = 'direct';                    -- works

SELECT value2 FROM t2 LEFT JOIN rdb ON rdb.key == t2.k WHERE materialize(1)
SETTINGS join_algorithm = 'direct';
-- Code: 48. Can't execute any of specified algorithms for specified
-- strictness/kind and right storage type. (NOT_IMPLEMENTED)

toNullable(256) and CAST(1 AS LowCardinality(Nullable(UInt8))) produce the same failure, and query_plan_filter_push_down = 0 cures all of them.

A column-free conjunct is now only pushed when it is a constant the DAG has already folded to false: that one case is worth a Filter, because it makes the side's read provably empty, which the join-order estimator turns into an exact empty relation (04516_join_order_estimation_pruned_parts). Even that constant is never offered to a side whose push-down is disabled, such as a prepared JoinStepLogicalLookup right side: the vacuous column check used to let it through with an empty allowed-column set, and the resulting Filter hid the key-value storage just like the materialize(1) case. The estimator still reads the empty relation from the other side.

The carve-out deliberately stops at the folded constant and does not derive always-false for an unfolded expression such as materialize(0). Widening it that way was implemented and measured: it buys only symmetry with the folded case, and it costs the NOT_IMPLEMENTED above for one more class of queries, because the filter it lets through is exactly the Filter that hides the key-value side. 05227 asserts materialize(0) and materialize(toNullable(NULL)), as well as the folded WHERE 0 and WHERE toNullable(NULL), return 0 under a forced direct join.

Non-deterministic conjuncts that also read a column are a separate class, reported in #116930. That one is already closed on master by the determinism gate in onlyDependsOnAvailableColumns, which uses allNodeFunctions and so also sees into lambda inner DAGs. 05229_nondeterministic_conjunct_join_push_down adds the reported repro shape, where the non-deterministic leaf sits inside a disjunction spanning both sides and only the Or branch of extractPartialPredicate can act on it.

05228 is tagged no-old-analyzer: the old analyzer answers UNKNOWN_IDENTIFIER for a qualified column of a joined table inside indexHint, before the optimization under test runs. All three regression tests pin use_join_disjunctions_push_down = 1 in each query's own SETTINGS clause, because the runner passes randomized settings on the client command line, where they are per-query settings that outrank a session SET.

Closes: #113969
Closes: #112035
Closes: #120463
Related: #116930

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.2099-master (included in 26.10 and later)

The partial join filter push-down extracts every conjunct whose columns are
available on a side. A conjunct that reads no column at all satisfies that
check vacuously, so a provably-true, column-free predicate was pushed to both
sides. Pre-filtering with it removes nothing, but it interposes a `Filter`
step, and that changes what later optimizations recognize: a `Filter` above a
key-value right side hides the prepared storage from the direct-join
detection. With `join_algorithm = 'direct'` there is no fallback, so a working
query started failing because of a conjunct that cannot change which rows
qualify:

    SELECT value2 FROM t2 LEFT JOIN rdb ON rdb.key == t2.k
    SETTINGS join_algorithm = 'direct';                    -- works

    SELECT value2 FROM t2 LEFT JOIN rdb ON rdb.key == t2.k WHERE materialize(1)
    SETTINGS join_algorithm = 'direct';
    -- Code: 48. Can't execute any of specified algorithms for specified
    -- strictness/kind and right storage type. (NOT_IMPLEMENTED)

`toNullable(256)` and `CAST(1 AS LowCardinality(Nullable(UInt8)))` produce the
same failure, and `query_plan_filter_push_down = 0` cures all of them.

A column-free conjunct is now only pushed when it is a constant already known
to be false: that one case is worth a `Filter`, because it makes the side's
read provably empty, which the join-order estimator relies on
(`04516_join_order_estimation_pruned_parts`).

Closes: #113969
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4cade36]

Summary: ✅


AI Review

Summary

This PR fixes the real correctness/regression cases around column-free conjunct push-down on joins: the new indexHint and direct-join regressions are covered, the prior nondeterministic case is addressed, and the changelog metadata is good. I found one remaining contract gap, though: the new “column-free predicates are only useful when already-folded false” rule is enforced only in the partial-predicate extractor, while the main JOIN filter push-down path still accepts no-input non-constant predicates such as materialize(1) and can still materialize useless pre-join Filter steps.

Findings
  • ⚠️ Majors
    • [src/Processors/QueryPlan/Optimizations/partialJoinFilterPushDown.cpp:123] The new usefulness rule is implemented only in tryToExtractPartialPredicate. The sibling JOIN push-down path in src/Interpreters/ActionsDAG.cpp:3858 still treats a no-input non-COLUMN conjunct such as materialize(1) as pushable to any enabled side, so whether a column-free predicate is pre-filtered now depends on which optimizer path sees it first.
    • Suggested fix: apply the same no-input usefulness gate in splitActionsForJOINFilterPushDown / createActionsForConjunction, or factor the predicate classification so both JOIN push-down mechanisms share one rule.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: make the ordinary JOIN filter push-down path reject no-input truthy predicates too, or narrow the new invariant/comments/tests so they match the behavior that actually remains supported.

LLVM Coverage Report

Measured on commit 4cade36.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.40% 79.50% +0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 1, 2026
@zlareb1

zlareb1 commented Sep 1, 2026

Copy link
Copy Markdown
Member

The column-free gate fixes the loud NOT_IMPLEMENTED face and, incidentally, the literal repro of #116930 (a column-free nondeterministic conjunct such as rand() % 2 = 0 no longer passes isUsefulToPreFilterWith). But the class described by #116930 — nondeterministic conjuncts are not eligible for partial-predicate extraction — stays open for conjuncts that also read a column, because isUsefulToPreFilterWith accepts on dependsOnSomeColumn alone and neither extractPartialPredicate nor the callers in tryPushDownOverJoinStep check determinism (the only global gate is hasStatefulFunctions, which rand passes).

Verified on 26.9.1.1 at default settings: with t1 as 100000 rows of (k, a = k % 2, b = k) and t2 as (k, c = 1),

SELECT count() FROM t1 JOIN t2 ON t1.k = t2.k
WHERE (t1.a = 0 AND (t1.b + rand()) % 2 = 0) OR (t1.a = 1 AND t2.c >= 0)

returns 62699 with use_join_disjunctions_push_down = 1 and 75070 with it off (the correct expectation is ~75000: 50000 deterministic rows plus ~25000 at one coin flip per row). The extracted pre-filter below the join and the retained filter above it draw rand independently, so the a = 0 rows must pass two independent coin flips. This variant still reproduces with this PR's gate because (t1.b + rand()) % 2 = 0 reads t1.b.

Two suggestions: a determinism check in isUsefulToPreFilterWith (or in extractPartialPredicate's leaf branch) would close the whole class rather than its column-free face; and #116930 should not be closed on the strength of its literal repro passing after this PR.

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4cade3614 with master a200f3b9a (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

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

Job report

`indexHint` carries its condition in a separate inner expression, so in the
outer one it reads no column - exactly the shape this branch stops pushing to
the join sides. On the non-preserved side of an OUTER join the push was not a
no-op: pruning granules there turned matched rows into unmatched ones, the
preserved side then got default values for the right columns, and those
defaults passed the accompanying predicate, so the query returned a much
larger row set at default settings:

    SELECT count() FROM jl AS l LEFT JOIN jr AS r ON l.id = r.id
    WHERE indexHint(r.id < 150) AND (r.id < 150);
    -- 958, while the same query without the hint, and the INNER JOIN, return 150

Closes: #112035
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
alexey-milovidov and others added 4 commits September 10, 2026 09:32
The carve-out that kept a provably false column-free conjunct pushable
reproduced the very failure this change fixes. A `Filter` above a
key-value right side hides the prepared storage from the direct-join
detection, so with `join_algorithm = 'direct'` forced,

    SELECT value2 FROM t_direct_left LEFT JOIN t_direct_right
    ON t_direct_right.key == t_direct_left.k WHERE 0

failed with `NOT_IMPLEMENTED` exactly like the `materialize(1)` case,
because the folded `0` was still extracted and pushed below the join.

The carve-out also bought nothing: the copy of the filter that stays
above the join already drops every row, so the pushed copy only changes
which optimizations recognize the plan. `extractPartialPredicate` now
extracts a leaf only when it reads at least one column of the side it is
extracted for, which makes the rule total and removes the inconsistency
between a folded `0` and a `materialize(0)` that constant folding does
not see.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…analyzer

`clickhouse-test` randomizes `use_join_disjunctions_push_down`, and it
passes randomized settings on the client command line, where they are
per-query settings that outrank a `SET` issued earlier in the session.
Every query now pins the setting in its own `SETTINGS` clause, so the
runs that flip it to `0` no longer make the guard pass vacuously.

The old analyzer cannot resolve a qualified column of a joined table
inside `indexHint` at all - it answers `UNKNOWN_IDENTIFIER` before the
optimization under test runs - so the file is tagged `no-old-analyzer`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The partial predicate is pushed below the join while the original filter
stays above it, so an extracted leaf is evaluated twice and a per-row
draw such as `rand` becomes two independent coin flips. Master already
rejects a non-deterministic subtree in `onlyDependsOnAvailableColumns`,
but no test covers the reported shape, where the leaf sits inside a
disjunction that spans both sides and only the `Or` branch of
`extractPartialPredicate` can act on it.

Related: #116930

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @zlareb1 thank you for the measurement — the class you describe is real, and it turned out to be already closed on master. This branch was 5206 commits behind; I have merged master up.

onlyDependsOnAvailableColumns now carries the determinism gate, and it is stronger than a check on the leaf node itself because allNodeFunctions also walks lambda inner DAGs:

/// The extracted predicate runs in addition to the filter above the JOIN, so a per-row draw such as
/// `rand` happens twice and only a row passing both survives; a lambda body is a separate DAG.
if (!allNodeFunctions(node, [](const IFunctionBase & function) { return function.isDeterministicInScopeOfQuery(); }))
    return false;

Verified on the merged branch with your fixture shape: the plan keeps the non-deterministic leaf above the join and extracts only the deterministic part of the disjunction,

Filter (WHERE)
│  Filter column: a = 0 AND (b + rand()) MOD 2 = 0 OR a = 1
└──Join (JOIN FillRightFirst)
   ├──Filter (( + Change column names to column identifiers))
   │  │  Filter column: a = 0 OR a = 1

and the count now agrees with the push-down-off arm. I added 05175_nondeterministic_conjunct_join_push_down for exactly your query — 05139_join_partial_push_down_nondeterministic_lambda only covers a single top-level conjunct, so the Or branch of extractPartialPredicate had no regression guard. It asserts the count lands in [74000, 76000] with and without the push-down; the buggy answer was ~62500, about 110 standard deviations away.

Agreed on your second point: #116930 should be judged on the class, not on its literal repro, and it is the determinism gate on master that closes it rather than the column-free gate in this PR.

alexey-milovidov and others added 2 commits September 10, 2026 10:25
Removing it regressed `04516_join_order_estimation_pruned_parts` on
`master`, whose `WHERE 0` probe asserts the pruned side is estimated as
an exact empty relation:

    -    │  f[0] ⋈ d[0]
    +    │  f[101000] ⋈ d[10000]

So a folded always-false constant stays pushable, and the carve-out
deliberately stops there rather than deriving always-false for an
unfolded expression such as `materialize(0)`. Widening it that way was
measured to buy only symmetry with the folded case while costing the
`NOT_IMPLEMENTED` this change exists to remove:

    Code: 48. None of the algorithms enabled by the 'join_algorithm'
    setting [direct] can execute this ALL INNER JOIN with the given right
    table storage type. (NOT_IMPLEMENTED)
    (query: SELECT count() FROM (SELECT value2 FROM t_direct_left
            LEFT JOIN t_direct_right ON t_direct_right.key == t_direct_left.k
            WHERE materialize(0) SETTINGS join_algorithm = 'direct'))

`05101` now states which of the two directions each case belongs to.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits September 17, 2026 21:28
…bled

Address review: a column-free conjunct such as a folded `WHERE 0` depends
on no column, so it passed `tryToExtractPartialPredicate` even for a side
that was given an empty allowed-column set because its push-down is
disabled. Above a `JoinStepLogicalLookup` the inserted `Filter` hides the
prepared storage from the direct-join detection, and a forced
`join_algorithm = 'direct'` failed with `NOT_IMPLEMENTED` instead of
returning an empty result. Skip such a side in `tryPushDownOverJoinStep`;
the join-order estimator still reads the empty relation from the other
side (`04516_join_order_estimation_pruned_parts`).

Add folded `WHERE 0` / `WHERE toNullable(NULL)` direct-join cases to the
test, and renumber the three tests to `05227`-`05229` after the merge with
`master`, because their old prefixes were taken meanwhile.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Oct 11, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 11, 2026
Merged via the queue into master with commit 4ee93ae Oct 11, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-column-free-conjunct-join-push-down-113969 branch October 11, 2026 01:59
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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

4 participants