Repository navigation
Fix LogicalExpressionOptimizer chain->IN rewrites for Variant and dynamic-structure expressions - #111924
Conversation
…e for Variant The LogicalExpressionOptimizer pass rewrites `x = c1 OR x = c2 OR ...` into `x IN (c1, c2, ...)` (and the `notEquals` AND -> NOT IN and `has` -> `in` counterparts). For a Variant expression with use_variant_default_implementation_for_comparisons = 0 (the default before 26.1, and still a supported/documented configuration), `equals`/`notEquals` resolve to UInt8, but the resulting `in`/`notIn` resolve through FunctionBaseVariantAdaptor to Nullable(UInt8). The rewrite then changes the node's result type, which ancestors already captured -> the query-tree ValidationChecker throws LOGICAL_ERROR (debug/sanitizer builds abort). Found by the AST fuzzer, STID 0250-20a8, on the windowFunnel + OR-chain shape. Add a type-preservation guard to each of the three chain->IN conversions: skip the rewrite for a group whose in/notIn replacement resolves more nullable than the comparisons it replaces (tryReplaceOrEqualsChainWithIn, convertNotEqualsChainToNotIn), and add Variant to the needle-type exclusion list that HasToInPass already keeps for the same reason. Also skip the OR->IN rewrite for a Dynamic-structure expression, which `in` rejects outright. When the rewrite cannot preserve the type it keeps the original chain, so semantics are unchanged and the optimization still fires for every type where in/notIn preserves the type (String, Nullable, LowCardinality, Variant with the setting on). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108715&sha=e0ab38d92bcb293849e8bf35e1932a7ae8b94316&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 Co-Authored-By: Claude Opus 4.8 <[email protected]>
The AND path had the same defect the OR path was already guarded against: notIn rejects arguments with a dynamic structure outright, and the rewrite resolves the function before the nullability-drift guard runs, so the optimizer turned a working query into ILLEGAL_TYPE_OF_ARGUMENT. The earlier reasoning that this could not happen keyed on exact Dynamic, where notEquals gets the nullability adaptor and the caller bails out on the resulting nullable AND. Array(Dynamic) and JSON get no adaptor while hasDynamicStructure() is transitively true, so their comparisons stay UInt8, the AND stays UInt8, the caller does not bail, and building notIn throws. Move the check before the function is built, mirroring the OR path. The two guards stay separate: Variant(UInt256) has no dynamic structure, so only the nullability-drift guard covers it. The test now exercises both directions for Dynamic, Array(Dynamic) and JSON, and asserts that the rewrite still fires for the same Variant column once use_variant_default_implementation_for_comparisons makes equals nullable, so a guard keyed on the type instead of the drift cannot pass unnoticed. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent reviewer plus an independent model
Severity: ❌ blocker / Also verified by reading, with no finding: the OR guard keys on the type drift rather than on the Session id: cron:clickhouse-review-slot-10:20260725-222600 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260725-213300 |
|
cc @vdimir @yakov-olkhovskiy — could you review this? It stops the LogicalExpressionOptimizer chain->IN rewrites ( |
|
Workflow [PR], commit [8191c97] Summary: ✅
AI ReviewSummaryThis PR fixes several analyzer Findings❌ Blockers
Final Verdict
|
…rite convertNotEqualsChainToNotIn built the right-hand tuple as ConstantNode(Tuple), so the element types were re-derived from the Field values by FieldToDataType. That collapses DateTime to UInt32, DateTime64 to a plain Decimal64, an Enum to its underlying integer and so on, and the rewritten notIn then compares against different values than the notEquals chain it replaced. Two observed effects, both with optimize_min_inequality_conjunction_chain_length reached: d Date, ts DateTime d != parseDateTimeBestEffort(...) AND ... -- matched every row ts != toDate(...) AND ... -- matched every row The results were silently wrong: with the rewrite disabled the same queries return one row, with it enabled they return all four. tryReplaceOrEqualsChainWithIn already passes an explicit DataTypeTuple built from ConstantNode::getResultType() for this exact reason (the OR -> IN direction had the same bug, fixed in ClickHouse#66344). Do the same here. Found by the automated review of ClickHouse#111924.
The existing has() regression only checked the result, which the query tree ValidationChecker protects in debug and sanitizer builds. Reverting the Variant exclusion in HasToInPass therefore passed a release stateless run. Assert the absence of the `in` node with EXPLAIN QUERY TREE instead, and assert it still fires for a plain UInt8 needle so a blanket guard cannot pass either.
Preserving the constant types is necessary but not sufficient. The set
converts each element to the expression's type, while the comparison it
replaces is evaluated in the wider of the two types, so a lossy
conversion makes the two disagree:
d Date
d != toDateTime('2020-01-01 12:00:00') AND ...
The row 2020-01-01 promotes to midnight and does differ from the
constant, so the predicate holds, but the constant truncates to
2020-01-01 and the set matches the row instead.
Reuse tryConvertToColumnType(), which the comparison-filter folding in
this pass already uses for exactly this question, and keep the original
chain when any constant fails to round-trip.
Call the ValidationChecker failure a logical error rather than an abort: it throws a LOGICAL_ERROR exception, it does not abort the server. Trim the lossless-conversion comment down to the invariant at that line; the reasoning belongs in the commit that introduced the check.
The equals chain has passed the resolved constant types to the set since ClickHouse#66344, but preserving the types is not the whole requirement: the set still converts each element to the expression's type while the comparison is evaluated in the wider of the two. d Date d = toDateTime('2020-01-01 12:00:00') OR ... -- matched 3 rows, should match none Every row differs from a non-midnight constant, so the chain selects nothing, but each constant truncates onto a row and the set matches it. Same mechanism and same fix as the notEquals direction; a NULL constant is excluded before the chain is collected, so `k = 1 OR k = NULL` is unaffected.
|
Confirmed, and fixed in 8191c97. The asymmetry was real: The tuple resolved to Two corrections to the suggested scope, both found by verifying it: Carrying the types over is not sufficient on its own. The set converts every element to the expression's type, while the comparison it replaces is evaluated in the wider of the two, so a lossy conversion still makes them disagree. For a The same lossless requirement was missing in the
Not addressed, and not regressions from this PR. Test 04628 covers each carrier in both directions and asserts the fires/skips split with |
| /// The set converts each element to the expression's type, while the comparison it | ||
| /// replaces is evaluated in the wider of the two: a lossy conversion makes them disagree. | ||
| /// A NULL constant is excluded above, so it never reaches this check. | ||
| if (!tryConvertToColumnType(literal, expr_type)) |
There was a problem hiding this comment.
This still misses the same-value mismatch that HasToInPass already had to special-case for floats. tryConvertToColumnType succeeds for Float*, so both this OR -> IN branch and the analogous NOT IN branch above will still rewrite chains like f = 0.0 OR f = 1.0 / f != 0.0 AND .... But equals/notEquals treat -0.0 and +0.0 as equal, while in/notIn go through a Set keyed on the raw float bits, so a row f = -0.0 changes result after the rewrite. Please reject float expressions/constants here as well, or add a stronger equivalence check than “lossless conversion”.
There was a problem hiding this comment.
Declining this one, with measurements. I checked the specific new interaction you point at, because a47b8af and 8191c97 did not exist when I first looked at signed zero, and your reading of them is correct: tryConvertToColumnType succeeds for Float64 -> Float64, so the new lossless check is a no-op on this carrier and both rewrites still fire. The EXPLAIN QUERY TREE still shows the in/notIn node and the tuple resolves to Tuple(Float64, Float64, Float64), which is what it is meant to do.
What it is not is a regression from this PR. Rows (-0.0, 1.0, 2.0, 3.0) in a Float64 column, counting with the rewrite on (chain_length = 3) versus off (100):
rewrite ON rewrite OFF
f != 0.0 AND f != 1.0 AND f != 2.0 2 1
f = 0.0 OR f = 1.0 OR f = 2.0 2 3
Ground truth per row agrees with the off column (-0.0 != 0.0 is 0, so one row survives the conjunction). I then rebuilt the pass from the pristine base version of the file, with none of this PR's changes in it, and got 2 / 1 and 2 / 3 again, identical in both directions. The divergence predates this PR in both builders, and the OR side has had it since #66344.
I would rather not fold the fix in here. Signed zero is one of three symptoms of a single different root cause: equals compares via accurateEquals in the widened type, while in builds a set keyed on the converted raw representation. The same mismatch produces wrong results for mixed String/FixedString, where equals ignores trailing zero padding and the set does not, and for tuples with nullable elements, where equality yields NULL and top-level membership yields UInt8. Note that tryConvertToColumnType deliberately exempts string sources from its round-trip check, so no strengthening of the lossless test reaches the padding case; the correct shape is a value-equivalence precondition, not a stronger conversion check.
HasToInPass already carries exactly that precondition for has(arr, x) -> x IN (arr): it excludes floats outright, isFloat so BFloat16 is covered too, and otherwise requires the two types to be equivalent under raw Field comparison or both to be native integers. Neither chain builder has an equivalent. Lifting that predicate into the two chain builders, most likely by factoring it out of HasToInPass so all three rewrites share one implementation, is the right change, and it needs its own type matrix asserting that the rewrite still fires for the safe types rather than silently turning into a plan regression.
That is a separate change on carriers this PR does not touch, and this PR is a P0 fuzzer fix for type and nullability drift. I have opened a fix task for the value-mismatch class with the baseline measurements above recorded, and I am tracking it separately rather than dropping it.
There was a problem hiding this comment.
The follow-up I said I was tracking separately is now open: #112272.
It covers the value-mismatch class from this thread and nine further divergences found while
investigating it, across all three consumers of tryConvertToColumnType rather than just the
notEquals builder. The float half is value-based rather than type-based, because only +0.0/-0.0
and NaN actually diverge and a type-level exclusion would silently stop the rewrite firing for
every ordinary float constant.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 68/68 (100.00%) · Uncovered code |
4af577e
…rite convertNotEqualsChainToNotIn built the right-hand tuple as ConstantNode(Tuple), so the element types were re-derived from the Field values by FieldToDataType. That collapses DateTime to UInt32, DateTime64 to a plain Decimal64, an Enum to its underlying integer and so on, and the rewritten notIn then compares against different values than the notEquals chain it replaced. Two observed effects, both with optimize_min_inequality_conjunction_chain_length reached: d Date, ts DateTime d != parseDateTimeBestEffort(...) AND ... -- matched every row ts != toDate(...) AND ... -- matched every row The results were silently wrong: with the rewrite disabled the same queries return one row, with it enabled they return all four. tryReplaceOrEqualsChainWithIn already passes an explicit DataTypeTuple built from ConstantNode::getResultType() for this exact reason (the OR -> IN direction had the same bug, fixed in ClickHouse#66344). Do the same here. Found by the automated review of ClickHouse#111924.
…te-type-drift Fix LogicalExpressionOptimizer chain->IN rewrites for Variant and dynamic-structure expressions
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed three bugs in the analyzer rewrites that turn a chain of comparisons into
IN/NOT IN(x = c1 OR x = c2 OR ...,x != c1 AND x != c2 AND ..., andhas(const_array, x)). For aVariantexpression withuse_variant_default_implementation_for_comparisons = 0the rewrite changed the expression result type fromUInt8toNullable(UInt8), which raised aLOGICAL_ERRORfrom the query-tree validation check in debug and sanitizer builds. For an expression with a dynamic structure (Dynamic,Array(Dynamic),JSON) the rewrite made a working query fail withIllegal type ... of argument of function in, becauseINrejects such arguments. Both directions also returned wrong results when a constant does not convert losslessly to the expression's type, such as aDateTimeconstant with a time of day compared against aDatecolumn.Description
The
LogicalExpressionOptimizerpass rewritesx = c1 OR x = c2 OR ...intox IN (c1, c2, ...), and symmetricallyx != c1 AND x != c2 AND ... -> x NOT IN (...);HasToInPassrewriteshas(const_array, x) -> x IN (const_array). Each replaces a node whose ancestors were already resolved against the old result type, and neitherINnorNOT INaccepts the same set of argument types, or compares values the same way, as the comparisons it replaces. Three separate defects follow.1. Result type changes from
UInt8toNullable(UInt8)forVariant. Withuse_variant_default_implementation_for_comparisons = 0,equals/notEqualson aVariantexpression resolve toUInt8, but the resultingin/notInresolve throughFunctionBaseVariantAdaptortoNullable(UInt8).has()never uses that adaptor (it does not use the default implementation for NULLs) so it always returnsUInt8, while thein()it is rewritten to always does for aVariantneedle. Debug and sanitizer builds report this from the query-treeValidationCheckerasFunction ... expects argument N to have UInt8 type but receives Nullable(UInt8) after running LogicalExpressionOptimizer pass. In release builds that check is compiled out, and the aggregate function created during analysis for the capturedUInt8argument type is used as-is by the planner (only window functions are re-created from the actual argument types), so the divergence reaches execution.2. A working query starts failing for a dynamic structure.
in/notInreject arguments whose type has a dynamic structure outright, and do not use the default implementation forDynamic, so resolving the rewritten node throwsIllegal type Array(Dynamic) of argument of function notIn(error 43) out of the optimizer pass, in every build type. This affectsDynamicas well as types that merely contain one (Array(Dynamic),Map/Tuple/VariantoverDynamic) andJSON.3. The rewrites silently return wrong results when the constants are not compared as they were. Two independent causes, one per direction.
convertNotEqualsChainToNotInbuilt the right-hand side asConstantNode(Tuple), so the element types were re-derived from theFieldvalues byFieldToDataType. That collapsesDateTimetoUInt32,DateTime64to a plainDecimal64, anEnumto its underlying integer and so on, and the rewrittennotInthen compares against different values than the chain it replaced.tryReplaceOrEqualsChainWithInhas passed an explicitDataTypeTuplebuilt fromConstantNode::getResultType()since #66344 for this exact reason; theNOT INdirection never did.Keeping the types is necessary but not sufficient, in either direction: the set converts every element to the expression's type, while the comparison it replaces is evaluated in the wider of the two. Where that conversion is lossy the two disagree.
The fix keeps the original chain whenever the rewrite cannot preserve the type, cannot be built, or would not compare the same values:
tryReplaceOrEqualsChainWithIn: skip when the expression has a dynamic structure (checked before theinnode is resolved, since resolving it is what throws), and skip when the resultinginis nullable while none of the replacedequalswas. The second guard keys on the drift, not on the type, so the rewrite still fires for aVariantcolumn onceuse_variant_default_implementation_for_comparisons = 1makesequalsnullable too, and the existingk = 1 OR k = NULLre-wrapping is unaffected.convertNotEqualsChainToNotIn: the same two guards, plus the typed tuple. Here the nullability guard needs no drift term: the caller returns early when theANDis nullable, andANDis nullable whenever any operand is, so a surviving non-nullableANDimplies everynotEqualswas non-nullable.tryConvertToColumnType(), which the comparison-filter folding in this same pass already uses for that question, and whose comment block documents exactly thisDateTimetoDatetruncation. ANULLconstant is excluded before either chain is collected, so it never reaches the check.HasToInPass: addVariantto the needle-type exclusion list it already keeps forNullable/LowCardinality/Dynamic/... for exactly this reason.has()never takes the variant adaptor, so the drift is unconditional there and the type is the right key.Query semantics change only where they were wrong (defects 2 and 3); a skipped rewrite leaves the original chain, which was already correct. The optimization still fires for every type where
in/notInpreserves both the result type and the comparison, and the regression test asserts that fires/skips split withEXPLAIN QUERY TREEin both directions, including theVariantcolumn with the setting on and a plain needle forhas(), so a blanket "excludeVariant" guard cannot pass unnoticed.Found by the AST fuzzer, STID 0250-20a8, on a
windowFunnel(...)((b = '10') OR (b = '22') OR (b = '6'), ...)shape wherebisVariant(UInt256)and the job pinscompatibility = 24.3(henceuse_variant_default_implementation_for_comparisons = 0, the default before 26.1 and still a supported configuration). Defect 3 was found by the automated review of this PR.Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108715&sha=e0ab38d92bcb293849e8bf35e1932a7ae8b94316&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29
I found no open issue for this signature, so the report URL above is the provenance.
Version info
26.8.1.156(included in26.8and later)