Repository navigation
Fix wrong results from cross-type equi-key filter push-down, and enable it for a plain INNER JOIN - #117973
Conversation
…INNER JOIN A `WHERE` predicate on one join key of a plain `INNER JOIN` did not reach the other table as an index condition when the two join keys had different types, so that table was read in full. The same query with matching key types used the other table's primary key. Results were always correct; only the plan lost the condition. Reported in ClickHouse#116395, whose body notes that `INNER JOIN` behaves the same as the `RIGHT`/`LEFT` shape fixed in ClickHouse#103478. `tryPushDownOverJoinStep` has exactly one producer of equi-key equivalence entries for keys whose two sides differ in type, because the ordinary producer `buildEquialentSetsForJoinStepLogical` needs equal input types for its Union-Find. That producer was gated on at least one side being unavailable for push-down, and a plain `INNER JOIN` clears neither availability flag: one flag is cleared only for `JoinKind::Left`/`Right`, both only for `isAnyInnerJoin` (`Inner` with strictness `Any`/`RightAny`, while a plain `INNER JOIN` has `All`), and the right one only for ASOF and `JoinStepLogicalLookup`. So both equivalence maps stayed empty for such keys, `splitActionsForJOINFilterPushDown` had nothing to substitute, and the opposite input was read with `Condition: true`. `ANY INNER JOIN` already worked, precisely because clearing both flags turned the gate on, which means the feature was granted to the more delicate kind and withheld from the simpler one. The gate was redundant rather than a soundness condition, so it is deleted. Availability is already applied per map further down, where the equivalence lists are built, so a pair registered for a side that cannot take the filter is inert. Soundness comes from the per-substitution guard, which is untouched: it requires the replaced name's JOIN output type to be the two keys' least supertype, which rejects a narrowing cast and a column the join widened for an unrelated reason such as `join_use_nulls`. A plain `INNER JOIN` emits a row only where the two keys are equal in that supertype, so a predicate on one key implies the same predicate on the cast of the other, and pushing it can only drop rows that could not have survived the join. Measured on 1M rows per side, `Date32` against `Date`, with the predicate on the wider key: the other table goes from `Condition: true` and 122/122 granules to the join's own `_CAST(b, 'Date32')` range and 1/122 granules, 1008282 rows read down to 16471, identical result. Every other join kind is bit-identical before and after, including `ANY`/`RightAny INNER`, `LEFT`, `RIGHT`, `LEFT` converted to `INNER`, key pairs with no least supertype, and a predicate on the narrower key. Four arms are appended to `04117_join_equi_key_filter_pushdown_right_full`: both cross-type key orientations, an equal-type control, and a result assertion. They compare the two granule counts of a read rather than matching a literal total, because a total pins the part layout that CI randomizes; the side carrying the predicate is ordered by `tuple()` so it can never prune, which is what identifies the pruning read as the opposite input. Co-Authored-By: Claude Opus 5 <[email protected]>
… query Widening the cross-type registration gate to plain INNER JOIN put one unsound case in reach. `add_replacement` makes a name substitutable by the opposite side's key, and the pushed-down filter then carries a copy of that key's sub-DAG while the JOIN still computes its own copy for the key matching. If the key does not return the same value twice within one query, the pre-join filter judges a row on one draw and the join matches it on another, so rows that satisfy the query's own WHERE are discarded. The step-level veto in `tryPushDownFilter` does not cover this: it inspects the post-join WHERE DAG, and such a key lives in the JOIN ON clause. Measured on a 10-row fixture with a key of `toInt32(rowNumberInAllBlocks() + r.x * 0)` and `WHERE l.a BETWEEN 5 AND 6`: correct rows with `query_plan_filter_push_down = 0`, no rows with it enabled. The same shape with the two key types made equal is already wrong on a pristine binary, so the equal-type path has the same exposure; that is a separate root cause and is deliberately not changed here. Decline the substitution when any function in the source key's sub-DAG is not deterministic within the query. `isDeterministicInScopeOfQuery` rather than `ActionsDAG::hasNonDeterministic`, because the latter forwards to `isDeterministic` and would also decline a key derived from `now`, which is stable within a query. Also disambiguate the comment on the registration gate: it now says which availability flag admits which map, since the map keyed by one side's name is the one applied to the filter pushed to the other side. Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit's stability check tests `node.type == FUNCTION`, but `arrayJoin` is a separate `ActionsDAG::ActionType`, kept apart precisely because it changes the number of rows. A cross-type equi-key built over an `arrayJoin` therefore still reached `add_replacement`, which copied its sub-DAG into the filter pushed to the opposite input while the JOIN kept computing its own copy for the key matching. The rows are then expanded twice and each match is reported once per extra copy. The existing mitigation cannot reach this. `fix_predicate_for_join_logical_step` snapshots the pre-join DAG's `ARRAY_JOIN` nodes and calls `ActionsDAG::removeNodes`, which erases a node only when it is not reachable from the outputs. When the pushed predicate depends on the array-joined value, which is the case here, the removal is a no-op. Measured on a 10-row fixture, key `toInt32(arrayJoin([r.x, r.x]))` and `WHERE l.a BETWEEN 5 AND 6`, in both join orientations: 4 rows with `query_plan_filter_push_down = 0` and 8 with it enabled. A pristine binary returns 4 either way, so the exposure comes from widening the registration gate. Two controls hold the attribution: the same shape with a plain column source does not move, and neither does a plain-column shape over a fixture holding each value twice, which reproduces the row count of 4 without an `arrayJoin`. Turn the check into an accept-list over node types, so an `ActionType` added later is declined rather than silently admitted. Inputs, constants and aliases are accepted; a function is accepted only when it is neither stateful nor non-deterministic within the query; anything else declines the substitution. The statefulness term is included for parity with this pass rather than for a reproducer: `tryPushDownFilter` already refuses to push any filter containing a stateful function, so injecting a stateful sub-DAG into a filter that passed that veto would defeat a condition this file already applies. The same row-changing exposure exists on the equal-type equi-key path, where it predates this change and is produced by `buildEquialentSetsForJoinStepLogical`; that is a separate root cause and is deliberately not changed here. One arm is appended to `04117_join_equi_key_filter_pushdown_right_full`. Its array repeats its element so that the second expansion changes the result rather than only an intermediate row count, and it needs no settings pin because `query_plan_filter_push_down` defaults to enabled and is not randomized by the test runner. Co-Authored-By: Claude Opus 5 <[email protected]>
The cross-type substitution added earlier in this branch replaces a join key
name by the opposite side's key, cast to the two keys' least supertype. That is
sound only for predicates that cannot tell two join-equal keys apart, and a
float breaks it: `IDataType`-level equality and the comparison a merge-based
algorithm joins on both treat `-0.0` and `+0.0` as equal, so two keys can be
join-equal while differing bit for bit. A bit-sensitive predicate then disagrees
between the two sides and the filter pushed to the opposite input drops a
matching row.
Measured on a `Float64`/`Float32` `INNER JOIN` over `+0.0` and `-0.0`, with
`join_algorithm = 'full_sorting_merge'` and a second non-zero matching pair so
that an empty result is distinguishable from nothing having matched:
SELECT l.a, r.x FROM f64 AS l INNER JOIN f32 AS r ON l.a = r.x
WHERE reinterpretAsUInt64(l.a) = 0
returns the matching row at `query_plan_filter_push_down = 0` and, before this
commit, nothing at `1`. `EXPLAIN PLAN actions = 1` shows the right input
carrying `reinterpretAsUInt64(CAST(x AS Float64)) = 0`, so the substitution
happened rather than the row being lost elsewhere; with this commit the plan is
byte-identical to the pre-branch one and the row comes back. Two controls hold
the attribution: a sign-insensitive predicate `l.a = 0` does not move on any
binary, and the same bit-sensitive predicate over an `Int64`/`Int32` pair does
not move either. The algorithm is pinned because the hash algorithms hash the
key bitwise and never match the pair at all.
The check walks the supertype with `IDataType::forEachChild` instead of testing
`isFloat(removeNullable(removeLowCardinality(supertype)))`. The flat form is not
sufficient: `Array(Float64)` against `Array(Float32)` loses the same row and
neither wrapper-stripping predicate looks inside an `Array`.
`Nullable(Float64)` against `Float32` loses it too, which the flat form would
have caught. `Tuple(Int64, Float64)` against `Tuple(Int32, Float32)` did not
reproduce but is declined as well, since the supertype is what the JOIN
compares in.
The supertype is tested rather than either input type. `Decimal` is
deliberately not declined: its equality is bit-identity at a fixed scale, and
the existing rule that the JOIN output type must equal the supertype already
forbids a narrowing scale change. A `Dynamic` supertype needs no separate
decline because a `Dynamic` join key is rejected before this code runs, and
`Variant`, `LowCardinality(Float32)` against `Int64`, and `JSON` keys have no
supertype on this path at all.
3378 stateless tests covering the join, push-down, prewhere, predicate and
float surfaces were run through the pre-guard and post-guard binaries and
byte-compared. The only behavioural difference is this test's new arms; every
other candidate reproduced identically when either binary was run twice.
The equal-type substitution path carries the same float hazard, and is left
alone here exactly as the row-changing and not-stable residuals are.
Also rephrases the neighbouring stability comment, whose last sentence was
garbled.
Co-Authored-By: Claude Opus 5 <[email protected]>
The flat float arm was a plain INNER JOIN, which cannot reproduce on a released
build: the cross-type equi-key producer only registered when one side was
unavailable for push-down, which a plain INNER JOIN never is. So nothing in the
suite covered the half of the float decline that is broken today.
The registration path for LEFT, RIGHT and ANY INNER predates this branch, so the
same fixture reproduces there. Measured on the released static builds, and on the
shared master snapshot:
SELECT l.a, r.x FROM left_f64 AS l LEFT JOIN left_f32 AS r ON l.a = r.x
WHERE reinterpretAsUInt64(l.a) = 0 SETTINGS join_algorithm = 'full_sorting_merge'
default settings query_plan_filter_push_down = 0
26.8.2.7-lts 0 0 (wrong) 0 -0
26.6.4.55-stable 0 0 (wrong) 0 -0
master snapshot 0 0 (wrong) 0 -0
this branch 0 -0 0 -0
+0.0 and -0.0 are equal to the comparison a merge-based algorithm joins on, so
the row matches; substituting one side's key for the other lets the bit-sensitive
predicate drop the right row, and a LEFT JOIN then reports the left one with r.x
defaulted to 0. The push-down-off column is the control: correct everywhere, so
the divergence is the substitution and not the fixture or the comparator. On
26.6.4.55 the __filterpushdown cast name is visible in the plan as well.
The nested-float arm stays on INNER, so both registration entry conditions are
still exercised, and the arm count does not change.
Co-Authored-By: Claude Opus 5 <[email protected]>
Corrects the claim in e365fc5 that "a Dynamic supertype needs no separate decline because a Dynamic join key is rejected before this code runs". That is false. All three rejection sites sit inside a test of allow_dynamic_type_in_join_keys (JoinStepLogical.cpp:753, PlannerJoins.cpp:881, TableJoin.cpp:959), and that setting is user-settable. With it on, the supertype of any pair containing a Dynamic is Dynamic, DataTypeDynamic has no forEachChild override, so the walk visits nothing and isFloat(Dynamic) is false. The substitution was admitted and lost a row. The earlier measurement it was drawn from (Dynamic vs Int64 -> Code: 44) was taken at the setting's default. Reproducer, a Dynamic holding Float32 +0.0 against a Float32 -0.0, plain INNER JOIN, SETTINGS allow_dynamic_type_in_join_keys = 1, join_algorithm = 'full_sorting_merge', bit-sensitive predicate on the Dynamic side: before after query_plan_filter_push_down = 0 0 -0 0 -0 query_plan_filter_push_down = 1 (no rows) 0 -0 dynamicElement(_CAST(x, 'Dynamic')) on the opposite input present absent Two controls. With the setting left at its default the same query is Code: 44, so the setting is what opens the shape. An Int64/Int32 pair carrying the same bit-sensitive predicate returns its row at both push-down settings before and after, and its substitution is still registered afterwards, so the decline is not a blanket disable of cross-type substitution. JSON is declined by the same predicate because DataTypeObject::forEachChild visits only typed paths. It carries no reproducer of its own, measured rather than assumed: a float in a typed path is already declined by the walk (the row survives at both settings, no substitution in the plan), and the only shape that hides one, a dynamic path, matches nothing at all - JSON(max_dynamic_paths=8) against JSON(max_dynamic_paths=16) returns no rows even for byte-identical {"a":0.0} on both sides. A float-free cross-type JSON key likewise registers no substitution, so the decline gives up nothing. What it does give up, for Dynamic: a float-free Dynamic/Int32 key did receive the substitution and no longer does. Results are identical either way, so the cost is a push-down opportunity, never a result. Co-Authored-By: Claude Opus 5 <[email protected]>
Which `JSON` paths get their own subcolumn is a property of the column, not of the type. Two columns can hold the same logical value and still place a path differently: with `JSON(max_dynamic_paths = 2)` on the left, two earlier rows fill both dynamic slots so `x` lands in shared data, while `JSON(max_dynamic_paths = 1)` on the right keeps `x` dynamic. The values stay join-equal, but `JSONDynamicPaths` reads that placement rather than the value, so substituting the opposite side's key into a predicate over it drops a matching row. `isObject` in the cross-type equi-key guard is what prevents that. It is load-bearing for correctness, not a symmetry with `isDynamic`, and it had no test. Both directions on the real runner, randomization on, Build ID asserted against the running server each way: guard present, 264c49e1b0366591: 04117 OK, new arm row returned `isObject` reverted, 1daebd7643a0: 04117 FAIL, new arm row lost The mutant's `.reference` diff is that one row and nothing else. 50 runs self-concurrent at `--jobs 8` all pass, worst single run 1.89 s. The arm pins no join algorithm, unlike the float arms above it: what disagrees is the predicate and not the equality, so the row is lost on the reverted binary under each of `full_sorting_merge`, `hash`, `partial_merge`, `grace_hash` and the default, and under Compact, Wide, `index_granularity = 1` and small `index_granularity_bytes` parts. This corrects the conclusion recorded for `JSON` while the float decline was being built, that `JSON` carries no reproducer and the predicate could be dropped. That probe asked whether a hidden float can escape the walk over the supertype, a different question which it answered correctly. The hazard is the path layout, which the static type does not describe either. The guard's comment stated only the float half of that reason, which is what invited the deletion. It now says a `Dynamic` or `JSON` supertype describes neither the runtime contents nor the representation, and that a predicate can read either. Co-Authored-By: Claude Opus 5 <[email protected]>
…dicate `isConstant` and `toColumnTypeName` return different results for the same value depending on the constness of their argument. `IFunction.h` names exactly these two as the counterexamples to full determinism, and both report `isDeterministic() = false` while inheriting `isDeterministicInScopeOfQuery() = true`. The JOIN filter splitter tests only the in-query flag (`ActionsDAG.cpp:3228-3235`), so it admits such a conjunct for cross-side push-down, and a cross-type substitution then swaps a non-constant key for a constant one, which is the one thing full determinism rules out: SELECT l.a FROM t AS l INNER JOIN (SELECT toInt32(0) AS b) AS r ON l.a = r.b WHERE isConstant(l.a) = 0; With `t` holding a single `Int64` row `0`, the pushed filter on the opposite input becomes `isConstant(CAST(0 AS Int64)) = 0`, which is false where `isConstant(l.a) = 0` was true, so the matching row is dropped: one row with `query_plan_filter_push_down = 0`, none with `= 1`. Both map directions are affected. Every substituted name that reaches such a function is now dropped before the split, cross-type and equal-type alike. Distinguishing the two would need extra bookkeeping for no gain, and one unconditional rule also closes the equal-type instance of the same hole. Two narrower alternatives were rejected. Declining a constant source key breaks the released headline case, `RIGHT JOIN (SELECT 1 AS k) USING (k) WHERE k = 1`, whose whole point is to reach the other table's index. Testing full `isDeterministic()` inside `getConjunctionNodes` is shorter but changes a shared signature and also rejects zero-argument non-deterministic nodes, so `WHERE join_key < now()` would silently lose cross-side push-down; measured here, that push-down survives, because a zero-argument function has no input to drop. `dictGet(dict, 'attr', join_key)` does lose substitution for its conjunct, which is conservative and intended. Same-side push-down is untouched throughout.
Internal pre-publication review (click to expand)An independent model reviewed this branch cold over six rounds before publication. ❌ Every correctness finding it raised was agreed and fixed in the commits above: a cross-type
💡 The changelog scopes the declines to keys of differing type. The representation one is broader: |
|
Workflow [PR], commit [79ca417] Summary: ❌
AI ReviewSummaryThis PR enables cross-type equi-key filter push-down for analyzer Missing context / blind spots
Findings
Final VerdictLLVM Coverage ReportMeasured on commit 79ca417.
Changed lines: Changed C/C++ lines covered: 112/117 (95.73%) · Uncovered code |
|
cc @novikd @nickitat, could you review this? The cross-type equi-key producer in the filter push-down pass was gated on one side being unavailable for push-down, which a plain |
…sentation
`splitActionsForJOINFilterPushDown` replaces a both-streams conjunct's equivalent inputs
with the opposite side's columns, so such a conjunct must read no more than their value.
That was enforced by erasing the input's name from `equivalent_columns_to_push_down`
before the split, which is coarser than the split itself: every conjunct on that key was
held back, not only the unsafe one.
Measured on a plain `INNER JOIN` of two 1M-row `MergeTree` tables with equal `UInt64`
keys and `WHERE dictHas('d', l.id) AND l.id BETWEEN 100 AND 200`, the opposite input read
123/123 granules where master reads 1/123. `dictHas` is not an introspection function:
`FunctionDictHas::isDeterministic()` is `false`, as it is for `dictGet` and `joinGet`, so
an ordinary warehouse filter lost the index condition this pass exists to provide.
Moving the check into the split makes it per conjunct and puts it at the site of the
substitution it guards. `WHERE l.id < now() AND l.id BETWEEN ...` is unaffected either
way, because `now()` has no substitutable input below it. The `isConstant` decline is
unchanged, including for the equal-type substitution master gets wrong: an `Int64` key
joined to a constant `Int64` subquery under `WHERE isConstant(l.a) = 0` returns no row on
master with push-down on and the row with it off.
`isConstant(l.a)` is false for every row of that read; what holds is the comparison `isConstant(l.a) = 0`. The comment claimed the former, which reads as the opposite of what the arm relies on.
Build profile diff (arm_release)Comparing commit See the job log for details. |
Both guards added earlier in this pull request walk an outer `ActionsDAG`: the equi-key one over the key's own nodes, the conjunct one over `Node::children`. A lambda keeps its body in a separate inner `ActionsDAG` and the node holding it reports the `IFunctionBase` determinism defaults whatever the body does, so neither walk saw a body that is unstable within the query or that reads a column's representation. Measured on the previous head of this branch, 100000 right rows, one matching left row, key `toInt32(arraySum(arrayMap(z -> rand(z) % 2, [r.x])))`: 49844 rows with `query_plan_filter_push_down = 0` against 25078 with it on, i.e. half the matching rows dropped, because the pushed filter draws the key once and the `JOIN` draws it again. Pristine master returns 50084 and 49979: the shape is reachable only through the cross-type registration this pull request adds. The conjunct side loses a row the same way for `arrayExists(y -> rand(l.a + y) % 2 = 0, [1])`. Two carriers had to be covered. A lambda that captures a non-constant column stays a `FunctionCapture` node; one whose captures are all constant is folded to a constant holding the lambda object, whose own captures can hold further lambdas, so the walk recurses through both. A subexpression of a body that does not reference the lambda argument is hoisted into the outer DAG and was already visible, which is why an argument-free `rowNumberInAllBlocks()` never reproduced. Deterministic lambda bodies are unaffected at any nesting depth, so the optimization this pull request adds still applies to them. `arrayJoin` cannot be hidden this way: a body that references the lambda argument is rejected with `BAD_ARGUMENTS`.
A higher-order function hands its remaining arguments to the lambda as its formal parameters, and those arguments are siblings of the node holding the body, not descendants of it. The conjunct walk only tainted what sat below that node, so an equi-key reaching the body as a formal parameter stayed on a clean path. Measured with 100000 matching pairs and `arrayExists(y -> rand(y) % 2 = 0, [l.a])`: 50183 rows with `query_plan_filter_push_down = 0` against 25003 with it on, against 50071 and 50076 on pristine master. The same conjunct with a deterministic body returns 50000 either way, before and after. The equi-key guard needs nothing here: it walks every node of the key's own sub-expression and rejects the key outright, so where the body sits in that sub-expression does not matter. `ALIAS` nodes are resolved before looking for a body, since an alias is the same value as the node below it.
`getConjunctionNodes` already refuses a conjunct that is not stable within the query, and that is what makes a both-streams conjunct safe to evaluate once per side and drop from the post-join filter. It reads only the visible functions, though, so a lambda body escaped it and was drawn twice. Two positions were measured, both with 100000 matching pairs and both against pristine master, which loses nothing: `arrayExists(y -> rand(y) % 2 = 0, [l.a])`, the key as the formal parameter: 50183 rows with `query_plan_filter_push_down = 0` against 25003 with it on. `arrayExists(y -> rand(y) % 2 = 0, materialize([1])) = toUInt8(l.a * 0)`, the body beside the key rather than above it: 50165 against 24754. The second position is why this walks the conjunct's whole sub-expression rather than the paths reaching a substituted input: the body there is in a branch that reaches no such input. The same conjunct with the visible `rand()` is already refused, before and after, which is the behaviour this extends to a hidden body. The equi-key guard's own walk is unchanged, since it already visits every node of the key and rejects the key outright. This also drops the lambda inspection from the representation check added earlier: no spelling of it changes a result. A body subexpression that does not read the lambda's formal parameter is hoisted into the outer expression, where the check already sees it, and one that does read it is never constant, so `isConstant` answers the same before and after substitution. Measured on both the captured and the formal-parameter spellings, with and without the inspection: one row either way.
…ness Two holes in the previous two commits, both measured. A body subexpression that reads the lambda's formal parameter is not hoisted into the outer expression, and it is not automatically non-constant either: the formal comes from the call's array argument, so when that argument is a constant array the parameter is constant too. With `arrayExists(y -> isConstant(if(y, l.a, l.a)) = 0, [1])` over an `Int64` key against a constant `Int32` subquery, both branches of the `if` become the substituted constant and the read flips. Measured: `0` with `query_plan_filter_push_down = 0` and no row with it on; pristine master returns `0` either way. So the representation check needs the body after all, in the capture position and in the formal-parameter position. The stability check took only `isDeterministicInScopeOfQuery`, while both the outer filter gate and the equi-key guard also reject a stateful function. A stateful body is duplicated across the two inputs exactly like an unstable one, so it now uses the same predicate as the equi-key guard.
The pre-push gate measured 0.96 word overlap between them and the commit messages; the reasoning belongs in the latter.
The block reached five lines because the lambda note was appended to the existing constness note, and it repeated `isConstant`/`toColumnTypeName` verbatim from the pull request text. The two properties a reader needs at that spot, that a both-streams conjunct's inputs are replaced by the opposite side's column and that a lambda body reads the arguments it does not capture, now take one line each. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Fixing PR for the |
…shes `tryPushDownOverJoinStep` substitutes the opposite side of a cross-type equi key into a predicate it pushes below the join, and keeps that key's own name whenever it already carries the two sides' least supertype, on the grounds that such a key is not cast by the join either. That name is not unambiguous. `join_use_nulls` makes the join null-extend one side before the join and alias the widened column back to the original name, so the expression DAG deliberately holds two nodes called `__tableN.id` with different types: the pre-join input, and the post-join output action. The pushed-down predicate's inputs are matched to the join's output actions by name alone, and merging the two DAGs re-points the children of nodes that were already built. A `_CAST` in the predicate therefore ended up with a `Nullable(UInt16)` child while keeping `result_type = UInt64`, and executing it raised `LOGICAL_ERROR: Unexpected return type from _CAST. Expected UInt64. Got Nullable(UInt64)`. Release builds return that to the client for a query with a well-defined answer; debug and sanitizer builds abort, which is how it was found (`Stress test (arm_tsan)`). Take the bare name only while it denotes a single type at that point in the plan, and otherwise fall through to the uniquely named replacement this function already builds for the cast case. The sibling equal-typed substitution above solves the same problem the same way, by renaming to `__filterpushdown_src<name>`. The replacement's materializer now adds an alias rather than a cast when the types already agree, so plans that need only the fresh name do not carry an identity `_CAST`. `ActionsDAG::mergeInplace`'s name-based binding is left alone on purpose: its contract is name-based and shared by many callers, so the ambiguous name is corrected where it is created rather than guarded where it bites. The substitution was added in ClickHouse#103478. My own ClickHouse#117973 lists this case under "Not fixed here" and leaves the shortcut untouched. Co-Authored-By: Claude Opus 5 <[email protected]>
9042501
|
@groeneai @vdimir @fm4v — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
Checked the finding: the equal-typed equi-key path really does lack these guards, but it is not from this PR. All seven shapes I measured give byte-identical output on a master build that predates the merge, and the only hunks here in |
…-pushdown Resolves the one conflict in `ActionsDAG::splitActionsForJOINFilterPushDown`: master's cross-type representation gate (from ClickHouse#117973) and this branch's totality gate filter the same both-streams conjunct list, so both blocks are kept, this branch's first. Co-Authored-By: Claude Opus 5 <[email protected]>
…icts The plan-time JOIN-kind rewrites (outer -> inner, ANY -> INNER/SEMI/ANTI) decide from a one-row evaluation of the WHERE filter with constant stand-ins for the inputs of the null-extended side. A function that reads its argument's representation (`isDeterministic() == false`, e.g. `isConstant`) answers for a stand-in no runtime row has: a row of the outer join reaches the filter as a full column. And for a constant of that side the answer depends on the rewrite itself, because after it the filter can run below the join, where the constant is still a constant. Both made `WHERE isConstant(b.x) = 0` look always false and dropped or added rows. Extract the representation-read walk of `splitActionsForJOINFilterPushDown` (ClickHouse#117973) into `ActionsDAG::getInputsReadByRepresentation`. In `filterResultForNotMatchedRows`, the calls that read representation are evaluated on full one-row stand-ins of the null-extended side's inputs and enter the probe as constants, and the probe gives no verdict when such an input is a constant in the side's header (checked on the header, so an input without a stand-in, e.g. an `Enum`, is covered too). `filterResultForMatchedRows` gives no verdict when the filter reads representation. Everything else keeps master's stand-ins, so `joinGet`/`dictGet`/`now()` filters over ordinary columns convert as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…gh a FULL JOIN ... USING chain Three empty Memory tables with keys UInt8 / UInt64 / UInt16 and no settings clause were enough to be rejected: SELECT a.k, b.k, c.k FROM a FULL JOIN b USING (k) LEFT JOIN c USING (k) WHERE c.k > 1; Code: 10. Not found column firstNonDefault(__table1.k, __table2.k): in block __table1.k UInt64, __table2.k UInt64. (NOT_FOUND_COLUMN_IN_BLOCK) In tryPushDownOverJoinStep, add_replacement makes a name the filter uses substitutable by the opposite side's key. When the source already carries the least supertype the JOIN does not cast it either, so the code took a shortcut: put the source in the map under its own name and add nothing to the pre-filter DAG. That shortcut silently assumed the name denotes a column of the stream the substituted filter binds against. For the second join of a FULL JOIN ... USING (k) chain the left key is the first join's coalesced USING column, carried as the join-computed expression firstNonDefault(__table1.k, __table2.k), while that join's left stream input header holds only __table1.k and __table2.k. The predicate was rewritten onto the computed name and pushed below the join, where addNewFilterStepOrThrow could not bind it. The by-name shortcut now also requires the source to be present, at its own type, in its own side's input header. That header is derived from source.fromLeft() rather than passed in, so it cannot be mis-wired at a call site: forEachEquiJoinKey admits only side-pure pairs, and the two add_replacement calls pair the right key with the right-stream vectors and the left key with the left-stream ones, so the source's own side is always the stream the substituted filter is pushed to. When the requirement does not hold the code falls through to the existing replacement, which materialises the substitute from the source's inputs, all of which belong to that stream. Admission is untouched: cross_type_equivalent_columns.insert runs before the branch and both branches key the same map, so no push-down is newly allowed or declined and only the substitute's name and the pre-filter DAG change. The equal-typed sibling path substitutes by name too, but it pushes every source it substitutes into required_actions_from_join unconditionally, so the name it promises is always provided. The physical-join path fills both maps straight from the stream input headers. The cross-type shortcut was the only substitution in this function that promised a name without providing it. Two shapes were affected, both measured on stock defaults. FULL plus LEFT or INNER was introduced on master by ClickHouse#117973, which removed the availability gate that had kept those second-join kinds out of this path, and is unreleased. FULL plus RIGHT also fails on official v26.8.5.13-lts, so that half is pre-existing on released branches. The guard added in ClickHouse#120109 covers neither: it asks whether the source's own name appears in the JOIN output at a different type, and here that name is absent from the output altogether. Beyond the new test, the same 1287 stateless tests matching join, push_down, pushdown and filter_push were run against the unpatched and the patched binary on one rig: no test regresses, and exactly one changes state, the new one. 04117 and 05217, which pin this machinery including their EXPLAIN granule assertions, pass unmodified. Co-Authored-By: Claude Opus 5 <[email protected]>
A WHERE predicate on a JOIN key is also pushed to the other side of the
JOIN, with that side's key put in place of the filtered one. Whether
that is allowed is decided with IDataType::equals, which ignores the
time zone of DateTime and DateTime64 and custom names such as Bool.
So with ON r.hour = p.hour, where r.hour is DateTime('UTC') and p.hour
is DateTime('Europe/Moscow'), WHERE toDate(p.hour) = '2024-06-02' is
also evaluated as toDate(r.hour) = '2024-06-02' in UTC, and the rows
between midnight and 3 am Moscow time are silently dropped. A plain
range such as p.hour >= '2024-06-02 00:00:00' breaks the same way,
because the string is read in the other key's time zone.
The cross-type path added in ClickHouse#117973 has the same problem one step
later: the least supertype of DateTime('Asia/Tokyo') and
Nullable(DateTime('UTC')) takes the Tokyo time zone, and the check that
it matches the replaced key uses equals as well.
Compare full type names instead, as PlannerCorrelatedSubqueries.cpp
already does for the same reason. Keys whose types are equal but not
identical are no longer substituted. A predicate on such a key is still
pushed to its own side.
This is not a recent regression: 25.8 through the current master return
the same wrong results.
Related: #116395
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results in five cases where a
WHEREpredicate on a join key was pushed to the other side of aJOINwhose two keys have different types. Such a key is no longer substituted when the keys' common type is a float, because-0.0and+0.0are join-equal but differ bit for bit; nor when it isDynamicorJSON, whose runtime contents the static type does not describe; nor when the key is unstable within the query or changes the row count; nor in a conjunct that reads a column's representation rather than its value, asisConstantandtoColumnTypeNamedo, including when such a read or an unstable function is hidden inside a lambda body. Separately, withenable_analyzer = 1, a predicate on the wider of two differently typed join keys is now also used as an index condition on the other table of a plainINNER JOIN, so it is read through its primary key instead of in full; previously onlyANY INNER JOIN,LEFT JOINandRIGHT JOINgot this.Description
@ fm4v asked for this in #116395 (comment). #103478 fixed his
LEFT JOINarm; theINNER JOINarm remains.Root cause. The cross-type equi-key producer was gated on one side being unavailable for push-down, which a plain
INNER JOINnever is, so both maps stayed empty. The gate was redundant: availability is applied per map below, as the equal-type registration above it always has.Widening it put unsound cases in reach, so the substitution now declines the five kinds above. The declines also apply to
LEFT/RIGHT/ANY INNER, so the float one fixes wrong results already released there: on 26.8.2.7 and 26.6.4.55,Float64 +0.0 LEFT JOIN Float32 -0.0underfull_sorting_mergereturnsr.xas0, not the matched-0, and is correct with push-down off. Only that decline reproduces on a release.At 1M rows per side,
Date32againstDate,dimgoes from 122/122 granules to 1/122, reading 1,008,192 rows not 2,000,000, same result.Not fixed here: key pairs with no least supertype, a predicate on the narrower key, cross-type keys that
join_use_nullswidens in the join output, which anOUTERjoin does and a plainINNER JOINdoesnot, and the unstable-key and row-count exposures on the equal-type equi-key path,
which predate this change and come from a different producer,
buildEquialentSetsForJoinStepLogical. The declines above now do read a lambda body reached throughFunctionCapture, butgetConjunctionNodesitself still judges only the functions it can see, so the other push-down paths keep that gap; my open #112700 addresses it.Workflow [PR]
Sync PR [sync-upstream/pr/117973]
Version info
26.9.1.1543(included in26.9and later)