Skip to content

Cherry pick #112957 to 26.7: Restore index analysis for range predicates in JOIN ON - #113463

Closed
robot-clickhouse wants to merge 7 commits into
backport/26.7/112957from
cherrypick/26.7/112957
Closed

robot-clickhouse wants to merge 7 commits into
backport/26.7/112957from
cherrypick/26.7/112957

Conversation

@robot-clickhouse

Copy link
Copy Markdown
Member

Original pull-request #112957

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 7 commits August 2, 2026 12:24
When the bounds of a range predicate on a MergeTree primary or partition key arrive through
`JOIN ON` against a single-row constant side, the logical join step left the inequality as a
residual filter ABOVE the join, where index analysis never sees it. Every part was read.
Reported as #112586: on a ~365M-row table this was 1.4s versus 35-68s. Until 26.5 the
`query_plan_use_new_logical_join_step` setting could restore pruning; #104017 made it
obsolete, leaving no mitigation.

Such a condition is now retried against a clone of itself with the opposite side's
references replaced by the constants its input header carries. That makes it single-sided,
so the existing path places it below the join and `KeyCondition` sees it.

The substitution is declined unless it is provably safe:

  - only INNER, CROSS and comma joins with ALL strictness, where the residual is equivalent
    to a filter over the product;
  - never a key-forming equality, including one nested in a disjunction, so a join cannot
    become keyless and degrade to a product;
  - constness is read from the header column, so a one-row table stays unpruned;
  - duplicate column names resolve by source relation and header position, not by name;
  - every node must be safe to relocate: no stateful or non-deterministic function, no
    `arrayJoin`, and no function that can throw or is expensive. Below the join a predicate
    also sees the rows a surviving key rejects, so `ON t.k = b.k AND intDiv(1, t.x) >= b.lo`
    would raise ILLEGAL_DIVISION on an unmatched row that master answers. Safety is read
    from `isSuitableForShortCircuitArgumentsExecution`, the property short-circuit
    evaluation already consults to keep such arguments unevaluated.

One behaviour change: a relocatable inequality-only `ON` against a constant side is now
answered on the non-hash algorithms instead of raising INVALID_JOIN_ON_EXPRESSION, since the
predicate is enforced below the join and no key is needed. Literal bounds already answered,
so this removes an inconsistency. A predicate the guards decline keeps raising as before.

Nine pruning assertions flip without the fix and each guard is mutation-tested both ways.
An A/B sweep of 1195 join and index tests found no difference from pristine master. The
stateless test is tagged `no-parallel-replicas`: there the `ON` clause is re-serialized as
SQL for the remote legs, so the opposite side is a temporary table rather than a plan-time
constant and the plan under test never forms, measured identical on master.

Closes #112586.
`getFilterActions` re-ran `collectOppositeSideConstants` over the combined
`and(...)` of every extracted conjunct. That walk reaches the current-side
inputs of the purely one-sided conjuncts too, so a current-side name duplicated
in the header and referenced only from a one-sided conjunct raised the
duplicate-name veto and made the whole call return `nullopt`.

The lost filter includes the one-sided pushdown master performs today with no
substitution at all, so the veto was a regression rather than a missed
optimization: a left header `[y, x, x]` with `ON y >= r.lo AND x > 0` pushed
`x > 0` before this PR and pushed nothing after it.

The substitution map is now accumulated per substitutable conjunct, which is the
scope the veto describes: the substituted predicate is bound to the stream by
name, so only names reached through a conjunct that is actually rewritten can be
mis-bound. The whole predicate is still cloned in ONE call, keeping the single
input per repeated column that the surrounding comment records.
…edicate

The relocation guard asked isSuitableForShortCircuitArgumentsExecution, but that
property means "can throw OR is computationally heavy", so it is wrong in both
directions as a throw-safety test. h3GetBaseCell returns false from it and still
raises INCORRECT_DATA on an invalid cell under the default
functions_h3_default_if_invalid = 0, and addDays(String, ...) returns false and
raises CANNOT_PARSE_DATETIME on an unparsable value. Either one, placed in an ON
predicate over both relations, was moved below the join and then evaluated on the
probe rows a surviving key rejects, turning an answer into an error. Master
answers 1 for both shapes; the previous head raised.

There is no exception-only property to switch to. IFunctionBase::canThrow
delegates to that same predicate in IFunctionAdaptors.h and carries a TODO asking
for a dedicated interface, so reaching for it only relocates the same call.

So ask the opposite question and admit a function only once its totality has been
checked: logical connectives, which combine already-computed UInt8s; toYYYYMM on
Date, Date32 and DateTime, verified by evaluating it over each of those complete
domains, but not on DateTime64, where rescaling ticks raises Decimal math
overflow; and comparisons whose stripped argument types are equal, since a
comparison converts only to reach a common type. Mixed widths stay declined
because they do overflow: Decimal256(0) against Decimal32(9) raises "Decimal
value is too big" and DateTime64(0) against DateTime64(9) raises "Can't compare
decimal number due to overflow".

Declining a function costs only the optimization, so cityHash64 keeps its
previous placement, now because it is not in the allowlist rather than because it
is expensive. The nine pruning assertions and the Nullable and LowCardinality
bounds rows are unaffected, and an A/B sweep of 1195 join and index tests shows
no difference.
…ains

Equal argument types are not enough to make a comparison total. Dynamic and
Variant compare the values they happen to contain, so two columns of the very
same type can meet at a row whose contained types have no supertype and raise
NO_COMMON_TYPE. Moving such a predicate below the join then evaluates it on the
probe rows a surviving key rejects, so a query master answers with 1 raised
instead. A container is only as safe as its element type, and Tuple(Variant(...))
raises the same way, while Array and Map of the same happen not to today.

So admit only types whose values all share one comparison order, recursing
through Array, Tuple and Map. That covers the class rather than the two adaptor
names, and it keeps the Nullable and LowCardinality bounds rows working, since
stripping those wrappers does not change the compared value.
std::ranges::all_of is true for an empty range, so Tuple() passed the element
check with nothing to check. Comparing a zero-sized tuple raises NOT_IMPLEMENTED,
so the type does not belong in an allowlist of totally ordered types.

No behaviour changes: that comparison raises from FunctionComparison::executeTuple
for every row regardless of where the predicate sits, so master, the previous head
and this build all answer the shape identically. This closes the vacuous branch
rather than a reachable regression.
…index-analysis-112586

Restore index analysis for range predicates in JOIN ON
@robot-clickhouse robot-clickhouse added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request labels Aug 5, 2026
@fm4v fm4v closed this Aug 5, 2026
@maxknv
maxknv deleted the cherrypick/26.7/112957 branch November 13, 2026 13:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants