Repository navigation
Conversation
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 ❌ Blockers found and fixed
|
Pre-PR validation gate (click to expand)
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 Session id: cron:clickhouse-review-slot-9:20260801-213700 |
|
cc @antaljanosbenjamin @novikd, could you review this? A JOIN ON range predicate referencing both relations is never extracted by |
|
Workflow [PR], commit [fc4b1cf] Summary: ✅
AI ReviewSummaryThis PR extends Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 267/279 (95.70%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 223/232 (96.12%) · Uncovered code |
CI finish ledger - 2086e1cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Both failures are caused by this PR's own diff, so the fix lands here rather than being tracked
Session id: cron:our-pr-ci-monitor:20260802-080000 |
CI ledger follow-up: both failures on
|
| 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 0Wrong 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.
88db4a1 to
aab152e
Compare
`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); | ||
| }; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - fc4b1cfCI is fully finished on this head and there are no failures to own: 175 check-runs,
One CIDB row needs a note so it is not misread as a red: Session id: cron:our-pr-ci-monitor:20260802-223000 |
Fixing PR for
|
|
I'm preparing smaller fix, will try to revert this PR for now and submit my PR |
|
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
The second row is byte-identical to your committed Cause, in As a control that this measures the new traversal rather than the whole optimization, a single-sided Two constraints from my review rounds that a narrower fix does not inherit, in case they save you a round:
Also, the Happy to leave this area to you. Ping me if you want any of the above as a test case. |
Closes: #112586
Changelog category (leave one):
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 ONclause against a single-row constant side, for exampleSELECT 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 thequery_plan_use_logical_join_stepsetting 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 reportsCondition: trueand reads every part, while the same predicate as a plainWHEREprunes. Only pruning is lost.Root cause.
getFilterActionsselects theONconditions a filter below the join can evaluate. A predicate comparing a left column against a right column is neitherfromLeftnorfromNone, 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
ALLstrictness 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
ONagainst a constant side is now answered on the non-hash algorithms rather than raisingINVALID_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.