Skip to content

Do not prune comparisons that are compared element by element - #117595

Open
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:fix-element-wise-container-comparison-pruning
Open

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:fix-element-wise-container-comparison-pruning

Conversation

@groeneai

@groeneai groeneai commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #117379
Related: #112272
Related: #113470
Related: #116763

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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 an AND chain compares two Tuples, two Arrays with no least supertype, or a Tuple against a String literal, because such a comparison is evaluated element by element, not in the order the optimization prunes with; and when a container constant carries a NULL, which the optimization orders first and execution last. Closes #117379.

Description

optimize_redundant_comparisons prunes a comparison implied by another on the same expression, ordering constants with FieldAccurateComparison, which places NaN last. That order holds only where the comparison reaches IColumn::compareAt. Two shapes instead decompose into per-element comparisons, under which a comparison against a NaN is false and nothing is ordered: two top-level Tuples, which executeTuple takes before the equal-types shortcut, so even for identical types, and two Arrays 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 a NaN, only the stored row.

Reaching compareAt is not sufficient either: it orders a nested NULL last while Field orders it first, and two nullable-element containers compare to plain UInt8, so the nullable screen misses it. On Array(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 NULL at registration, keeping such a filter an ordinary predicate as a nullable result is, and out of the notEquals chain's merge into NOT IN, which tests set membership instead. Classifying the type the comparison executes at, which executeWithConstString can change for a constant String, is what covers the Tuple-against-String spelling. This is the focused form of #112272's nested-NaN slice. Every other fold is kept, pinned by a test arm: scalars, same-type containers, Array pairs with a least supertype, and nullable-element containers with no NULL constant. For a String against a Tuple, declining surfaces a NO_COMMON_TYPE error where the chain answered 0.


Workflow [PR]
Sync PR [sync-upstream/pr/117595]


Workflow [PR]
Sync PR [sync-upstream/pr/117595]

groeneai and others added 7 commits September 1, 2026 06:09
`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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (7 rounds)

An independent cold review plus a second model reviewed this change over seven rounds before it was
pushed. Everything marked ❌ was fixed before publication. The last round reached my review process's
fix-round cap, so it published the tree as it stands; nothing marked ❌ was left unfixed, and the
residuals below are the ones deliberately not addressed.

Finding Verdict
❌ A Tuple constant on the left of a String constant was still pruned. The pass designates the left operand as "the constant" whenever it is one, so with two constant operands the String becomes the expression side, and the classifier normalized only the constant side. The condition was then compared in the String order ('(4,4)' < '(nan,9)') while execution decomposes it through executeWithConstString and executeTuple, where every comparison against the NaN element is false. Reachable in an ASOF JOIN ON with a multi-column scalar subquery: 0 rows with the optimization off, 1 with it on. AGREE, fixed. Normalization is now symmetric, with a regression arm in both operand orders; the mirrored order was already correct, which is what isolates this to operand order rather than to the shape.
❌ A NULL nested in a container constant is ordered oppositely by the analysis and by execution, so the bound the analysis keeps is not the one execution treats as tighter. Field comparison orders by type tag with Null lowest, while execution reaches IColumn::compareAt with a direction hint of 1, under which ColumnNullable puts a null last. Two nullable-element containers compare to a plain UInt8, so the existing nullable-result screen never sees it: a <= [NULL] AND a <= [1] on Array(Nullable(UInt32)) holding [NULL] returned 1 where the bounds alone give 1 and 0, and the same on Array(LowCardinality(Nullable(String))) and Map(String, Nullable(Float64)). AGREE, fixed. The constant's Field is screened for a NULL at registration, not its type: the deduction depends only on the two constants' relative order, a Field carries no LowCardinality to strip, and a type-based screen also gives up folds whose constants hold no NULL (measured against the in-tree, LowCardinality-aware hasNullable, which loses both). Three regression arms plus two folds-must-survive controls, and the controls were shown to move under a type-based screen rather than assumed to be load-bearing.
❌ The same divergence one container further out was still pruned: a NULL inside a JSON value. Object is the fourth Field container and the only one held as a map rather than a vector, so the screen's walk, written over the other three, structurally could not reach it. On JSON(a Nullable(UInt32)) holding {"a":null} the conjunction returned 1 where the bounds alone give 1 and 0. AGREE, fixed. The walk now covers all four containers Field::isContainer names, and it is iterative over an explicit worklist rather than recursive, because a JSON value's nesting depth comes from the data and the codebase already states that a recursive walk over these containers overflows the stack. A JSON fold whose constants hold no NULL is pinned as a control, and a mutant screening the type instead reddens exactly that control.
❌ A decomposed or nested-NULL notEquals reached the notEquals-chain merge into NOT IN, and there set membership does not agree with the comparison it replaces. Routing such a filter to opaque_filters moved it from a container keyed on its converted value to one deduplicated structurally, so three constants of one value at three declared types stayed three entries instead of collapsing to one, crossed the default chain-length threshold of 3, and became a notIn under which nan equals nan while the element-wise notEquals returns true. A correct query returned the wrong answer 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. AGREE, fixed. Measured on three binaries: master is correct, an earlier revision of this branch was wrong, the fix is correct again, so this was a regression introduced inside this pull request and never shipped. A screened filter now records that this analysis and execution do not order its constant the same way, and the merge skips it, which leaves it an ordinary conjunct; the flag is set only by the two screens this change adds, so nothing else moves. Arms pin the value, the plan and the error code, and one control keeps it narrow: a chain reaching opaque_filters by an older route still has to merge. An earlier round of this review recorded the opposite verdict, arguing the rewrite is pre-existing and threshold-gated. Both are true and neither addresses the entry count, which is the actual mechanism; that reasoning is superseded.
❌ The three wrong-results scenarios pinned optimize_and_compare_chain = 0. It defaults to true and clickhouse-test disables it with probability 0.05, so the reported query only ever ran in the rare configuration, which is also the one where tryOptimizeAndCompareChain calls the changed function with pruning hardcoded on and appends a plain executable conjunct on a contradiction. AGREE, fixed. Result arms pin = 1; the EXPLAIN arms keep = 0, because an indexHint-wrapped derived conjunct also matches their pattern.
❌ The test header justified both pins with "the runner randomizes them", which is false for optimize_redundant_comparisons: it appears nowhere in tests/clickhouse-test or under ci/. AGREE, fixed. Each pin carries its true reason.
❌ Issue #117379 was linked as Related: although both of its reproducers are top-level Tuple pairs, which this change corrects in full, and no other pull request is linked to it. On merge it would have stayed open with its fix already in master. AGREE, fixed. Now Closes:.
❌ The changelog entry named only the original shape, and the description claimed the change "can only decline a fold". Later rounds added a two-constant spelling and the nested-NULL shape, and declining can also let a NO_COMMON_TYPE error surface where the fold answered 0. AGREE, fixed in this description: the entry names every shape, and the error case is stated with its limits.
❌ The comment added to correct one false claim introduced another of the same shape: it said compareAt is faithful for nested values so only the top level needs classifying, with a nested NULL as the exception. That is not the only exception: ColumnVariant::compareAt orders differently-typed elements by discriminator while Field orders by type tag, which is the subject of a separate open pull request of mine. AGREE, fixed. The comment now states the relation as necessary and not sufficient, names one non-sufficiency without claiming the list is complete, and cites no pull request in the source.
❌ The test preamble described only the decomposed half, which misdescribed six of the arms: those comparisons do reach IColumn::compareAt and diverge on the direction hint for a null instead. AGREE, fixed. The preamble now states both ways the order breaks.
❌ The test preamble restated the helper's own doc comment nearly verbatim, a third copy of the same mechanism. AGREE, fixed. Condensed to the regression invariant; the setting-pinning paragraph, which is not duplicated, is kept.
⚠️ A contradiction on another expression can still collapse the whole AND and replace a NO_COMMON_TYPE exception with 0, for example WHERE i = 1 AND i = 2 AND s <= (1, 2). AGREE on the mechanism, DISAGREE that this change causes it, raised twice so recorded rather than dropped. The collapse veto inspects only opaque_filters, and only for a missing converted value; before this change the same predicate sat in range_filters, which the veto never inspects, so the collapse fired identically. The predicate is also unsatisfiable in that example, so 0 rows is the correct answer and the exception is an artifact of evaluating a dead ill-typed operand. Making it consistent means changing the collapse rule for every filter container, a separate pre-existing issue, so it is reported here rather than folded in.
⚠️ The classifier's probe form, SELECT <container holding a NaN> = <the same literal>, cannot classify a nested Tuple: it measures the element's dispatch, not the top level's, and two identical top-level Tuple types answer 0 and 1 under it. AGREE on the mechanism, no code change. The predicate declines every top-level Tuple pair, which is what execution does; the probe, not the predicate, is what the control refutes.
⚠️ Scalar comparisons stay foldable even though a scalar NaN comparison is IEEE rather than NaN-last. DISAGREE that pruning them is unsound. Any predicate surviving pruning is either a range against a non-NaN constant, which a NaN row fails, or a !=, which a NaN row satisfies with pruning on and with it off; the strengthening arms only tighten <= to < at an equal constant, which a NaN row fails either way. A NaN constant was already opaque before this change. The notEquals-to-NOT IN merge is a separate rewrite and is the subject of the row above.
❌ The flag added in round 5 is assigned at two sites and only one had a test guarding it: deleting the assignment in the nested-NULL branch reddened nothing, because no != constant in the test carried a NULL. More than a coverage gap, because on master all three constants of a != [NULL] AND a != [1] AND a != [2] reach the chain-length threshold and the NOT IN set includes [NULL], while this branch drops the chain to two entries and does not merge, and whether that fixes a wrong result or declines a sound merge was unmeasured, which is what decided whether the changelog understated the fix. AGREE, fixed, and the arm's shape was chosen by the measurement rather than guessed. Three binaries (master, this branch, and this branch with only that one assignment deleted), 45 values all predicted in writing beforehand and all hit, with the mutant byte-identical to master on all 15 queries so it is known to have changed one thing. Result: the merged chain, the unfolded chain and a hand-written NOT IN with both optimizations off give the same answer, on Array(Nullable(UInt32)), Map(String, Nullable(Float64)) and Array(LowCardinality(Nullable(String))) alike. ColumnArray::serializeValueIntoArena writes the nested null flag, so set bit-equality and IColumn::compareAt agree on a nested NULL; NaN is the only place they diverge, which is the wrong result the other two arms pin. So the exclusion there is a conservative over-decline, the changelog understates nothing, and the description needed no edit. Because a single-row table answers 0 on every value arm under either semantics, a 7-row probe returning the surviving id set was measured as well, and agrees row by row.
❌ Three comments stated something not exactly true: the new struct field's said the NOT IN merge's set membership "uses that order" (it is bit equality on the key, and accurateEquals(nan, nan) is false, so the two coincide for NaN only through the order's induced equivalence and disagree for -0.0); the surviving-merge arm's read as a soundness claim about a merge that is unsound for a NaN row; and opaque_filters' doc comment enumerated three routes into it where there are now five. AGREE, all three replaced, and each replacement proven comment-only rather than asserted: stripping comments and blanks leaves both revisions of both files byte-identical (sha256 and executable line count), with negative controls confirming the check detects a real change.
💡 The test is 201 lines and 22 arms for a 63-line fix. Deliberately not trimmed, and flagged here so the objection costs one line rather than a round trip. Every arm has a recorded mutant that reddens that arm alone, so none of them is redundant coverage; if you would rather have fewer, name the arms and I will drop them.
💡 Another open pull request of mine, #117427, changes the same function. Composition checked, not assumed. Mapped onto base line numbers the two changes are ~37 lines apart with no textual overlap, and they are independent in the safe direction: #117427 rewrites the sole-survivor emission tail, while this change can only increase the number of surviving operands, so it makes that path rarer and cannot create a new case for it.
💡 A String compared with an Array constant still folds, so there the fold can still suppress a NO_COMMON_TYPE error, while the Tuple spelling no longer does. Noted, deliberately not addressed, and not claimed by the description. That pair is not decomposed, it throws, so it is outside what this change is about; widening the classifier to cover it would also mean testing constness, which is invisible here because a scalar subquery arrives as a __getScalar call at default settings, turning a safe over-decline into an unsafe under-decline.
💡 The notEquals-to-NOT IN merge tests set membership, which is bit equality on the key, so it disagrees with the comparison it replaces for a bare NaN constant and for -0.0; and with optimize_redundant_comparisons = 0 a chain of container inequalities still merges, because that route records nothing about the constant's order. Noted, pre-existing, deliberately not addressed. master answers the same wrong value in both cases, so neither is caused by this change, and both belong to the merge rather than to the pruning this pull request is about. Disclosed here rather than left for a bot to find.
💡 The helper carries an eight-line comment, above the usual per-block budget. Kept deliberately. It justifies why exactly two type shapes decompose, why identical types are included, why reaching compareAt is necessary but not sufficient, and why Map is absent. None of that is obvious from the code below it and none of it refers to this fix. The citations, the refuted alternatives and the measurements are in the commit messages instead.

Session id: cron:clickhouse-review-self-slot-58:20260901-215600

@clickhouse-gh clickhouse-gh Bot closed this Sep 1, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f9794ab]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Reviewed PR #117595 at f9794ab7239c38b068ca260820a4a1aeca1f6153, including all prior discussion and the current callers and comparison implementations. The change excludes decomposed comparisons and constants containing nested NULL from pruning and the NOT IN rewrite. The added stateless test passes in the current head's Fast test report. No new inline findings; the existing ordering finding remains reproducible and is retained below.

Findings

❌ Blockers

  • src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp:991 — Pruning still changes results for comparisons whose ordering depends on a variant discriminator. [dismissed by author -- https://github.com/Do not prune comparisons that are compared element by element #117595#discussion_r3909141358] The author defers this to Do not prune a comparison of a value that carries its own type #117637; the current guard still admits same-type Array(Variant) comparisons, so the discrepancy between Field ordering and runtime ordering can drop a bound that excludes the row.

    Reproduced with this PR's Fast test binary:

    SELECT count()
    FROM
    (
        SELECT materialize(CAST([9.0::Float64], 'Array(Variant(Float64, Int64))')) AS x
        FROM numbers(1)
    )
    WHERE x >= CAST([9.0::Float64], 'Array(Variant(Float64, Int64))')
      AND x >= CAST([2::Int64], 'Array(Variant(Float64, Int64))')
    SETTINGS optimize_redundant_comparisons = 1, optimize_and_compare_chain = 0;

    This returns 1; changing only optimize_redundant_comparisons to 0 returns 0. A top-level Variant reproduces the same 1 versus 0 discrepancy with use_variant_default_implementation_for_comparisons = 0. The earlier top-level example at default comparison settings was inaccurate: the nullable-result guard protects that mode.

    Coordinate the shared type screen in PR Do not prune a comparison of a value that carries its own type #117637 with this change, covering either operand and nested carriers, and retain regression coverage for both the container and legacy top-level comparison modes. The existing thread was left unchanged; no duplicate inline comment was posted.

Final Verdict

Status: ❌ 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.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, nine shapes, one command each, 100% of runs, no randomization: a no-supertype Array pair, a top-level Tuple pair, a constant String against a Tuple column, a container constant on the left of a String constant (two constants inside an ASOF JOIN ON), a String column against a Tuple constant, and a NULL nested in an Array(Nullable), an Array(LowCardinality(Nullable)), a Map(..., Nullable) and a JSON(a Nullable(UInt32)) constant. Round 5 adds a tenth: a three-conjunct != chain of one value at three declared types, over a container column holding a NaN, which is wrong at pure default settings. Each row-count shape carries its single-condition count as ground truth, so the expected answer is derived rather than asserted.
b Root cause explained? The pruning analysis orders constants with FieldAccurateComparison and never asks whether execution evaluates the condition in that order. Two ways it can diverge. executeTuple and executeArrayLexicographic decompose the container into per-element comparison functions, under which a comparison against a NaN is false and nothing is ordered. And for a value nested in a container, Field::operator< compares type tags first with Types::Null lowest, so a nested NULL sorts before every value, while execution reaches IColumn::compareAt with a hardcoded direction hint of 1 and ColumnNullable puts NULL last. ColumnObject::compareAt delegates each path to its own column, so a JSON value diverges the same way. Either way a bound the row fails was pruned as implied by a bound the row satisfies.
c Fix matches root cause? Yes, at the layer that makes the invalid claim, and in the same place for both halves: at filter registration a decomposed comparison is classified from the two operand types, and a constant carrying a nested NULL is screened from its Field, and either one is kept as an ordinary predicate instead of entering the pairwise comparison. Round 5 completes it: the same screened filter is now also kept out of the notEquals merge into NOT IN, whose set membership uses the very order the filter is not a point in, so one flag governs both inferences rather than only the pairwise one. No widened bound, no defensive check at a symptom site, no test weakening. The change only ever declines a fold; where the declined operand is one the server cannot execute at all (a String expression against a Tuple constant), declining restores the NO_COMMON_TYPE rejection the fold was suppressing, which is what both the unfolded spelling and the setting-off spelling already do today.
d Test intent preserved / new tests added? New test 05056_redundant_comparisons_element_wise_container with twenty-two arms, eight of them over-decline controls that must keep folding and one the fold this change deliberately gives up. Arm 20 is the control that makes the merge exclusion's narrowness measured: a chain whose third entry reaches the opaque path by a route this change does not flag must still merge, and a blanket implementation reddens it. Arm 22 covers the second of the two sites that set the flag, the nested-NULL one, which nothing else reached; its comment records that at that site the exclusion is a conservative choice rather than a correctness requirement, because the measurement below shows the merge and the comparison agree there. No existing test modified and no reference regenerated; the three 04032_* snapshot tests show zero churn, and each earlier form of this test still passes unmodified against the final binary.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (base 7661717f, final cc85acab). The round-5 arms were measured on three binaries, not two: base correct, the pre-round-5 head wrong, the final binary correct, so the defect is a regression this PR introduced rather than a pre-existing one. Against the new test the base binary reddens exactly the wrong-results conjunctions, the one fold this change deliberately gives up, and the suppressed-rejection arm, and nothing else; the over-decline controls pass on both. Each screen was additionally confirmed to redden on the intermediate heads of this PR (1ac5370e for the nested-NULL arms, 5a5886b1 for the JSON arm), so no arm is already covered by an earlier commit. Also demonstrated under clickhouse-test against mutant servers, which is what proves the serverError arms are enforced rather than ignored. Round 5 adds two mutants whose reddening sets were predicted in writing before they were built and matched exactly: reverting the merge exclusion reddens the two regression arms and the error-code arm and nothing else, and excluding every opaque notEquals reddens the over-decline control and nothing else. Round 6 adds a third, deleting the flag assignment in the nested-NULL branch alone: it reddens the new arm's single reference line and nothing else, and it reproduces master's answers on all 15 measurement queries byte for byte, which is what proves it changed one thing. All 45 values of that three-binary measurement were predicted in writing first.
f Fix is general across code paths? Registration is the single choke point, so all three addComparisonFilter callers (the main loop, optimize_and_compare_chain seeding, the derived-conjunct path) inherit both screens; the only insertions into range_filters and not_equals_filters are after them. The type classifier is symmetric in the two operand types, matching executeWithConstString, which converts whichever side is the constant string. The Field screen walks all four containers that nest Fields, which is the set Field::isContainer itself names, so it is independent of which shapes the type classifier covers. The != path is where round 5 landed: both screens set one flag at registration, and every inference that assumes the analysis order now consults it, so neither the pairwise comparison nor the NOT IN merge can read a screened filter as a point in that order. The same defect one layer down in KeyCondition and the skip-index range readers is #116763 and stays separate.
g Fix generalizes across inputs (params/datatypes/wrappers)? Ten-shape type matrix measured on my own binary: scalar, LowCardinality, Array same type, Array with a differing but supertype-compatible type, Map, Array(Tuple) same type and with differing signedness, Tuple, nested Tuple, Array(Nullable). Plus a constant String against both a Tuple and an Array column, both operand orders of a container-versus-String pair, a String and a FixedString column against String constants (folds preserved), a JSON value with and without a nested NULL, and four != shapes. The nested-NULL screen is on the Field, not the type, so it needs no wrapper stripping: Array(LowCardinality(Nullable(T))) is covered by construction, and mutants using a type-based screen were measured to lose folds that carry no NULL at all.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or re-defaulted, so no SettingsChangesHistory.cpp entry is needed; no format or serialization change. The optimization becomes strictly more conservative.
i Invariants and contracts preserved? Yes. Both exclusions route to the existing opaque-filter path, whose rebuild tail re-emits the filter with its original node and original index, so no operand can be dropped from the AND and operand order stays stable. The round-5 flag is set on the filter before it is moved into that container and is only ever read there, so it cannot disagree with the route the filter actually took; a filter excluded from the merge falls through to all_operands, which is the same emission path, so the exclusion cannot lose an operand either. Both screens run after the existing non-lossless/NaN screen, so every filter they add to the opaque container carries a converted value, which is the property the conflict-collapse veto reads. The type classifier is a pure function of two DataTypePtrs; the Field screen is an explicit-worklist walk over a value already materialized, so it borrows no state and cannot overflow the stack on a deeply nested value, which is the reason Field's own copy and destroy are iterative. No allocation of note, no lifetime or concurrency interaction, error paths unchanged. A comparison with a nullable result is already excluded before both.

Session id: cron:clickhouse-impl-self-slot-57:20260901-212200

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd, could you review this? optimize_redundant_comparisons prunes a comparison implied by another using a total order over the constants, but two shapes are evaluated element by element instead (a top-level Tuple pair, and an Array pair with no least supertype), and a NULL nested in a container constant is ordered the opposite way by the analysis and by execution, so a bound that excludes a row could be dropped.


/// 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()))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#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.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit b7d3c1c4677d7e636f9ae955f73b6ff0f88700f8 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 17eedec

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1 pre-existing trunk bug, not caused by my diff. The query is a window function over a multi-shard remoteSecure(...) wrapping an inner view that references no column of the table and projects a constant (SELECT DISTINCT 2). The window function is deferred to the initiator, which expects a zero-column header and is handed one column. 4 true-master hits and roughly 25 unrelated PRs carry this signature in 30 days. My diff only changes optimize_redundant_comparisons pruning, and the failing query contains no comparison at all #113469 (mine, open), which fixes this exact shape on the analyzer. #113955 covers the enable_analyzer = 0 half of the same defect
Stress test (amd_tsan) / Not-ready Set is passed as the second argument for function 'globalNotIn' pre-existing trunk bug in the in-place set build, not caused by my diff. 28 true-master hits plus release 26.6 in 30 days, spread across many unrelated PRs #102308 (external, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) the nested-container memory guard on this shard, not caused by my diff: the /docker leaf's charge is unreclaimable anonymous memory and its cap is the only one that binds, so the guard trips independently of any query change #117412 (external, merged 2026-09-01T11:31:33Z), rule 3c: absent from the tree that ran, probed at the failing head with both controls firing. I am deferring the master merge here because the other two rows are owned by still-open PRs, so re-running would not turn this head green; naming the merged owner is what that rule asks for in that case

One caveat on reading the check list: there are two workflow runs at this commit, 7 seconds apart,
and they fail disjointly. 33566891404 reds the AST fuzzer and Integration tests rows, and
33566880693 reds Stress test (amd_tsan). A deduplicated view of the checks therefore shows only
two of the three, so the table above is taken from CIDB at this commit, which sees all three.
Control: 544,685 rows at this commit, of which exactly 2 FAIL and 1 ERROR, and no job-level row
carries a fourth non-green check_status. Config Workflow, Style check and Finish Workflow
are all green.

Session id: cron:our-pr-ci-monitor:20260902-050000

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

NaN inside a Tuple constant escapes the comparison-chain pruning NaN guard: optimize_redundant_comparisons returns extra rows at pure defaults

1 participant