Repository navigation
Do not reorder the conjuncts left in a WHERE by JOIN filter push-down or an aggregate projection - #122160
Conversation
…r push-down On 26.6.1.2207 a valid query at default settings is rejected with "Code: 41. CANNOT_PARSE_DATETIME ... Value 0 for day of week must be in the range [1, 7]" (issue ClickHouse#121909): the WHERE is `(adj > 0) AND (st < nxt)`, `nxt` is reachable only through parseDateTime and `adj > 0` is what keeps its day-of-week argument inside [1, 7], yet parseDateTime is evaluated on exactly the rows the guard exists to remove. splitActionsForJOINFilterPushDown rebuilds the predicate out of the conjuncts it could not push, and took their order from a std::unordered_set keyed on heap node pointers. That iteration order is unspecified, so the guard could end up behind the conjunct it guards; `and` is evaluated left to right, and FilterStep::trySplitSingleAndFilter additionally hoists the left-most atom into an earlier FilterTransform, so a demoted guard no longer guards anything. Pointer hashing also varies with allocation addresses, which is why the reporter saw it intermittently on real data. Take the order from the predicate itself instead, keeping the set only for membership. extractConjunctionAtoms splits on the same `and` predicate as getConjunctionNodes, so the walk provably reaches every element of the set; erase() doubles as the de-duplication that walk lacks, and the chassert guards the one way this could go wrong, a conjunct silently dropped from a WHERE. splitActionsForFilterPushDown, the single-side sibling, already preserves the order this way. The order being replaced is unspecified rather than defined, so no defined behaviour changes. A hash set choosing it is the violation MergeTreeSplitPrewhereIntoReadSteps already accepts a pessimization to avoid (ClickHouse#107988): the user may have intentionally interleaved a guard predicate.
…o-JOIN-condition merging Same invariant as the previous commit, violated in a second place and deterministically rather than by hash order, so it fires on every run. When an equality in the WHERE is merged into the JOIN condition, the residual `and` is rebuilt from getConjunctsList, which walks a LIFO stack and therefore emits the atoms right to left at every nesting level. A guard written before the conjunct it guards ends up behind it, and `and` is evaluated left to right. Measured with no tables and join runtime filters off, an explicit ON join plus a second cross-side equality in the WHERE is rejected with "Code: 6. CANNOT_PARSE_TEXT" and returns rows once the order is restored; query_plan_merge_filter_into_join_condition = 0 accepts it on both sides. Only rejected_conjuncts is reversed. conjuncts_list is left alone on purpose: the same loop appends the extracted equalities in list order, and those become the JOIN condition parts and from there the JOIN expressions and hash-key vectors, so reversing the list would reorder JOIN keys, which is a different question from the order of the conjuncts left behind.
…te projection's residual filter Third carrier of the same invariant as the two preceding commits. When an aggregate projection carries its own WHERE, buildResidualFilterNode strips the query conjuncts the projection already satisfies and rebuilds an `and` over the ones that are left. It builds that list from ActionsDAG::extractConjunctionAtoms, which walks the chain right to left, so the residual `and` came out reversed. FilterStep then hoists its left-most atom into an earlier FilterTransform, which puts a guarded conjunct ahead of its guard. Unlike the first carrier this one does not depend on hash iteration order, so it is deterministic: CREATE TABLE t (id UInt64, g UInt64, s String) ENGINE = MergeTree ORDER BY id; INSERT INTO t SELECT number, number, if(number % 4 = 0, toString(number), 'oops') FROM numbers(64); ALTER TABLE t ADD PROJECTION pw (SELECT g, s, count() WHERE id < 1000 GROUP BY g, s); SELECT g, count() FROM t WHERE id < 1000 AND (g % 4 = 0) AND toUInt64(s) + g > 3 GROUP BY g; `id < 1000` is covered by the projection WHERE and is stripped; `g % 4 = 0` guards `toUInt64(s)`. Before this commit the residual filter evaluated the conversion first and the query failed with CANNOT_PARSE_TEXT; with optimize_use_projections = 0 the identical query returned 15 rows, which isolates the projection path as the actor. After it, both return the same 15 rows. The test cell added here asserts that result, and its second line is the projections-off control: green on both sides by design, and what makes the first line evidence about the residual filter rather than about the ordinary filter path. force_optimize_projection = 1 makes the cell fail instead of passing vacuously if the projection is not chosen. Co-Authored-By: Claude Opus 5 <[email protected]>
…duplicated conjunct list When an equality in the WHERE is merged into the JOIN condition, the residual `and` is rebuilt from the conjuncts that were not merged, and their order matters: `and` is evaluated left to right and FilterStep hoists the left-most atom into an earlier FilterTransform, so a guard written ahead of the conjunct it guards has to stay ahead of it. getConjunctsList, which the surrounding loop walks, cannot supply that order. It walks a LIFO stack, so it reports the atoms right to left, and it carries a visited_nodes set, so a conjunct written twice is one shared DAG node reported once, at its right-most position. Reversing such a list is therefore neither the written order nor its reverse: on `WHERE (eq AND guard AND throwing) AND guard` it yields [throwing, guard], which rejects with CANNOT_PARSE_TEXT a valid query that query_plan_merge_filter_into_join_condition = 0 accepts. Walk the predicate itself instead, left to right, and keep the rejected atoms in the order that walk reports them, first occurrence winning. The local walker is a mirror of getConjunctsList with the de-duplication removed, so it can only ever report more occurrences of a node and never fewer, and the size check can fail only if the two walkers drift apart. It throws instead of degrading: falling back to the order at hand would silently restore the rejection above, and dropping a conjunct from a WHERE would return wrong results. Only the residual conjuncts are reordered. The equalities extracted into the JOIN condition keep the order they have today, because they become the JOIN condition parts and from there the JOIN expressions and hash-key vectors, and a join key order is not a user-written evaluation order. Co-Authored-By: Claude Opus 5 <[email protected]>
Two cells in which a conjunct is written twice, so one node of the expression graph stands at two positions of the WHERE and the conjunct list the rewrite works from reports it once. The first repeats the guard. That list is then already in the written order, so a release without the fix is right by accident and this cell has no pre-fix red: it reds against an implementation that restores the order by reversing that list instead of reading the predicate, which is the only assertion in the file that can tell those two apart. It is a declared regression guard, like the projections-off control further down. The second repeats the guarded conjunct, which puts it first in that list, and fails before the fix with CANNOT_PARSE_TEXT. Co-Authored-By: Claude Opus 5 <[email protected]>
The file's second case asserts that the AND-chain split renames a colliding boundary input. That assertion exists so the fourteen result cases below it cannot pass vacuously, and the collision it observes arises only when the repeated conjunct is the left-most of the pair the split reorders. Until now it arose because those conjuncts were being permuted, not because the queries asked for it. Writing the repeated condition first makes each query ask for it. Measured on this branch, the edited canary's EXPLAIN is byte identical to the one the unedited text produced before it, so the reference file is unchanged, and every result row was already identical on both sides. The right-join case repeats a left-side condition that is first already, so it is untouched. Co-Authored-By: Claude Opus 5 <[email protected]>
05256 is taken on master by 05256_mutation_scalar_subquery_nullable_placeholder, which landed after this branch was cut. Two tests sharing a number make the runner's name filter select both. File content is unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
The written-order walk was matched against the rejected conjuncts through a set, so it kept one position per distinct node. getConjunctsList can report the same node twice: its ALIAS branch pushes children.front() without consulting visited_nodes, so a predicate shaped and(ALIAS -> A, A) yields A at both positions and the rejected vector inherits the pair. Collapsing it is not an option, because an `and` of one argument is TOO_FEW_ARGUMENTS_FOR_FUNCTION, so the set form would have dropped an argument from a WHERE the server accepts today, and the size check guarding it would have raised LOGICAL_ERROR, which aborts the server in debug and sanitizer builds. Counting occurrences instead makes the size equality provable rather than merely unobserved: the walk carries no visited_nodes, so it reports every conjunct at least as often as getConjunctsList did, and a shortfall can only mean the two walks disagree. Where there is no duplicate the result is unchanged, each node still being taken at its earliest written position. Also adds the two standard headers the new std::ranges uses rely on, which compiled so far only through transitive includes. Co-Authored-By: Claude Opus 5 <[email protected]>
…turn rows The four JOIN cells asserted result rows only, and those rows are the same when the rewrite under test declines to fire: disabling query_plan_filter_push_down for the first cell or query_plan_merge_filter_into_join_condition for the others leaves all four returning 3 2. The first cell pinned neither setting, and the join-order limit, the join-order randomizer, the table swap and the filter merge are all randomized by the runner, any of which can change which side a conjunct is pushable to. Three EXPLAIN assertions, in the idiom 04650 already uses in this area, name the atom the rewrite hoists and require it to be the guard. That is false in both failure modes at once: if the rewrite never runs, the left-most residual atom is still the conjunct the query wrote first, and if the order regresses it is the throwing conjunct. The extra settings are pinned on the EXPLAIN queries because the assertion needs a deterministic plan; the four result queries keep the settings they were measured with. The fourth cell deliberately gets none. It shares the carrier, the shape and the pins of the cells above and already fails without the fix, so a fourth EXPLAIN block would add size without coverage. Co-Authored-By: Claude Opus 5 <[email protected]>
The three assertions added last round still pass when the rewrite they measure declines to fire. FilterStep::describeActions prints one `AND column:` line per atom the filter step extracts, and splitAndChainIntoMultipleFilters loops trySplitSingleAndFilter until a single non-trivial atom is left, so an N-atom residual yields N-1 such lines and not only the hoisted one. A declined rewrite therefore keeps all three atoms and extracts the pair [consumed, guard], which left position(explain, 'AND column: <guard>') > 0 true: measured 1 with query_plan_filter_push_down = 0 for the first cell, and with query_plan_merge_filter_into_join_condition = 0 for the other two. Each assertion now requires the guard to be among the extracted atoms and the atom the rewrite is supposed to consume not to be, as one statement per cell. The consumed atom is only extracted while it is still in the WHERE, so the pair is false when the rewrite declines, false when the order regresses, and true only when the rewrite fires and the guard is hoisted. Read off the binary, that atom is less(__table1.k, 100_UInt8) for the push-down cell and equals(__table1.j, __table3.j) for the two merge cells. Counting `AND column:` lines instead would red on any unrelated multi-atom filter step elsewhere in a future plan; naming both atoms stays local to each cell's own predicate. Under the same declined pins all three now print 0 where the previous form printed 1. The three-arm ledger is unchanged: master 0 0 1, the reversal implementation this branch replaced 1 1 0, and this branch 1 1 1. The query cells, their settings and the reference file are untouched. Co-Authored-By: Claude Opus 5 <[email protected]>
Dropped the narration of the new code (the reverse-push idiom, the LOGICAL_ERROR rationale, the refuted alternative) and kept the pre-existing-entity properties as one-line invariants: extractConjunctionAtoms' right-to-left order, and's left-to-right evaluation, getConjunctsList' de-duplication.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 gate findings plus 5 from my own cold
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260925-051600 |
|
Workflow [PR], commit [8514664] Summary: ✅
AI ReviewSummaryReviewed PR head Final VerdictStatus: ✅ Approve. |
Build profile diff (arm_release)Commit See the job log for details. |
…nto each side Each side's pushed filter was built as that side's own conjuncts followed by the conjuncts pushed to both sides through the join key equivalence, so a both-sides conjunct written first ended up after a side-local one. With `ON l.k = r.k WHERE (l.k + r.k) < 10 AND toUInt64(l.s) > 0`, the left side evaluated `toUInt64(l.s) > 0` before its guard `l.k + l.k < 10` and the query failed with CANNOT_PARSE_TEXT. Each side's list is now taken from one left-to-right walk of the predicate's conjuncts, the same walk the residual filter already uses. The membership of each list is unchanged. The two existing references that pinned the old order (`01655_plan_optimizations`, `03036_join_filter_push_down_equivalent_sets`) now show the right side in the written order, the same as the left side. Review comment: ClickHouse#122160 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai check the failed test, it is probably related |
Since ClickHouse#116248 and ClickHouse#122604, a WHERE over a `Memory` table is moved to PREWHERE and split into steps by `tryBuildPrewhereSteps`, so the `Memory` cases of this test no longer reach the filter-step split they were written for. With `allow_reorder_prewhere_conditions = 0`, the steps compute `enabled = 1` (the ON copy) and `toNullable(enabled) = 1` (the WHERE copy) separately under one column name, and the read fails with AMBIGUOUS_COLUMN_NAME. Which written order reaches that depends on the conjunct order, which this PR changes. That failure is a defect of the PREWHERE split, not of the filter step: master fails the same way when the ON condition is written first, and 26.8.21.12 fails with `MergeTree` tables. It is left to a separate fix. Failed run: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122160&sha=4c1aab48fb2eaede08abeddd7e866d076c948214&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Yes, it is related. Since #116248 and #122604, the The defect itself is in the In 8514664, |
|
The fix for the |
…onjunct order After merging master, ClickHouse#122160 keeps the conjuncts pushed into a `JOIN` side in the order they were written, so on the right table of the `FULL JOIN` converted to `INNER` the direct `toNullable(rk)` condition now precedes the inferred `_CAST(rk, 'Nullable(UInt64)')` one. Both conditions are still present; only their order in the `EXPLAIN` output changed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Backport #122160 to 26.10: Do not reorder the conjuncts left in a WHERE by JOIN filter push-down or an aggregate projection
…RE by JOIN filter push-down or an aggregate projection
Related: #121909
Related: #122143
Related: #111954
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A valid query over a
JOINwhoseWHEREguards a conjunct that can throw could be rejected with an error such asCANNOT_PARSE_DATETIME. Filter push-down into theJOIN, merging a filter into theJOINcondition, and an aggregate projection's residual filter each rebuilt the conjuncts they pushed into a side or left behind in an order that was not the written one, so a guarded conjunct could be evaluated ahead of its guard. Reported in #121909.Description
On 26.6.1.2207, at default settings and with no table,
... WHERE (adj > 0) AND (st < nxt)is rejected withCode: 41 CANNOT_PARSE_DATETIME:nxtis reachable only throughparseDateTime,adj > 0keeps its day-of-week argument in range, and push-down into the JOIN reverses the pair.The single-side push-down (
splitActionsForFilterPushDown) already keeps the written order. These did not:std::unordered_setof node pointers: unspecified and varying with allocation addresses, which is why the reporter saw it intermittently.ON l.k = r.k WHERE (l.k + r.k) < 10 AND toUInt64(l.s) > 0rantoUInt64(l.s)before its guard on the left. Each side now uses the same left-to-right walk;01655_plan_optimizationsand03036_join_filter_push_down_equivalent_setspinned the old right-side order.04650_join_use_nulls_repeated_on_condition_in_whereasserts the atom hoisted out of anANDchain is a renamed duplicate, which held only because the push-down reversed the pair the query wrote. ItsWHEREclauses are reordered here to ask for that collision directly, and the plan produced is byte identical to master's.#120069 (mine) and #119259 touch this function for other reasons. The other #121909 reproducers were fixed by #111954 and #122143.
Measured, on two debug builds of the same base
The hoisted atom, read off the
AND column:line ofEXPLAIN actions = 1, pretty = 0(the same splitter the pipeline uses):The reporter's query goes from
Code: 41to 17092 rows, which is what it returns withenable_join_runtime_filters = 0before and after. Hand-rewriting that query asWHERE (st < nxt) AND (adj > 0)still throws on both sides: nothing here reorders what theuser wrote. The regression test covers all six shapes, five of them without any table, and
asserts the hoisted atom by name; it passed 30 of 30 randomized runs.
Workflow [PR]
Sync PR [sync-upstream/pr/122160]
Version info
26.11.1.432-master(included in26.11and later)