Repository navigation
Conversation
`optimize_redundant_comparisons` prunes a comparison that another one on the same expression implies. It orders constants with `FieldAccurateComparison`, a total order that places `NaN` after every ordinary value, and never asks whether execution evaluates the condition in that order. Execution usually does: `executeGenericIdenticalTypes` and `executeGeneric`, and `executeArray`'s supertype branch, all end in `IColumn::compareAt` with a `NaN`-last direction hint, which is faithful through every nested column. Two shapes instead decompose the container into per-element applications of the comparison function, under which a comparison against a `NaN` is false and nothing is ordered: a pair of top-level `Tuple`s, caught by `executeTuple` before the equal-types shortcut so that identical types decompose too, and a pair of `Array`s for which `tryGetLeastSupertype` finds nothing, which reach `executeArrayLexicographic`. There is no `executeMap`, so a `Map` always reaches a `compareAt` path or throws for want of a supertype. The dispatch is decided at the type the comparison is executed at, not at the constant's declared type, because `executeWithConstString` converts a constant `String` to the other side's type and re-enters the dispatch. So a condition the row satisfies under `compareAt` and a condition the row fails under decomposition both reached the ordered analysis, the range arm pruned one as the weaker bound, and the survivor admitted a row the pruned bound excluded. Neither constant has to hold a `NaN` for this; only the stored value does. Classify the pair of types where the filter is registered and route a decomposed comparison to the existing opaque-filter path, which the rebuild tail re-emits with its original node and index. Only the top level needs classifying, since a comparison that reaches `compareAt` follows the same order all the way down. Testing `tryGetLeastSupertype` rather than type equality keeps the folds for `Array` pairs that do differ but have a supertype, which execution really does evaluate through `compareAt`. The change can only decline a fold, so it cannot alter a result that is correct today. Folds are given up for the two shapes above; scalar folds are untouched, including with a `String` constant. The principle is already in this file from `optimize_and_compare_chain`, whose `ComparisonOrderDomain` gate refuses to relate comparisons that do not share one ordering, and whose comment notes that the filter seeding is domain-agnostic. That seeding is this path. `ComparisonOrderDomain` itself is not reusable here: it answers a type-pair question, and two equal `Tuple` types report one valid domain while execution still decomposes them. Each of the new test's nine arms was shown to redden under a distinct mutation of the predicate. Co-Authored-By: Claude Opus 5 <[email protected]>
`comparisonDecomposesContainer` decides whether a comparison is evaluated in the order the pruning analysis reasons in. `executeWithConstString` converts a constant `String` to the other side's type and re-enters the dispatch, so a `String` operand has to be read as that other type. The first version of the helper did that only when the `String` was the constant. `tryOptimizeAndCompareNotEqualsChain` picks the operand that plays the constant by taking the left one whenever it is a non-NULL `ConstantNode`, so when both operands are constants the right-hand one becomes the expression. A multi-column scalar subquery reaches this pass as a `Tuple` `ConstantNode`, and inside an ASOF `JOIN ON`, spelled `(SELECT nan, 9.) >= '(3,3)'`, it left the `String` on the expression side. The helper saw `(String, Tuple)`, normalized nothing, and reported the comparison as ordered. Two such conditions were then compared in the `String` rendering, where `'(4,4)' < '(nan,9)'`, so the `nan` bound was pruned as the weaker one while execution decomposes it and evaluates it as false, and the `AND` gained a row. Normalize whichever operand is the string. The only other shape this reaches is a `String` column against a container constant, which has no common type at all. There the fold was suppressing a `NO_COMMON_TYPE` error and answering `0` for a query the server cannot execute; it is now rejected, the way that same operand on its own and that same query with the optimization disabled already were. Pin `optimize_and_compare_chain = 1` on the arms that check results. `clickhouse-test` disables that setting with probability 0.05, so pinning it to 0 ran the reported queries only in the configuration a user does not have, and that is precisely the configuration where `tryOptimizeAndCompareChain` calls `addComparisonFilter` with pruning enabled and appends a plain executable conjunct on an ALWAYS_FALSE verdict. The old header also said the runner randomizes `optimize_redundant_comparisons`, which it does not: that setting does not appear in `tests/clickhouse-test` or `ci/` at all.
The first paragraph restated `comparisonDecomposesContainer`'s own doc comment nearly verbatim, and the PR description states the same facts a third time. What is left is one sentence for what the test pins, plus the paragraph on why each setting is pinned per arm class, which is not written down anywhere else.
…omparison Field orders a Null by its type tag, which is the lowest one, so a NULL nested in a container sorts before every value. Execution reaches IColumn::compareAt with a direction hint of 1, under which ColumnNullable sorts NULL after every value. The pruning analysis therefore ranked two such constants in the opposite order from the one the query is evaluated in and pruned the bound that excludes the row. The screen is on the constant's Field rather than on its type: the deduction depends only on the two constants' relative order, a Field carries no LowCardinality to strip, and a type-based test would also give up folds whose constants hold no NULL. Comparing two nullable-element containers yields a non-nullable UInt8, which is why the existing nullable-result screen does not already cover this.
…eratively
`fieldContainsNull` switched over `Array`, `Tuple` and `Map` only. `Object`, which
is what a `JSON` value is held in, is a map rather than a vector, so a loop written
over the shared `FieldVector` could not reach it and a constant such as `{"a":null}`
was still taken as ordered. `Field` orders that `Null` by its type tag, before every
value, while `ColumnObject::compareAt` delegates each path to its own column and
`ColumnNullable::compareAtImpl` returns the direction hint for a null, that is,
after every value. Pruning then kept the bound execution treats as the looser one,
and a row the `AND` excludes was returned.
The walk is now an explicit worklist over an `absl::InlinedVector`. `Field.h` states
that these four containers nest `Field`s inside `Field`s and that a recursive copy or
destroy overflows the native stack for a deeply nested value, which is why `Field`
handles them iteratively itself, and a `JSON` value's depth comes from the data rather
than from the column type. `containsOrderInconsistentValue` in `MergeTreeData.cpp` is
the same walk for the same reason.
`comparisonDecomposesContainer` needs no `Object` shape, because two `JSON` values are
type-equal and execution reaches `IColumn::compareAt` through
`executeGenericIdenticalTypes`. Its doc comment claimed `compareAt` is faithful for
nested values with a nested `NULL` as the only exception. Reaching `compareAt` is
necessary and not sufficient, and a nested `Variant` is ordered by discriminator
there while `Field` orders it by type tag, so the comment states the relation instead
of enumerating exceptions it cannot close.
…t of the pairwise one Routing a decomposing or nested-`NULL` `notEquals` to `opaque_filters` moved it from a container keyed on its *converted* value to one deduplicated structurally, by `getTreeHash` and `node->isEqual`. The declared type is part of that key, so three constants of one value at three declared types stopped collapsing to a single entry and stayed three. Three is `optimize_min_inequality_conjunction_chain_length`, so the chain crossed the threshold and became a `notIn` -- and `notIn` compares by `Field` set equality, under which `nan` equals `nan`, while the element-wise `notEquals` it replaced returns true for a `NaN` row. A `WHERE` that excluded the row returned it, at pure default settings. For a `String` compared with a `Tuple` the same route replaced the `NO_COMMON_TYPE` rejection with `ILLEGAL_TYPE_OF_ARGUMENT` from resolving `notIn`. The screens now record on the filter that this analysis and execution do not order its constant the same way, and the merge skips such a filter, which leaves it an ordinary conjunct. This only ever removes an inference, so it cannot drop an operand. Measured on three binaries: the base is correct at defaults, the previous head of this branch is wrong, this commit is correct again. Arms 18 and 19 of `05056_redundant_comparisons_element_wise_container` pin the value and the plan oracle for the `Tuple` and the no-supertype `Array` spelling, arm 21 pins the error code, and arm 20 is the control that keeps the change narrow: a chain whose third entry reaches `opaque_filters` by a route these screens do not flag has to keep merging. Dropping the merge exclusion reddens arms 18, 19 and 21 and nothing else; excluding every opaque `notEquals` instead reddens arm 20 and nothing else. The test preamble described only the decomposed half, which misdescribed the six nested-`NULL` and `JSON` arms: those comparisons do reach `IColumn::compareAt` and diverge on the direction hint for a null instead. It now states both ways the order breaks.
`order_inconsistent` is assigned at two sites and only one was covered: reverting the `comparisonDecomposesContainer` guard reddens five reference lines, while deleting the assignment in the `fieldContainsNull` branch left all 62 of them unchanged. Arm 22 covers that second site. Measured what that second assignment changes, on three binaries: master, this branch, and a mutant of this branch with only that assignment deleted. For `a != [NULL] AND a != [1] AND a != [2]` on `Array(Nullable(UInt32))`, master merges the chain into `a NOT IN ([NULL], [1], [2])` and this branch leaves it alone, but the answer is the same either way, and so is the hand written `NOT IN` run with both optimizations off. `Map(String, Nullable(Float64))` and `Array(LowCardinality(Nullable(String)))` behave the same. `ColumnArray::serializeValueIntoArena` writes the nested null flag, so the set matches a `NULL` element against a `NULL` element exactly where `IColumn::compareAt` calls them equal. At that site the exclusion is therefore a conservative choice and not a fix, and the arm says so. `NaN` is where the two come apart, and that is the wrong result the rest of this branch removes. Three comments corrected: `order_inconsistent`'s own comment justified the exclusion with the claim that the `NOT IN` set membership uses the same order this analysis does. It does not: `HashTable` compares keys with `bitEquals`, a third notion of equality, which agrees with the order for `NaN` and disagrees for `-0.0`. Arm 20's comment read as a claim that the merge it keeps is sound. It is not, for that same reason, and that is pre-existing behaviour. It now states what the arm discriminates: a bare `NaN` is held aside by an older screen that sets no flag, so what is excluded is the flagged filter and not every opaque one. `opaque_filters`' comment enumerated three routes into that vector where there are five. It was already missing the nullable comparison result before this branch, which added the other two.
Internal second-model review (7 rounds)An independent cold review plus a second model reviewed this change over seven rounds before it was
Session id: cron:clickhouse-review-self-slot-58:20260901-215600 |
|
Workflow [PR], commit [f9794ab] Summary: ❌
AI ReviewSummaryReviewed PR #117595 at Findings❌ Blockers
Final VerdictStatus: ❌ Block — the existing wrong-results finding remains present. Land the companion ordering fix before this change, or include its shared guard and focused regression coverage here. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260901-212200 |
|
cc @vdimir @novikd, could you review this? |
|
|
||
| /// A comparison that is decomposed into per-element comparisons is neither a point nor a bound on the | ||
| /// order this analysis reasons in, so it must not be compared against the other conditions. | ||
| if (comparisonDecomposesContainer(raw_type, new_filter.constant_node->getResultType())) |
There was a problem hiding this comment.
order_inconsistent is still incomplete here: compareComparisonFilters will continue to rank Variant (and Dynamic) constants by raw Field tag order, but execution compares mixed alternatives by variant discriminator / type-name order instead. A concrete case is Variant(Float64, Int64): ordinary Variant sorts its alternatives by type name, so execution has Float64 < Int64, while accurateLess on the converted Fields sees Int64 (tag 2) < Float64 (tag 3). That means a row holding 1.0::Float64 can still satisfy x >= 1.0::Float64 and fail x >= 2::Int64, yet the pruning logic can keep the Float64 bound as the tighter one and drop the bound that actually excludes the row. Since this PR introduces order_inconsistent as the fence for mismatched runtime ordering, I think Variant/Dynamic need to be routed to opaque_filters here as well, with a focused regression for that mixed-alternative case.
There was a problem hiding this comment.
Measured this, and the case as stated does not reproduce: a top-level Variant comparison is already held aside, one screen earlier than the one you commented on. x >= 1.0::Float64 on a Variant(Float64, Int64) column has result type Nullable(UInt8), so the nullable-result screen routes it to opaque_filters before any ordering is consulted. On a row holding 1.0::Float64, x >= 1.0::Float64 AND x >= 2::Int64 keeps both greaterOrEquals conjuncts in the query tree and answers 0 with the setting on and off, where the same shape on a Float64 column folds to one conjunct.
The ordering premise is half right, and the half that does not hold is the one your example needs. A top-level Variant comparison converts to a common type and compares by value: 9e9::Float64 >= 2::Int64, both as Variant(Float64, Int64), is 1. Discriminator order governs compareAt, which is what ORDER BY uses and what compares container elements. So the divergence you describe is real one level down: inside a container, analysis orders elements by Field tag (Int64 is 2, Float64 is 3) and execution by alternative name order (Float64 before Int64), which for that alternative list is exactly reversed. It is wrong at default settings on Array(Variant(...)), Map(String, Variant(...)), Array(Dynamic), Array(Array(Variant(...))), Array(Tuple(Variant(...))), Array(JSON), and on a top-level JSON, whose comparison is not nullable.
The Variant half is already fixed by my open #113470, which declines the analysis when the expression type is or contains a Variant, so I am not adding a second predicate for it here. Dynamic and JSON are covered by neither PR; that gap is real, I have it reproduced, and I will link the fix here when it opens.
One more thing I found and am not acting on: when a constant String plays the expression side, conversion and ordering both happen at String, so [10] sorts before [2] lexicographically. It reproduces identically on master, needs enable_scalar_subquery_optimization = 0 plus an ASOF JOIN ON to put two constant comparisons in front of the pass, and is a different mechanism from this fence.
There was a problem hiding this comment.
#117637 opens this.
It ended up wider than I said above. Rather than leave Variant to #113470, one predicate covers Variant, Dynamic and JSON, on either operand and at any depth, so #117637 supersedes #113470 as a strict superset on both axes. It also keeps a screened comparison out of the notEquals-to-NOT IN merge, which optimize_redundant_comparisons does not gate and which has the same blind spot: a notIn set rebuilds its constants from Fields, and a Field cannot carry a discriminator.
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 17eedecEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
One caveat on reading the check list: there are two workflow runs at this commit, 7 seconds apart, Session id: cron:our-pr-ci-monitor:20260902-050000 |
Master restructured `addComparisonFilter`: the pruning-disabled early return moved from the top of the function down past the conversion and NaN screens, and now detects an always-false equals chain through `first_equals_position`. Resolution keeps that block byte-for-byte where master put it and places the two order-inconsistency screens after it, which is where they sat relative to the pairwise comparison before the merge. Placing them above it would push a screened `equals` into `opaque_filters` without registering `first_equals_position`, so master's new conflict detection would stop firing for container shapes with `optimize_redundant_comparisons = 0`. Below it, both behaviours are unchanged: with pruning off neither screen runs and every filter is opaque exactly as on master, and with pruning on the screens run exactly as on the pre-merge head.
Master grew `anyFieldSatisfies` in `Core/Field.h` while this branch was open (7bab806), with the same explicit worklist and the same four container cases as the local helper added here, so the merge left two copies of one walk. Call the shared one and drop the local helper together with its direct Abseil include; `MergeTreeData.cpp:11797` already calls it with a capture-less lambda in this shape.
Set lookup is key equality, not the `FieldAccurateComparison` order the pruning analysis reasons in, so "uses the same order it is not a point in" named the wrong mechanism. The source comment on `order_inconsistent` already says it correctly; this brings the test comment in line with it. The sentence after it, which is the concrete disagreement (`notIn` holding `nan` equal to `nan` where the element-wise `notEquals` does not), is unchanged.
One conflict in `addComparisonFilter`: master added the `take_slot` lambda (f6c34e5, keep the guard position when a comparison is pruned) at the spot where this branch's two order-inconsistency screens sit. Kept both: the screens first, then master's lambda, so a screened filter still goes to `opaque_filters` with its own `original_index` before any pairwise pruning, and `take_slot` stays next to the Step 3 code that uses it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #117379
Related: #112272
Related: #113470
Related: #116763
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results from
optimize_redundant_comparisons, enabled by default since 26.7. A bound that excludes a row could be dropped when anANDchain compares twoTuples, twoArrays with no least supertype, or aTupleagainst aStringliteral, because such a comparison is evaluated element by element, not in the order the optimization prunes with; and when a container constant carries aNULL, which the optimization orders first and execution last. Closes #117379.Description
optimize_redundant_comparisonsprunes a comparison implied by another on the same expression, ordering constants withFieldAccurateComparison, which placesNaNlast. That order holds only where the comparison reachesIColumn::compareAt. Two shapes instead decompose into per-element comparisons, under which a comparison against aNaNis false and nothing is ordered: two top-levelTuples, whichexecuteTupletakes before the equal-types shortcut, so even for identical types, and twoArrays with no least supertype.#117379 reports the first shape. For the second, on
Array(Tuple(Float64, UInt64))holding[(nan, toUInt64(9))],a >= [(1., toUInt64(1))] AND a >= [(0., toInt64(0))]answered 1 where each bound alone gives 1 and 0. Neither constant holds aNaN, only the stored row.Reaching
compareAtis not sufficient either: it orders a nestedNULLlast whileFieldorders it first, and two nullable-element containers compare to plainUInt8, so the nullable screen misses it. OnArray(Nullable(UInt32))holding[NULL],a <= [NULL] AND a <= [1]answered 1, the bounds alone 1 and 0.The fix classifies the comparison and screens the constant for a
NULLat registration, keeping such a filter an ordinary predicate as a nullable result is, and out of thenotEqualschain's merge intoNOT IN, which tests set membership instead. Classifying the type the comparison executes at, whichexecuteWithConstStringcan change for a constantString, is what covers theTuple-against-Stringspelling. This is the focused form of #112272's nested-NaNslice. Every other fold is kept, pinned by a test arm: scalars, same-type containers,Arraypairs with a least supertype, and nullable-element containers with noNULLconstant. For aStringagainst aTuple, declining surfaces aNO_COMMON_TYPEerror where the chain answered0.Workflow [PR]
Sync PR [sync-upstream/pr/117595]
Workflow [PR]
Sync PR [sync-upstream/pr/117595]