Repository navigation
Conversation
Whether a query is accepted must not depend on an optimizer threshold. With s
bound to materialize('1'), on master at pure defaults:
WHERE s != 1 AND s != 2; -- Code: 386 NO_COMMON_TYPE
WHERE s != 1 AND s != 2 AND s != 3; -- 0
WHERE s = 1 OR s = 2 OR s = 3; -- 1
WHERE s = '1' AND s = 1; -- 1
FunctionComparison::getReturnTypeImpl admits a String or FixedString operand
against an operand of any other type ("Everything can be compared with string by
conversion"); that overload takes const DataTypes & and cannot see which side is
constant. At execution only a constant String is coerced, by
executeWithConstString, so when the non-constant side is the string the call
falls through to executeGeneric, whose first statement is
getLeastSupertype(DataTypes{c0.type, c1.type}) and which throws. The comparison
therefore resolves and then refuses to run.
LogicalExpressionOptimizerPass removes such a comparison in four ways: merging an
AND chain into NOT IN, merging an OR chain into IN, pruning a comparison made
redundant by a stronger one on the same expression, and collapsing a conflicting
conjunction to false. Removing the only unexecutable operand turns a query the
engine refuses into a query that succeeds, so acceptance depends on
optimize_min_inequality_conjunction_chain_length,
optimize_min_equality_disjunction_chain_length and
optimize_redundant_comparisons. All four reach a tuple expression carrying such a
position as well - flat String, FixedString, LowCardinality(String),
Nullable(String), and Tuple(String), Tuple(String, UInt8) with one bad position,
Tuple(Tuple(String)), Tuple(Nullable(String)), Tuple(LowCardinality(String)).
The pass already tries to uphold this invariant in three places and all three key
on the wrong property. Two hasDynamicStructure() bail-outs say "building it would
turn a working OR chain into an error", and the found_conflict veto says
collapsing the AND "would drop that operand and suppress the exception, making the
query result depend on optimize_redundant_comparisons" - then enforces it by
looking for a filter with no converted_value, which a String-expression-versus-
UInt8-constant filter is not, because Field(1) converts to "1" perfectly.
All four paths route their constant through tryConvertToColumnType, and its three
call sites all decline when it returns nullopt, so the executability test goes
there and covers every path at once.
getReturnTypeImpl has TWO clauses that admit a pair the execution path then
refuses: the String one above, and the one admitting two tuples of equal size
whatever their elements are. A both-tuples comparison is executed element by
element, so one such position refuses the whole comparison - which is why the
predicate recurses through aligned tuple elements and strips LowCardinality and
Nullable at every level, not only at the top. Measured on the fix without that
recursion: Tuple(String) against Tuple(UInt8) threw at one term and returned 1 at
three, the same cliff as the flat case.
There are two ways for such a pair to be refused, which is why the predicate
requires the least supertype to be string family rather than merely to exist. A
String against a UInt8 has no supertype at all. A String against a Dynamic has
one, Dynamic, because getLeastSupertype returns Dynamic for any pair containing
one; the comparison resolves to Nullable(UInt8) and is refused at execution on the
type the Dynamic actually holds, reporting "no supertype for types String, UInt8".
Measured: s = CAST(1, 'Dynamic') threw at one term while the three-term OR chain
returned 1. For every pair getLeastSupertype does consider compatible with a
string it returns String, so requiring that leaves the Enum merge alone, and it
covers Variant, which has no common type with a string at all.
A Variant on the EXPRESSION side is refused by a third mechanism, which is why a
clause-based enumeration of the two above does not reach it. Such a comparison
reaches neither admitting clause: it resolves through the variant adaptor, so its
result type is Nullable(UInt8), and at execution each row is dispatched on the
alternative it holds, refusing a String alternative against a UInt8 constant.
DataTypeVariant::hasDynamicStructure is any_of over the alternatives, so a fixed
alternative set reports none and the two chain sites' bail-outs do not fire; the
leaf then saw Variant(String, UInt8), which is not string family, and answered
executable. Measured on Variant(String, UInt8) against toUInt8: one term threw
386, the three-term OR chain returned 0, and raising the threshold threw again,
flat and inside a tuple alike. The predicate therefore recurses into the
alternatives. The executability test also had to move ahead of the
equal-declared-type shortcut in tryConvertToColumnType: that shortcut returned a
constant of the expression's own declared type unchanged before the test was
consulted, which bypassed it for v = CAST(1, 'Variant(String, UInt8)') and for the
same shape in a tuple. For equal types the leaf computes tryGetLeastSupertype(T, T)
= T, so the move leaves every other verdict where it was.
An alternative can be refused for two different reasons and the leaf sees only one
of them. The leaf is gated on isStringOrFixedString(expression), so it catches a
String alternative against a UInt8 constant but answers "executable" for a UUID
alternative against the same constant, a pair getReturnTypeImpl admits under
neither clause and which raises ILLEGAL_TYPE_OF_ARGUMENT. Only a Variant needs
that second reason: for a flat expression, and for an aligned tuple position, such
a pair is refused when the comparison is RESOLVED - getReturnTypeImpl throws for
UUID versus UInt8, and inside a tuple each element pair is resolved eagerly by
func->build - so the query errors at every chain length and there is no
threshold-dependent cliff to close. A Variant resolves through the variant adaptor
instead, which defers the refusal to execution, per row, on the alternative that
row holds. The Variant arm therefore also declines an alternative outside the
string family that has no common type with a constant outside it. The
isStringOrFixedString(constant) conjunct is load-bearing: without it the clause
would also stop merging Variant(String, UInt8) against String constants, where the
constant is the side executeWithConstString coerces and the comparison does run.
Measured on Variant(UInt8, UUID) holding a UUID against toUInt8 constants: one
term threw Code: 43, the three-term OR chain returned a count, and raising the
threshold threw again, flat and inside a tuple alike; the != conjunction form of
the same shape throws at every length on both arms and is pinned as a control.
An array element is refused in one of two ways and only the second reaches the
pass, so the recursion is conditional on the element and not on the array. A direct
string-versus-non-string element is refused when the comparison is RESOLVED: the
array branch of getReturnTypeImpl throws for Array(String) versus Array(UInt8) at
any nesting depth, so such a pair gives Code: 43 at one term and at three on both
arms, and the test pins that as a control. An element that DEFERS its own refusal
is not, because that branch resolves each element pair through getReturnTypeImpl's
both-tuples clause, which builds every position through the adaptor, and the
adaptor resolves. Measured on Array(Tuple(Variant(String, UInt8))) against
Array(Tuple(UInt8)): one term threw Code: 43 "while executing function equals on
arguments __table1.a", the three-term OR chain returned 0 with notIn node count 1,
and raising the threshold threw again. Two array levels down behaves the same. The
predicate therefore recurses into the nested type when BOTH sides are arrays, which
leaves Array(Int64) against Array(UInt64) merging because that recursion reaches a
non-string, non-carrier leaf and answers executable. The mismatched pairs that
carry no string-family operand also throw at resolution, measured - materialize(1)
!= materialize(uuid) and materialize(toDate(...)) != materialize(1) both give
Code: 43 at one term and at three.
A constant can defer its own refusal the same way, and until now nothing looked at
the constant at all unless the expression was string family. A constant that only
CARRIES its value chooses a type per row, and
ExecutableFunctionDynamicAdaptor::executeImpl opens with
convertToFullColumnIfConst() on the carrier argument (FunctionVariantAdaptor does
the same), so the stored value is never a const column while
executeWithConstString needs checkAndGetColumnConstStringOrFixedString. The
coercion that makes u = '1' work therefore cannot apply to a string a constant
merely carries, and the dispatch falls to executeGeneric. Measured on a UInt8
expression against CAST('1', 'Dynamic'): one term threw 386, the three-term OR
chain returned 1, and raising the threshold threw again; identical against a
Variant(String) constant. Under dynamic_throw_on_type_mismatch = 0 the same chain
changes the ANSWER rather than the acceptance, 0 at one term against 1 at three,
because the carried strings convert losslessly to the expression's own type. The
predicate therefore declines any constant with dynamic structure or a Variant
constant, before the tuple and array arms. Both halves are needed:
DataTypeVariant::hasDynamicStructure is any_of over the alternatives so a fixed
alternative set reports none, and isVariant alone would miss a JSON constant and a
tuple or array carrying one, since Tuple, Array, Map, Nullable and LowCardinality
all forward hasDynamicStructure to what they hold. A carrier below a tuple whose
alternatives are fixed is reached by neither half at the top level and only by the
element-wise recursion arriving at the leaf: Tuple(UInt8) against a
Tuple(Variant(String)) constant threw at one term, returned 1 at three, and is
pinned.
Map and AggregateFunction pairs deliberately get no arm, measured rather than
argued: no admitting clause covers either, so both are refused when the comparison
is resolved, giving Code: 43 at one term, at three and above the threshold on both
arms, with EXPLAIN QUERY TREE throwing rather than reporting a node count. The one
shape the predicate cannot see, a Map whose value type carries a fixed-alternative
Variant as the constant, is unreachable for that same reason and is pinned as a
control. An adjacent class was measured and is NOT covered by this change, so the
changelog entry does not claim it: a Decimal64(2) expression against DateTime64
constants is admitted by the both-numeric clause and can be refused by
allowDecimalComparison, but it answers identically at one term, at three and above
the threshold, so it has no threshold-dependent cliff.
Why it is keyed on the least supertype and not on the constant's type name:
getLeastSupertype makes String, FixedString, Enum8 and Enum16 mutually compatible
with common type String, and 04652_enum_constant_vs_string_column asserts that a
three-disjunct OR chain over a String primary-key column against Enum8 constants
is still merged. A type-name-shaped guard breaks that test; the supertype-shaped
one leaves it untouched.
Why the expression side is gated on being string-family: two pairs have no least
supertype and nevertheless execute, and both must keep being merged - an
Array(Int64) expression against Array(UInt64) constants, which compares element
by element, and a UUID expression against constant String literals, which
executeWithConstString coerces. Both measured with notIn node count 1 before and
after.
A FixedString(16) is comparable with an IPv6 without having a common type, but
the merge does not fire there anyway, because the IPv6 constant has no lossless
FixedString(16) form and the pre-existing round-trip guard declines first;
measured identical on both arms and pinned in the test.
The predicate has to be total, and tryGetLeastSupertype is not: it reports a
missing common type by returning null for every pair except two Intervals whose
groups differ, where findSmallestIntervalSuperType throws NO_COMMON_TYPE directly
instead of routing through throwOrReturn<on_error>, which returns null for
LeastSupertypeOnError::Null. That exception escaped the probe and refused an
executable chain at exactly the merge length while both the single comparison and
the same chain above the threshold answered, the precise inverse of the invariant
above. Measured on a Variant(IntervalDay, IntervalMonth) expression holding
IntervalDay against an IntervalDay constant: 1 at one term, Code: 386 at three, 3
above the threshold. getLeastSupertype recurses into nested types, so the clashing
pair counts at any depth and the guard is keyed on IDataType::forEachChild rather
than on isInterval of the two operands; a Variant(Tuple(IntervalDay)) against a
Tuple(IntervalMonth) constant, which a top-level guard would miss, is pinned. Only
a two-interval Variant needs allow_suspicious_variant_types:
Variant(IntervalDay, String) and Variant(Tuple(IntervalDay)) are creatable at pure
defaults, because validateDataType's suspicion probe calls the same
tryGetLeastSupertype and reads its null as permission. Declining whenever an
interval is present is wider than the pair that throws, in the same way the
alternative-wise clause is wider than executability; the cost is a fold and never
an answer, and Variant(IntervalDay) against an IntervalDay constant is pinned at
1, 3 and 3 with merge count 0 on both arms to hold that. Repairing
findSmallestIntervalSuperType to honour on_error is the root-cause fix for that
helper and is deliberately left out of this change: it moves the returned value
and the error text for every tryGetLeastSupertype, getLeastSupertypeOrString and
getLeastSupertype<Dynamic> caller, including the suspicious-variant diagnostic it
currently misreports.
This makes some currently-succeeding queries throw. They already throw with one
term fewer on the same build, so no consistent behaviour is being removed, and no
test in the tree asserted the accepting shape, so no reference file changes.
Related: ClickHouse#121006
Co-Authored-By: Claude Opus 5 <[email protected]>
Keep only the pre-existing semantics a reader cannot derive from the code: what FunctionComparison resolves versus what it executes, what getLeastSupertype returns, the Interval pair tryGetLeastSupertype throws on, and how a Dynamic or Variant operand is dispatched. The design, the measurements and the refuted alternatives are in the commit message of the change itself.
Internal second-model reviewAn independent model reviewed this change against the tree, and a second one re-reviewed it cold ❌ Blocker, fixed: the executability probe could itself throw, inverting this change's own contract. ❌ Blocker, fixed: a ❌ Blocker, fixed: a ❌ Blocker, fixed: tuple-wrapped string positions, and a ❌ Blocker, fixed: a least supertype is not proof the comparison can run.
💡 A question I would rather you settled than I assumed. The first blocker's root cause is one layer 💡 Two levers, both yours. A guard for a flat 💡 Design alternative considered and declined. The opposite fix is to make execution coerce the Everything else raised was editorial or refuted against the source. The test was measured in both |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260920-044000 |
|
Workflow [PR], commit [b7729b0] Summary: ❌
AI ReviewSummaryThis PR hardens Findings❌ Blockers
Final VerdictChanges requested: the remaining blocker is the still-open LLVM Coverage ReportMeasured on commit b7729b0.
Changed lines: Changed C/C++ lines covered: 49/51 (96.08%) · Uncovered code |
The executability guard declined every comparison whose constant is declared `Variant`, whatever its alternatives are. 05059's last assertion requires the chain -> IN rewrite to still fire for a `Tuple(DateTime, Variant(UInt64))` compared with a constant of the same type: the tuple arm recurses element-wise, element 2 hit the blanket decline, the rewrite declined and the assertion dropped 1 -> 0. `Variant(UInt64)` against `Variant(UInt64)` is executable. The default implementation for `Variant` decomposes the operand into the alternative each row holds, and `UInt64` against `UInt64` compares numerically. What a `Variant` constant does lose is coercion: the alternative it carries arrives materialized, so `FunctionComparison::executeWithConstString` no longer converts a string it holds, and `getLeastSupertype` has to admit the pair on its own. Measured on master, expression first and constant second: String vs Variant(String) ok UUID vs Variant(String) NO_COMMON_TYPE UInt64 vs Variant(String) NO_COMMON_TYPE UInt16 vs Variant(Date, UInt16) ILLEGAL_TYPE_OF_ARGUMENT UUID vs Dynamic NO_COMMON_TYPE Variant(UUID) vs a String literal ok, a string constant is coerced Variant(UInt64) vs Variant(UInt64) ok So a `Variant` constant now gets the alternative-wise arm the expression side already has, and `constant_is_materialized` carries the lost coercion down the recursion: a materialized operand needs a supertype of its own, whether or not either side is a string. `Dynamic` keeps declining as a whole, having no static alternative set to walk. The `Date` row above is the one a string-only test would miss. Its day number converts to `UInt16` losslessly, so three equalities merged and answered 1 while a single term and the threshold-raised chain raised `ILLEGAL_TYPE_OF_ARGUMENT`; 05230 now pins that shape scalar and one tuple position down, and a comparable carried value keeps both its answer and its merge so the arm cannot regress into a blanket decline. Both directions measured on this tree: 05059 fails with `-1 +0` before the change and passes after, the two new chain rows answer 1 instead of throwing without the supertype requirement, and the reported query of issue ClickHouse#121006 still raises NO_COMMON_TYPE at every chain length.
Review asked why the executability test declines a chain whose constant carries an
alternative the expression can be compared with, for instance
u = CAST(toUInt16(1), 'Variant(Date, UInt16)'), given that only the carried
alternative is executed. Such a chain does run, and the decline costs the merge and
not the answer, but it cannot be narrowed by looking at the carrier, because the
carrier is not there to look at. A Variant value read into a Field keeps only the
nested value (ColumnVariant::get), so a Variant(Date, UInt16) constant carrying
UInt16 1 and one carrying Date day 1 reach the pass as the same Field with the same
declared type, and master merges both into the byte identical predicate
in(u, tuple(_CAST(_CAST('1970-01-02', 'Date'), 'Variant(Date, UInt16)'), ...)).
The two need opposite verdicts: the UInt16 carrier executes, while the Date carrier
throws ILLEGAL_TYPE_OF_ARGUMENT as a single comparison and must not be merged, which
the rows above this block pin.
Rebuilding the constant is also not value preserving, so restoring the merge would
trade a missing optimization for a wrong answer. The rebuilt value has no
discriminator and lands in the first declared alternative:
CAST(toUInt32(100000), 'Variant(Date, UInt32)') reports variantType UInt32 and 100000,
while the constant master's merge writes into the tuple reports Date and 2064-05-11,
the day number 34464. So master answers 0 for the merged chain where one comparison
and the unmerged chain both answer 1. A hand written IN over the original constant
answers 1, so this is the rebuild and not the set.
Test only, no source change. The rows assert results rather than the absence of a
merge, so a merge that does reproduce the constant's value keeps them green. Mutation
control: without the guard, variant_two_alternatives_constant_chain answers 0 against
the reference 1. 12/12 green under the test runner's randomization.
4d974a0 to
1b14057
Compare
Review asked why the executability test declines a chain whose Variant alternative is an array, given that FunctionComparison compares two arrays element wise when the pair has no least supertype, so Array(Int64) against an Array(UInt64) constant executes. The fact is right: the alternative wise clause keys on tryGetLeastSupertype, which is null for the Int64 and UInt64 element pair, and materialize([toInt64(1)]) = [toUInt64(1)] answers 1. That is the same conservatism the variant_cross_numeric rows above pin one level up. Here it does not cost a fold, because the set the rewrite would build cannot execute at any element type. getCompoundTypeDepth in src/Analyzer/SetUtils.cpp does not look inside a Variant, so the depth arithmetic refuses Variant(Array(Int64)) against a tuple of array constants with ILLEGAL_TYPE_OF_ARGUMENT, Unsupported types for IN, whether the elements are UInt64 or Int64. On master the three term chain is therefore rejected while one term and a raised threshold both answer 3, which is the chain length dependent acceptance this PR removes, and the decline is what removes it. Measured on 26.10.1.1 debug, master snapshot build id 3f171735 against this head 67d22a5d: variant_array_cross_numeric_chain answers 3 here and fails on master with that Code 43. The carrier direction, an Array(Int64) expression against a Variant(Array(UInt64)) constant, is the same shape and is refused on master with Code 53 in the IN section. plain_array_cross_numeric_merged stays 1, so the element pair alone does not stop a fold, the Variant wrapper does. Not pinned here: with matching element types the probe admits the pair, the rewrite fires and the same Code 43 follows on master and on this head. That residual is pre-existing and has a different cause, the set builder's depth arithmetic rather than comparison executability, so it is reported on the PR thread rather than pinned as expected behaviour. Test only, no source change. 12/12 green under the test runner's randomization.
| return true; | ||
|
|
||
| const auto bare_alternative = removeLowCardinalityAndNullable(alternative); | ||
| if (!isStringOrFixedString(bare_alternative) && !isStringOrFixedString(constant) |
There was a problem hiding this comment.
This still leaves a threshold-dependent failure for compound Variant alternatives/carriers whose comparison is executable but whose rewritten IN is not. A minimal shape is CAST([toInt64(number)], 'Variant(Array(Int64))') AS v with v = [toInt64(1)] OR v = [toInt64(2)] OR v = [toInt64(3)]: this helper reaches the Array(Int64) alternative, decides the comparison is executable, and lets OR -> IN fire, but SetUtils::getCompoundTypeDepth does not unwrap Variant, so the rewritten IN still throws Unsupported types for IN while a single term and the same chain above threshold run.
That means the PR's contract is still violated for Variant(Array(...)) / Variant(Tuple(...)) with matching inner types. comparisonWithConstantIsNotExecutable needs to decline those compound Variant shapes too (on both the expression and constant side), or the IN/NOT IN set builder has to learn how to unwrap Variant before these rewrites are enabled.
CI finish ledger - 6c50553Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Gates: (a) 0 of 173 checks queued or running; (b) Session id: cron:our-pr-ci-monitor:20260920-143138 |
CI finish ledger - b7729b0Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The red The Session id: cron:our-pr-ci-monitor:20260921-000159 |
|
Closing in favour of #121719. The root cause is in |
|
Agreed, and no objection to the close. Rejecting the pair where the comparison is resolved is the better site: it holds at every chain length, it does not depend on which pass ran, and it covers Agreed on #121006 as well: that query should keep failing, for the reason already recorded on the issue. Your first example is live on today's master ( #121196 is not subsumed by #121719, so I am leaving it open. Its pair has no
One residual that #121719 leaves by design (the early return for |
Related: #121006
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Comparing an expression against a constant of an unrelated type is now rejected with the same error a single such comparison raises (
NO_COMMON_TYPE, or the comparison's own), wherever it was already rejected with one term fewer: aStringorFixedStringexpression (s != 1wheresis aString), such a position at any tuple or array depth, aVariantalternative the constant cannot be compared with, and any expression against a value-only constant (Dynamic,Variant,JSON, or a tuple or array holding one). Previously a long enoughAND/ORchain was merged intoNOT IN/INfirst, so the query was accepted at three terms, rejected at two;optimize_redundant_comparisonsdid the same by pruning or collapsing one. Use a constant of a compatible type,s != '1', to keep the query working.Description
Whether a query is accepted must not depend on an optimizer threshold. On master at defaults,
s=materialize('1'),u=materialize(toUInt8(1)):Root cause:
FunctionComparisonadmits a string-family operand against any other type, but only a constant string is coerced at execution, so with the constant on the other side it needs a common string type and throws without one; a value-only constant is never coerced at all: the adaptor dispatching on it materializes it first. Four optimizations then delete that operand: two chain merges, pruning, the fold tofalse.All four route their constant through
tryConvertToColumnType, whose three call sites decline onstd::nullopt, so the fix is one predicate, mirrored through tuples, arrays andVariantalternatives where the same cliff exists, and on the constant side where a carrier defers its refusal to the rows. A guard for a flatStringexpression alone is three lines; say so and I will cut it back. #111924's lossless guard and the old AST-level optimizer are untouched, so such a projection still attaches.Some currently-succeeding queries now throw by design, having already thrown with one term fewer. I picked the louder category; say the word for
Bug Fix.The reported query still errors, correctly, so this is
Related, notCloses. The other half it exposed,INover a string expression against aUUIDconstant matching nothing, is #117240 / #118372, which wants this guard first: a faithfulStringrendering would otherwise re-enable these rewrites for every self-typed constant.Validation and overlap with in-flight PRs
Two servers with asserted build IDs: the new test is
[ OK ]on the fix and[ FAIL ]on pristine base, 41 rows expecting an error the base did not raise. Of its 46 labelled rows, 38 print identically on base; the 8 that differ are merge pins this change moves.NOT IN/INmerge on a string-family expression, or such a position nested in a tuple or arrayNO_COMMON_TYPEfalseon conflictNO_COMMON_TYPEDynamic,Variant,JSON); aVariantalternative the constant cannot be compared withThe sharpest row asserts a result, not an acceptance: under
dynamic_throw_on_type_mismatch = 0the same chain answered 0 at one term and 1 at three, so the merge changed the answer, not only whether the query ran. It answers 0 at both lengths now.Array(Int64)againstArray(UInt64), andUUIDagainst constant strings, have no common type yet execute, and keep merging; the predicate keys on the common type, not on type names, soString,FixedStringandEnum(common typeString) keep merging too. AMappair and anAggregateFunctionpair are refused when the comparison is resolved, at every chain length, so neither needs an arm; measured, not argued.Nineteen mutation arms, sixteen redden a named row. Neighbour A/B over 1388 patterns, 1366 tests per arm: one transition, this test. 50 randomized runs green, clang-tidy clean.
Overlap: #117293 and #121047 touch this file well below the edit, and #117293's guard needs both sides in the string family, so it misses this class. #112272 adds the same include and #117595/#117637 add a helper at this anchor, so whichever merges second takes a mechanical conflict. #121065 touches this file too, without overlapping the edit.
Workflow [PR]
Sync PR [sync-upstream/pr/121146]