Skip to content

Restore index analysis for range predicates in JOIN ON - #112957

Merged
fm4v merged 6 commits into
ClickHouse:masterfrom
groeneai:fix/join-on-range-predicate-index-analysis-112586
Aug 5, 2026
Merged

fm4v merged 6 commits into
ClickHouse:masterfrom
groeneai:fix/join-on-range-predicate-index-analysis-112586

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #112586

Changelog category (leave one):

  • Performance Improvement

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

Restores part and granule pruning when the bounds of a range predicate on a MergeTree primary or partition key are supplied through a JOIN ON clause against a single-row constant side, for example SELECT count() FROM t JOIN bounds ON t.d >= bounds.lo AND t.d <= bounds.hi. Such a query read every part since 25.2, and the query_plan_use_logical_join_step setting that used to restore pruning became obsolete in 26.5, leaving no way to recover it. Closes #112586.

Description

What breaks. With the bounds coming from JOIN ON, index analysis reports Condition: true and reads every part, while the same predicate as a plain WHERE prunes. Only pruning is lost.

Root cause. getFilterActions selects the ON conditions a filter below the join can evaluate. A predicate comparing a left column against a right column is neither fromLeft nor fromNone, so it is not selected and becomes a residual filter, materialized above the join after index analysis.

The change. Such a condition is retried against a clone of itself with the right-side references replaced by the constants their input header carries, making it single-sided so the existing path places it below the join.

Only INNER, CROSS and comma joins with ALL strictness qualify, since only there is the residual equivalent to a filter over the product. A key-forming equality is excluded, including one nested in a disjunction, so a join is never keyless. Constness comes from the header column, so a one-row table stays unpruned. Duplicate names resolve by source relation and position. A condition moves only if every node is safe to relocate, excluding stateful and non-deterministic functions, arrayJoin, and any function not established to be total over its argument types: below the join a predicate also sees the rows a surviving key rejects, so one that raises there turns an answer into an error.

One behaviour change. An inequality-only ON against a constant side is now answered on the non-hash algorithms rather than raising INVALID_JOIN_ON_EXPRESSION, because the predicate is enforced below the join and no key is needed. Literal bounds already answered, so this removes an inconsistency. A declined predicate keeps raising.

Validation. 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 the previous head.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (6 rounds, independent reviewer + adversarial gate)

Before opening this PR I ran it through six rounds of independent review: a reviewer who reads the
resulting code cold, plus an adversarial second-model gate on every round. Six blockers and several
majors were found and fixed in the process. Recording the substantive ones and my verdicts, so a
maintainer can see what was already challenged.

❌ Blockers found and fixed

# Finding Resolution
1 A key-forming equality nested in OR/AND was extracted, so a disjunctive join lost the keys tryAddDisjunctiveConditions derives, and 01429_join_on_error_messages stopped raising NOT_IMPLEMENTED under partial_merge/grace_hash. wouldBecomeJoinKey now recurses through OR/AND. Both algorithms pinned in the test.
2 The opposite-side value was fetched with Block::findByName, which answers one position per name, so a reference to the second of two same-named columns was rewritten with the first one's value and then erased from ON — a wrong bound enforced, the intended one enforced nowhere. Resolution is now positional; membership is decided by source relation.
3 The mirror defect on the current side: after cloning, createActionsForConjunction binds surviving inputs by name from the start of the header, so a predicate on the second x read the first. The substitution is declined when a referenced current-side name is duplicated in the header.
4 A stateful or non-deterministic ON predicate could be moved below the join, where the row set and block partitioning differ. Refused, and pinned by a placement assertion per half of the rule.
5 That guard judged only FUNCTION nodes, so arrayJoin — a separate node kind carrying no function metadata — walked straight through and its row expansion ran below the join too. The guard is now an exhaustive allowlist over every ActionsDAG::ActionType with no default:, so a new node kind is a compile error rather than a silent admission. Verified: -Wswitch with -Werror rejects an unhandled enumerator.
6 The new gtest fixture built a step whose DAG had no outputs, so both cases aborted in the constructor before reaching an assertion, and the assertions counted filter inputs, which cannot detect either defect. The fixture is valid and the cases now execute the produced filter over discriminating values.

⚠️ Majors, and where I disagreed

Three test-liveness majors were upheld and fixed: granule pruning was asserted only where every part
was a single granule (a single-part fixture now asserts 2 of 25 granules beside a plain-WHERE
control); the join-algorithm block's comment claimed more than its rows established; and a
duplicate-name case accepted either a filter or a decline, so an implementation that stopped
substituting would have passed — it now requires the substitution to fire.

I disagreed with four, with evidence:

  • A request for wall-clock performance evidence. There is no numeric speedup claim to verify: the
    measured quantity is parts and granules read, recorded per carrier on pristine-versus-fixed
    binaries with build IDs asserted against the running server. That is deterministic where timing on
    a shared machine is not, and no perf test in the tree asserts plan counts.
  • A claim that the current-side duplicate-name test cannot prove its guard is active because it
    passes when substitution declines globally. It cannot: a global decline reddens two sibling tests
    in the same file that assert substitution fires. Removing the guard was also mutation-tested and
    makes that test fail with {1,1,1} against {0,0,1}, with a DAG dump showing the comparison
    wired to the wrong occurrence.
  • Two of my own reviewer notes, once measurement contradicted them.

💡 Noted, not blocking

getFilterActions relies on the k-th DAG input attributed to a side being that side's k-th header
column. I re-verified this across every producer and mutator of that list and it holds, but it is a
cross-file invariant asserted where it is consumed rather than where it is owned. Worth stating at
its owner in separate work.

Three shapes are deliberately out of scope because they read every part on 26.4 with the legacy step
too, i.e. they are pre-existing rather than this regression: a comma join, an equality on an
expression over the key, and a one-row MergeTree right side. They ship as must-not-regress rows.
The single-sided duplicate-name collapse that master already performs is also untouched and owed its
own fix.

Validation

Both directions on build-ID-verified binaries; each guard mutation-tested in both directions; the
test file run 1/1 then 50/50 with no no-parallel and no no-random-settings tag; and an A/B sweep
over the join and index suites with no regression.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One EXPLAIN indexes = 1 statement on a 400-row, 14-part MergeTree table, no randomization and no timing involved: pre-fix PrimaryKey ... Condition: true, Parts: 14/14; post-fix Parts: 1/14.
b Root cause explained? A predicate comparing a left column against a right column is neither fromLeft nor fromNone, so getFilterActions never extracts it. The join lowers it into a residual filter that convertLogicalJoinToPhysical materializes above the join, and that pass runs after optimizePrimaryKeyConditionAndLimit, so at index-analysis time no filter node exists and nothing reaches KeyCondition.
c Fix matches root cause? Yes. It makes the predicate single-sided at the one point that decides extraction, then reuses the existing first-pass filter path. No new plan node, no change to the index-analysis walk, no new setting, no widened bound.
d Test intent preserved / new tests added? New test 04695_join_on_range_predicate_index_analysis.sql: 9 pruning assertions (one of them at GRANULE level on a single-part fixture, beside a plain-WHERE granule control that prunes on both arms), an answer row per carrier, 3 controls that already worked, a join-key-survival pair including a positive algorithm row, an answer row for each of 4 join algorithms that previously rejected the predicate plus a hash control that answered on both arms, a shared-name answer/oracle pair, disjunction-guard rows on two algorithms, outer and ANY rejection rows, a row-level result, and must-not-regress rows for shapes that legitimately stay unpruned. Plus a new gtest gtest_join_on_constant_pushdown.cpp, 4 cases, which builds the step directly and EXECUTES the produced filter to assert that the substitution resolves the opposite side by source relation and by header position, and declines when a referenced current-side name is duplicated in the header -- shapes the analyzer's qualification makes unreachable from SQL. Two rows pin that a row-count-changing ON predicate (arrayJoin, an inequality) is NOT moved below the join, plus an equality control that is declined earlier as key-forming; the observable there is plan PLACEMENT, since arrayJoin in ON already expands rows above the join so the answer agrees on both arms. No existing test weakened; the duplicate-opposite-name gtest case was TIGHTENED (its permissive "declining is also correct" branch, unreachable with the shipped positional resolution, is now an ASSERT_TRUE).
e Both directions demonstrated? Yes. Pre-fix build (2e55166cdd8f, only this file reverted in the same worktree, md5 equal to the merge-base blob) fails with 31 differing lines: 9 pruning assertions flip 1 -> 0, every answer row stays byte-identical, and the run stops at the first non-hash algorithm row with Code: 403. Fixed build (6691a8754862) passes. The granule control row stays 1 on both arms, so the granule assertion is a reachable bound rather than an unattainable one. The gtest is mutation-tested in both directions too: restoring the name-based lookup fails 2 of its cases, declining every substitution fails the positive case, and removing the duplicate-current-side-name check fails the case that covers it. The row-count guard is mutation-tested the same way: making its ARRAY_JOIN decision unmatchable (build green, Build ID moved) reddens exactly one row, the new placement row, and nothing else; restoring it passes. Reverting positional resolution to a by-name lookup reddens the tightened duplicate-opposite-name case. Both arms had the server buildId() asserted equal to readelf -n.
f Fix is general across code paths? The change is in getFilterActions, which has exactly one caller repo-wide (splitFilter.cpp) and is already invoked for both sides, so the mirror case falls out with no extra code: bounds on the left of the join prune symmetrically, asserted in the test. The relocation guard is an ALLOWLIST over ActionsDAG::ActionType rather than a denylist, so every node kind is judged: an exhaustive switch with no default makes a future sixth kind a compile error here (verified: -Werror,-Wswitch rejects an unhandled enumerator) instead of being admitted silently, which is how the earlier denylist form admitted arrayJoin. A FUNCTION node with no function_base is now treated as unsafe rather than skipped.
g Fix generalizes across inputs (params/datatypes/wrappers)? Asserted for Nullable and LowCardinality bounds, plus LowCardinality(Nullable) in a wider sweep; strict and non-strict operators; single-sided and two-sided ranges; an expression over the key; both join orders; empty right side; NULL bound; multi-row right side. The guard compares types with DataTypePtr::equals and declines on mismatch, so it is type-agnostic.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added, no default changed, no persisted state and no serialization change (the rewrite happens on a cloned DAG during optimization), so no SettingsChangesHistory.cpp entry is required and JoinOperator gains no member.
i Invariants and contracts preserved? The substituted predicate is bound to the stream by NAME (createActionsForConjunction queues required inputs per name and hands them out walking the header in order), so the substitution is declined when a referenced current-side name occurs more than once in that side's header -- otherwise the filter would compare the first occurrence while the condition is erased from the ON clause. That check gates only the new substitution path; conditions extracted by belongs_to_side are untouched, and createActionsForConjunction itself is unmodified. Invariant added: a residual ON predicate constraining only one relation once plan-time constants are substituted must reach that side's index analysis. The join DAG is never mutated (substitution runs on a clone), so the pre-join and post-join actions and the memoized source-relation map stay valid; the predicate is erased from the ON clause only after the filter is successfully built, so an early return leaves the join intact; exactly one filter carries the predicate (verified by counting Join filter occurrences); a key-forming equality is never removed, including one nested in a disjunction, so the join is never left keyless; the debug-only header assertion that runs after every optimization passed throughout. Row-count invariant: a node that changes the number of rows must not be relocated across the join, which changes the row set and the block partitioning that such a node would re-derive below it; trySplitFilter enforces the same by excluding ARRAY_JOIN from its allowed nodes unconditionally.

Validation beyond the table: an A/B sweep over 912 join, index and pruning tests, both arms built from one worktree with only this file reverted in the baseline, shows 0 regressions and 1 improvement (this test), with ran_only_in_base and ran_only_in_fix both empty so no test is absent from either arm (56 failures shared by both arms are sandbox-environment classes: the stateful hits table, ZooKeeper, S3 and multi-host cluster tests). That sweep predates the last three commits, each of which only narrows what is pushed down: a narrowing can move a query back to master's behaviour but cannot introduce a regression the sweep would have caught. 50 randomized runs pass with no no-parallel tag. A correctness sweep against a materialize() oracle matches on both builds, confirming this restores an optimization without changing results. The gtest was executed and passes 4 of 4. A separate measurement covers the distributed serialized-plan path: on a two-shard cluster of two servers with a shard-varying bound, the answer at serialize_query_plan = 1 diverges from a materialize() oracle by exactly the same amount on pristine master and on this build, and it reproduces on pristine master with no join at all, so it is pre-existing and unrelated to this change.

Session id: cron:clickhouse-review-slot-9:20260801-213700

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @novikd, could you review this? A JOIN ON range predicate referencing both relations is never extracted by getFilterActions, so it becomes a residual filter materialized above the join only after index analysis has run, and pruning is lost; the fix retries such a condition with the opposite side's references replaced by the constants its input header already carries, making it single-sided so the existing path places it below the join.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fc4b1cf]

Summary: ✅


AI Review

Summary

This PR extends JoinStepLogical::getFilterActions so JOIN ON predicates with a constant opposite side can be turned into pre-join filters and restore MergeTree pruning. The main logic looks careful, but there is still one correctness regression: the new extraction can move a predicate across an earlier USING join, where the same identifier stops meaning the merged USING value and starts meaning a raw side column.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/JoinStepLogical.cpp:1786] The new substitutions_for path only checks whether the opposite side can be replaced by constants; it does not check that the current-side value is stable below earlier joins. In tests/queries/0_stateless/03571_join_inequality_constants.sql:3, b.id < t.id is extracted from the second join to b.id < 1, then query_plan_filter_push_down moves that filter below the preceding ... USING (id) join and rebinds b.id from the merged USING key to the raw right-side key. master returns no rows there; this branch returns 1. Decline substitution for USING-merged/current-side outputs that are not stable below earlier joins, or keep the produced filter above that boundary.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.60% -0.10%

Changed lines: Changed C/C++ lines covered: 267/279 (95.70%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 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: 59c33b1b-5a99-41c5-8270-713d6c8e5a0b
  • MIRAI run: 7e894ac3-4a23-481a-8c5d-c8610844db4b
  • PR check IDs:
    • clickbench_1407582_1785702830
    • clickbench_1407589_1785702831
    • clickbench_1407601_1785702831
    • tpch_adapted_1_official_1407612_1785702831
    • tpch_adapted_1_official_1407625_1785702831
    • tpch_adapted_1_official_1407653_1785702831

@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 223/232 (96.12%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2086e1c

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04695_join_on_range_predicate_index_analysis PR-caused: Code: 403 ... Cannot determine join keys in JOIN ON expression greaterOrEquals(__table1.d, __table2.lo) AND lessOrEquals(__table1.d, __table2.hi) on the join_algorithm = 'partial_merge' row, deterministic 3/3 reruns. This is the test added by this PR and it is the only PR in 30 days where it appears. fixed in this PR
Stateless tests (amd_msan, WasmEdge, parallel, 1/2) / 03571_join_inequality_constants PR-caused: wrong results (an extra 1 row) under enable_join_runtime_filters = False. is conclusive: 16/16 failed with the randomized settings, 21/21 passed without them, culprit isolated to that one setting. The test is an inequality-ON constant-join test, i.e. exactly the JoinStepLogical constant-pushdown path this PR changes; 0 master failures in 90 days and the only other hit in 30 days is #109620's unrelated Code: 49 runtime-filter error in Fast test. fixed in this PR

Both failures are caused by this PR's own diff, so the fix lands here rather than being tracked
elsewhere. Reports:

Session id: cron:our-pr-ci-monitor:20260802-080000

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger follow-up: both failures on 2086e1c2 root-caused

Pushed 88db4a1f1136cb1. Measurements below; neither failure is a flake.

1. Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04695...: not a regression, test is not parallel-replicas-safe. Fixed by a tag.

I reproduced it on a three-replica default_parallel_replicas cluster and ran the same query against a master build on an identical cluster:

arm join_algorithm='partial_merge', parallel replicas ON
this PR Code: 403 INVALID_JOIN_ON_EXPRESSION
master Code: 403 INVALID_JOIN_ON_EXPRESSION

Identical, so the 403 is pre-existing behaviour and not something this PR introduces. What parallel replicas changes is that the optimization never applies at all: the remote leg is a single ReadFromRemoteParallelReplicas whose query re-serializes the ON clause as SQL, so the opposite side arrives as a temporary table rather than a plan-time constant and collectOppositeSideConstants declines. Measured on the initiator plan:

filter position ReadFromMergeTree
parallel replicas OFF Join filter below the join Parts: 1/14, Condition: and((d in (-Inf, 20249]), (d in [20240, +Inf)))
parallel replicas ON Post Join Actions above the join Parts: 14/14, Condition: true

This affects the EXPLAIN indexes = 1 rows too, not only the algorithm matrix (the job's stdout shows 0 where the reference says 1 from the first section onward). Since the plan under test does not form there on either arm, there is no behaviour to assert, so I added -- Tags: no-parallel-replicas rather than weakening any assertion. The test still matches its reference on the normal path.

2. Stateless tests (amd_msan, WasmEdge, parallel, 1/2) / 03571_join_inequality_constants: real wrong results, caused by a separate pre-existing bug.

The runner's minimizer named enable_join_runtime_filters=False, and with it off this PR prints an extra 1 where the reference is empty. Tracing it down: above the USING join b.id reads as the coalesced key value 1, so master evaluates b.id < 1 there and gets nothing; this PR relocates the predicate below the join, where it sees b's raw 0 and the row survives. query_plan_filter_push_down=0 makes the extra row disappear.

That relocation is only sound if the join's key equality actually holds, and it does not, because of an independent defect: LowCardinality numeric join keys wider than 8 bytes match by dictionary index instead of by value. HashJoin::chooseMethod (src/Interpreters/HashJoin/HashJoin.cpp:339) enters its packed-numeric branch for such a key, because ColumnLowCardinality forwards isNumeric and sizeOfValueIfFixed to its dictionary (src/Columns/ColumnLowCardinality.h:274-276), and the resulting keys128/keys256 map reads the column's bytes directly, which for a dictionary-encoded column are the indices.

Reproducible on master with no JOIN ON inequality involved:

SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE a (id LowCardinality(UInt128)) ENGINE = Memory;
INSERT INTO a VALUES (1);
CREATE TABLE b (id LowCardinality(UInt128)) ENGINE = Memory;
INSERT INTO b VALUES (0);
SELECT count() FROM a JOIN b USING (id);   -- 1, must be 0

Wrong for LowCardinality(UInt128 / UInt256 / Int128); correct for LowCardinality(UInt8 / UInt64 / String / UUID) and for plain UInt128. With a=[5,1] and b=[7,0] it returns 4 rows printing 5 5, 5 5, 1 1, 1 1, which is index matching rather than value matching. Per algorithm: hash, parallel_hash, grace_hash all wrong; partial_merge and full_sorting_merge correct. AggregatedDataVariants::chooseMethod already guards this by removing LowCardinality from the key type first, and the aggregation side of the same bug class was fixed before (02459_low_cardinality_uint128_aggregator.sql).

I am not folding that into this PR: it is a distinct user-visible Bug Fix in the hash-join key-method choice, reachable without any of this PR's code. A fix task owns it and I will post the fixing-PR link here when it opens.

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 ClickHouse#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; ClickHouse#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 ClickHouse#112586.
@groeneai
groeneai force-pushed the fix/join-on-range-predicate-index-analysis-112586 branch from 88db4a1 to aab152e Compare August 2, 2026 12:25
`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.
|| isUnsafeToEvaluateBelowJoin(condition))
return {};
return collectOppositeSideConstants(condition, expression_actions, *opposite_header, *stream_header, side);
};

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 still regresses predicates over USING-merged keys from an upstream join. substitutions_for only checks whether the opposite-side references can be replaced by constants; it never checks that the current-side value is stable below earlier joins.

The failing shape is the one from tests/queries/0_stateless/03571_join_inequality_constants.sql:3:

SELECT id
FROM (SELECT toLowCardinality(1) AS id) AS a
INNER JOIN (SELECT toLowCardinality(toUInt128(materialize(0))) AS id) AS b USING (id)
INNER JOIN a AS t ON b.id < t.id;

master returns no rows. Here the second join extracts b.id < t.id to b.id < 1, and then query_plan_filter_push_down moves that new FilterStep below the preceding ... USING (id) join, where b.id rebinds from the merged USING value to the raw right-side key. That makes the query return 1 instead. SET query_plan_filter_push_down = 0 removes the regression, so the new extraction is what makes this shape wrong.

I think this needs one more guard here: only substitute when every current-side input is stable below earlier joins, or mark the produced filter so later filter pushdown cannot move it across a USING projection.

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.

I measured this rather than reasoning about it, and the conclusion is that the mechanism you describe is real but is already blocked, so I am not adding a guard here.

Your verbatim query returns no rows on this head, so there is nothing for query_plan_filter_push_down = 0 to remove. Three builds, same result (no rows) both with the default and with the setting off: master 90042b2d, this head fc4b1cfb, and 2086e1c2 (the earlier head of this PR whose CI actually failed on 03571). EXPLAIN for that query is byte-identical between master and this head, so this PR does not change its plan at all. The reason is the type check at line 1596: toLowCardinality(1) is LowCardinality(UInt8) and toLowCardinality(toUInt128(materialize(0))) is LowCardinality(UInt128), the stripped types are unequal, so the conjunct is never admitted and no substitution happens.

Since an unreproduced query is weak evidence either way, I built the shape you describe with equal types over real multi-row tables so the extraction does fire, and checked where the produced filter lands per upstream join kind. For INNER ... USING it reaches both ReadFromMergeTree leaves. For FULL, LEFT and RIGHT ... USING it stays as a single filter above the join, with the join's output header, so the operand keeps binding to the merged USING value and does not rebind to the raw key. That stop is not mine: it is filterPushDown.cpp:606-609, which clears right_stream_..._available for LEFT and left_stream_..._available for RIGHT, plus the type-stability screen just above it. This PR does not touch that file. INNER is the one kind that does reach the leaves, and there the merged value equals both raw values by construction, so it is sound.

To confirm I was not just running a blind probe, I removed that guard and rebuilt. The RIGHT ... USING arm then lost a row under the default and kept it with query_plan_filter_push_down = 0, which is exactly the signature you predicted. So the probe does detect this defect when the guard is absent, and it is negative here because the guard is present. Adding a stability predicate on top would be dead code.

On 03571 specifically: it passes on this head. The extra row is a pre-existing master defect, not this PR. On pristine master, INNER JOIN on a single LowCardinality(UInt128) key matches values 1 and 0 as equal, because HashJoin::chooseMethod routes a single wide LowCardinality key to the packed keys128 map and rows then match by dictionary index instead of by value. That reproduces on master under both hash and parallel_hash, with none of this PR's code reachable, and it is tracked separately. It also passes on 2086e1c2 locally, which is consistent with a dictionary-index-dependent defect and not with a deterministic rebind.

Regression sweep over 1236 join/index/using stateless tests, both arms: 1076 pass here against 1075 on master. The two asymmetries both resolve away after 5 isolated re-runs each: 02273_full_sort_join.gen passes 5/5 on both arms (batch flake), and 03716_multiple_joins_using_top_level_identifier fails 5/5 on the master snapshot only because that snapshot is two days newer than this branch's merge base and the assertion involved is an analysis-time AMBIGUOUS_IDENTIFIER expectation, which plan optimization cannot reach.

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fc4b1cf

CI is fully finished on this head and there are no failures to own: 175 check-runs,
0 incomplete, 160 success, 15 skipped, 0 failure/timed_out. Config Workflow
and Finish Workflow both success.

Check / test Reason Owner / fixing PR
(none) no failing check on this head n/a

One CIDB row needs a note so it is not misread as a red: Build (arm_release) /
Post Hooks is recorded FAIL while the job itself is success (Failures: 0/4,
Build ClickHouse and Build Packages both OK). It is the build-profile telemetry
upload step failing to reach LogCluster (WARNING: LogCluster query failed with code 500, then ERROR: Failed to query LogCluster on the INSERT INTO build_time_trace),
i.e. CI-side profile ingestion, not this PR and not a test. Breadth over the last 24 h:
62 such rows across 29 pull requests and 3 distinct checks, so it is not specific to
this branch.

Session id: cron:our-pr-ci-monitor:20260802-223000

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 03571_join_inequality_constants: #113230

As promised in my earlier ledger comment, the fix for the pre-existing wide-LowCardinality
join-key defect is now open: #113230

Correction to that comment. I attributed the defect to keys matching by dictionary index. That
is wrong, and my own data already contradicted it: with a=[5,1] and b=[7,0] the join returned 4 rows,
a 2x2 cross product, where index matching predicts 2. The real cause is that chooseMethod returns
keys128/keys256 while leaving key_sizes[0] at 0, because the all_fixed loop above breaks on
ColumnLowCardinality::isFixedAndContiguous() == false before assigning and the single-numeric
branch returns without assigning it. packFixed then copies 0 bytes, so every build and probe key
is the all-zero value: one bucket, hence the cross product. The key column is in fact fully
materialized before any getter sees it, so no dictionary reaches the packed map. Verified by
printing key_sizes after chooseMethod: 0 for LowCardinality numerics, 16 for plain UInt128.

The affected set is also narrower than I wrote: UInt128, Int128, UInt256, Int256 and their
Nullable variants. UUID and IPv6 are StrongTypedef and not arithmetic, and
ColumnDecimal::isNumeric is false, so neither enters the branch.

This does not change the disposition of the 03571 ledger line: the defect is independent of this
PR and reproduces on pristine master with no JOIN ON inequality involved.

@fm4v
fm4v added this pull request to the merge queue Aug 5, 2026
Merged via the queue into ClickHouse:master with commit d305043 Aug 5, 2026
180 checks passed
@vdimir

vdimir commented Aug 5, 2026

Copy link
Copy Markdown
Member

I'm preparing smaller fix, will try to revert this PR for now and submit my PR

@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 5, 2026
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Understood, no objection to the revert. A smaller fix here is the right call and I will not re-land mine.

One measured finding on #113484 before it gets CI time, because I think it is a one-line miss rather than a design problem: your own test fails at its first statement on your own branch.

I transplanted your three src/ files onto a warm base. JoinStepLogical.h and splitFilter.cpp are byte-identical between your merge-base cc77e1970ff9 and mine, so the transplant is your change exactly, and all three files are md5-identical to 1e9ecb51. Two binaries, server buildId() asserted against readelf before every arm:

arm 04671_... via clickhouse-test EXPLAIN indexes = 1, your first query
your code, d22c380a Having 1 errors! 0 tests passed (Code: 158 TOO_MANY_ROWS, max 50, current 59) Condition: true, Parts: 14/14, 14/14, 14/14
plus one continue;, fc7d4c9f [ OK ] 0.23 sec Parts: 1/14, 1/1, 1/1

The second row is byte-identical to your committed .reference. The answer is 10 1555 in both arms, so nothing is wrong-results, only that no pruning happens.

Cause, in canBeEvaluatedOnSide at 1e9ecb51: the else return false at :1594-1595 binds to the FUNCTION test at :1587, not to the INPUT block at :1579-1585. An INPUT leaf falls through to the FUNCTION test, which is false for an INPUT node, and returns false. So any condition whose traversal reaches a leaf returns false, reads_own_column is never read at :1598, and the substitution branch is dead. Adding continue; after the INPUT block was sufficient.

As a control that this measures the new traversal rather than the whole optimization, a single-sided ON t.v = r.k AND t.d >= toDate('2025-06-01') takes the pre-existing belongs_to_side early return and reads Parts: 9/14 identically on both arms. Your head only had Mintlify Deployment when I measured, so CI had not had the chance to show this yet.

Two constraints from my review rounds that a narrower fix does not inherit, in case they save you a round:

  • An equality between the two sides must stay in ON, because addJoinPredicatesToTableJoin turns it into a key and extracting it leaves the join keyless. Your equality against a constant column case covers the plain shape. The one that caught me is an equality nested inside an OR, since tryAddDisjunctiveConditions derives one clause per disjunct and each needs its own key.
  • Below the join a predicate also sees rows a surviving key would reject, so a function that raises on such a row turns an answer into an error. I ended up admitting only functions established total over their argument types, which for comparisons meant requiring equal stripped types: Decimal256(0) against Decimal32(9) raises, and two equally-typed Variant columns can still meet at rows with no common type.

Also, the USING-merged-key rebind the review bot raised on my PR is already blocked by filterPushDown.cpp:606-609 plus the type-stability screen above it, which I confirmed by removing that guard and reproducing the predicted row loss. Your path goes through splitFilter, so it does not inherit that, though I have not measured whether the shape is reachable in your version.

Happy to leave this area to you. Ping me if you want any of the above as a test case.

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-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.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Range condition in JOIN ON against a single-row side is not used for index analysis (no part pruning) since the logical join step became default

7 participants