Skip to content

Do not optimize away a comparison the query could not have executed - #121146

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:do-not-optimize-unexecutable-comparison-chains
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:do-not-optimize-unexecutable-comparison-chains

Conversation

@groeneai

@groeneai groeneai commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121006

Changelog category (leave one):

  • Backward Incompatible Change

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: a String or FixedString expression (s != 1 where s is a String), such a position at any tuple or array depth, a Variant alternative 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 enough AND/OR chain was merged into NOT IN/IN first, so the query was accepted at three terms, rejected at two; optimize_redundant_comparisons did 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)):

WHERE s != 1 AND s != 2;                      -- Code: 386
WHERE s != 1 AND s != 2 AND s != 3;           -- 0
WHERE u = CAST('1','Dynamic');                -- Code: 386
WHERE u = CAST('1','Dynamic') OR ... OR u = CAST('3','Dynamic');  -- 1

Root cause: FunctionComparison admits 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 to false.

All four route their constant through tryConvertToColumnType, whose three call sites decline on std::nullopt, so the fix is one predicate, mirrored through tuples, arrays and Variant alternatives where the same cliff exists, and on the constant side where a carrier defers its refusal to the rows. A guard for a flat String expression 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, not Closes. The other half it exposed, IN over a string expression against a UUID constant matching nothing, is #117240 / #118372, which wants this guard first: a faithful String rendering 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.

path before after
NOT IN/IN merge on a string-family expression, or such a position nested in a tuple or array accepted NO_COMMON_TYPE
pruning by a stronger comparison; the fold to false on conflict accepted NO_COMMON_TYPE
a value-only constant (Dynamic, Variant, JSON); a Variant alternative the constant cannot be compared with accepted the comparison's own error

The sharpest row asserts a result, not an acceptance: under dynamic_throw_on_type_mismatch = 0 the 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) against Array(UInt64), and UUID against constant strings, have no common type yet execute, and keep merging; the predicate keys on the common type, not on type names, so String, FixedString and Enum (common type String) keep merging too. A Map pair and an AggregateFunction pair 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]

groeneai and others added 2 commits September 20, 2026 06:54
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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this change against the tree, and a second one re-reviewed it cold
without the author's notes, over seven rounds. The internal fix-round cap was reached, so the tree is
published as it stands; the residual findings are listed below as noted-not-blocking rather than
silently dropped.

❌ Blocker, fixed: the executability probe could itself throw, inverting this change's own contract.
tryGetLeastSupertype was used as a total test and is not: findSmallestIntervalSuperType
(getLeastSupertype.cpp:267) throws bare instead of going through the on_error machinery, and
getLeastSupertype recurses, so an interval pair at any depth raised and an executable chain measured
1 / Code: 386 / 3 across the threshold. Both probe call sites now decline any pair carrying an
Interval, and the three lengths are pinned as agreeing.

❌ Blocker, fixed: a Variant hidden under Array(Tuple(...)) bypassed the guard, turning Code: 43 at one term into a successful result at three. The predicate now recurses into aligned array element
types, with array_merged and tuple_array_merged pinning that ordinary array folds still fire.

❌ Blocker, fixed: a Dynamic or Variant constant bypassed the guard when the expression was
outside the string family.
The one class that changed an answer rather than acceptance: under
dynamic_throw_on_type_mismatch = 0 the chain answered 0 at one term and 1 at three, because the
carried strings convert losslessly to the expression's own type. It answers 0 at both lengths now.

❌ Blocker, fixed: tuple-wrapped string positions, and a Variant expression holding a String.
Equal-size tuples are admitted whatever their elements are (FunctionsComparison.h:1819) and compared
element by element, and a fixed alternative set reports no dynamic structure, so neither shape bailed
out at the top-level type; the predicate now walks aligned tuple elements and Variant alternatives at
any depth, stripping LowCardinality and Nullable at each level.

❌ Blocker, fixed: a least supertype is not proof the comparison can run. getLeastSupertype
returns Dynamic whenever either side is, so the probe now requires the common type to be itself in the
string family, which is what it returns for every pair it considers compatible with a string (:692,
"No other types are compatible with Strings"); Enum and FixedString merges are untouched.

⚠️ Noted, not changed: the old AST-level optimizer still rewrites such a chain in a projection
definition.
LogicalExpressionsOptimizer runs from TreeRewriter outside the
ast_optimizations_allowed gate, so a projection definition holding three such equalities is accepted
while the two-term form raises NO_COMMON_TYPE. Deliberately left alone: that same function runs during
ATTACH, so rejecting a definition accepted today would leave an existing table unable to attach, and
the guard cannot be spelled at that level, since the rewrite sees ASTLiteral values with no data type.
Pinned as unchanged so a later change is noticed there.

⚠️ Noted: the guard is wider than executability in two places, and in both the cost is a fold and
never an answer.
FixedString(16) against IPv6 is comparable without having a common type, and the
Variant arm declines an alternative with no common type with the constant, so Int64 against a
UInt64 constant loses its fold. The first is unreachable today, because the pre-existing round-trip
guard refuses an IPv6 constant for a FixedString(16) column first, and three rows pin the pair
unchanged on both arms; the second is pinned by variant_cross_numeric against its plain-Int64 twin,
both answering 3. Keying on the comparison's own admissibility rules instead would trade a real
regression risk for no correctness gain.

⚠️ Noted: one sub-clause of the guard is inert. The interval short-circuit on the string-family
branch cannot fire, so it makes the predicate total by construction rather than by an argument about
branch order. Removable with no measured row moving, if you would rather have one clause fewer.

💡 A question I would rather you settled than I assumed. The first blocker's root cause is one layer
down and pre-existing: findSmallestIntervalSuperType throws bare, so tryGetLeastSupertype breaks its
own LeastSupertypeOnError::Null contract for every caller, measurably misreporting the
suspicious-Variant diagnostic (parseColumnsListForTableFunction.cpp:104). I left it alone because the
blast radius is every tryGetLeastSupertype / getLeastSupertypeOrString / getLeastSupertype<Dynamic>
caller and I cannot validate that in this PR, and because on the queries I could reach the request is
refused either way, so only the message is wrong. Say the word and I will repair it at the source.

💡 Two levers, both yours. A guard for a flat String expression alone is three lines, and the test
shrinks with the predicate, so that lever cuts both the diff and the 571-line test. Separately, my open
#117595 adds a helper at this same anchor that walks the same structural shapes for a different reason
(NaN ordering, not executability); if you want one traversal, the right place is whichever of the two
merges second, not a PR built on an unmerged helper.

💡 Design alternative considered and declined. The opposite fix is to make execution coerce the
constant the way the set does, accepting every chain length instead of rejecting it. It cannot be applied
uniformly yet: for a UUID constant convertFieldToType renders a quoted literal and the comparison
would silently never match. That is the second defect named in the description, and it has to land first.

Everything else raised was editorial or refuted against the source. The test was measured in both
directions on two servers with asserted build IDs, the final run on the committed head, and the mutation
arms were restored with the source hash asserted equal and the rebuild reproduced bit for bit.

@clickhouse-gh clickhouse-gh Bot closed this Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no table, no randomization. With s = materialize('1'), s != 1 AND s != 2 AND s != 3 returns 0 on base and Code: 386 with the fix while the two-term form throws on both; the Dynamic/Variant-constant, tuple-wrapped, array-nested and Variant-expression shapes behave the same way, one of them changing the ANSWER (0 at one term against 1 at three, under dynamic_throw_on_type_mismatch = 0), and the two-interval Variant carrier, which needs nothing set, answers 1 / Code: 386 / 3 across the threshold on the intermediate head against 1 / 3 / 3 with the fix.
b Root cause explained? FunctionComparison::getReturnTypeImpl admits a string-family operand against any other type and two equal-size tuples whatever they hold, but at execution only a plain constant string is coerced, so with the constant on the other side the comparison needs a common string type and throws without one, and four optimizations in LogicalExpressionOptimizerPass delete exactly that operand, making acceptance depend on an optimizer threshold. Five refusals have to be caught: no common type at all; a common type that is not a string, which is what a Dynamic operand yields; a Variant expression, which reaches neither admitting clause because it is dispatched per row through the variant adaptor; on that path, an alternative refused for a reason outside the string family; and a constant that only CARRIES its value, which ExecutableFunctionDynamicAdaptor::executeImpl materializes before executeWithConstString can match. The probe must also be total, because tryGetLeastSupertype throws rather than returning null for two Intervals of different groups, at any depth.
c Fix matches root cause? Yes for this pass's own contract: the predicate is the executability test itself, evaluated at the single point all four removal paths already consult before substituting a constant, and kept total by declining whenever an Interval is present at any depth rather than letting the probe throw through the pass. Over-declining can only forgo a fold, never change an answer, and control rows pin exactly that, including two deliberately over-wide cases. Repairing findSmallestIntervalSuperType to honour on_error is deliberately not in this PR, because it moves the returned value and the error text for every tryGetLeastSupertype, getLeastSupertypeOrString and getLeastSupertype<Dynamic> caller. Nothing widened, no test weakened, no no-random-* tag, no error suppressed, #111924's lossless guard untouched.
d Test intent preserved / new tests added? No existing row's expected value changed, and one label was corrected to match the value it always asserted (variant_no_string_alternative_merged asserted 0, so it is now ..._not_merged; both rows kept, each still an exact pin). 05230_chain_to_in_string_expression_not_comparable pins 101 serverError rows (77 NO_COMMON_TYPE, 23 ILLEGAL_TYPE_OF_ARGUMENT, 1 pre-existing TYPE_MISMATCH) plus 56 labelled rows, fifteen of them merged / not-merged pairs, with each interval shape pinned at one term, at the default threshold and above it, and one pair asserting a RESULT the merge used to change rather than an acceptance.
e Both directions demonstrated? Yes, three independent ways: clickhouse-test is [ FAIL ] on the pristine base (build id 12fe6201..., 41 rows of "The query succeeded but the server error ... was expected") and [ OK ] on the fix (9f0531ef...); [ FAIL ] on the intermediate head (f01eaf91...), aborting at interval_variant_three_terms with every earlier row matching byte for byte, so the new rows are live and not decorative; and 20 mutation arms, 17 of which redden a named row, the three that redden nothing recorded with their measured reason, after which the source was restored with its sha256 asserted and the rebuild reproduced the same Build ID bit-identically.
f Fix is general across code paths? Eleven carriers were enumerated and each measured: the affected ones are all fixed by the one choke point, while has-to-IN, arrayExists-to-has, tryOptimizeAndCompareChain and redundant-equals removal are measured NOT to be carriers, with the pass on and off. Both admitting clauses of getReturnTypeImpl and both supertype-probe call sites are covered; a Dynamic expression deliberately gets no arm, because both chain sites bail out on hasDynamicStructure() first and an arm would be dead code; Map and AggregateFunction pairs are measured unreachable and pinned as controls rather than assumed; the legacy AST-level optimizer keeps its behaviour deliberately, since it also runs during ATTACH and rejecting a definition accepted today would stop an existing table attaching.
g Fix generalizes across inputs? Every constructor that can nest another type was walked and recorded: Nullable and LowCardinality stripped at every level, Tuple recursed element by element, Array recursed into the nested type when both sides are arrays and pinned two levels down, Variant handled on the expression side alternative by alternative and on the constant side with the fixed-alternative case pinned separately, Dynamic and JSON caught by hasDynamicStructure(), Map and AggregateFunction measured unreachable. The interval guard is keyed on the recursive IDataType::forEachChild, with six measured carriers; the constant side is measured across 20-plus types; thresholds 1, 2, 3 and 100 are pinned; the controls that must keep merging do (String vs String/Enum/FixedString, Array(Int64) vs Array(UInt64) flat and tuple-wrapped, UUID vs constant strings, FixedString(16) vs IPv6, three Variant-expression shapes); and the adjacent Decimal64(2)-against-DateTime64 class was measured to have no threshold cliff, so the changelog entry does not claim it.
h Backward compatible? No, deliberately: some queries that succeed today will throw, but they already throw with one term fewer on the same build, so no consistent behaviour is removed, no in-tree test asserted the accepting shape (reference churn: none), and no setting default changed, so no SettingsChangesHistory.cpp entry is owed. Category is Backward Incompatible Change, the louder of the two that fit, with Bug Fix (user-visible misbehavior in an official stable release) offered in the body.
i Invariants and contracts preserved? The predicate is a pure, total function of two DataTypePtrs, and that totality is the invariant this last round restores, because the chain sites call it while deciding whether to fold, so an exception escaping it refuses a query the unoptimized form accepts. tryConvertToColumnType widens on its declining side only, returning std::nullopt in strictly more cases and never a value it did not return before, and all three consumers already handle nullopt; tryFoldBoundaryOrRewriteFloatForIntColumn returns immediately unless the column is a native integer, so it never dereferences the now-empty converted_value; the executability test's position before the equal-declared-type shortcut is pinned by four rows plus a mutation arm that restores the old order. No lock, allocation, data-structure invariant or error path touched; IN's documented element-conversion contract is unchanged. Neighbour A/B over 1584 patterns, 1562 tests on each arm: one transition, this test.

Session id: cron:clickhouse-impl-slot-4:20260920-044000

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b7729b0]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR hardens LogicalExpressionOptimizerPass so OR/AND chain rewrites and redundant-comparison pruning stop deleting comparisons that would have thrown at execution time, and it adds broad stateless coverage around String, Tuple, Array, Dynamic, and Variant carriers. High-level verdict: the main regression is fixed, but the rewrite is still unsound for compound Variant alternatives/carriers with matching inner types, so the contract stated in the PR description is not yet met.

Findings

❌ Blockers

  • [src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp:506] comparisonWithConstantIsNotExecutable still treats Variant(Array(...)) / Variant(Tuple(...)) alternatives as executable when the inner types match, so tryReplaceOrEqualsChainWithIn and convertNotEqualsChainToNotIn can still build IN / NOT IN on a Variant expression or carrier that the set builder cannot execute. SetUtils::getCompoundTypeDepth still unwraps Nullable, Array, and Tuple, but not Variant ([src/Analyzer/SetUtils.cpp:48], [src/Analyzer/SetUtils.cpp:748]), so shapes like CAST([toInt64(number)], 'Variant(Array(Int64))') AS v WHERE v = [toInt64(1)] OR v = [toInt64(2)] OR v = [toInt64(3)] still fail only at the default chain length while one term and the same chain above threshold run. Suggested fix: either decline compound Variant alternatives/carriers here on both the expression and constant side until the set-builder path learns to unwrap Variant, or teach the IN / NOT IN set-construction path to handle Variant before these rewrites are enabled. Add focused rows for matching-inner-type Variant(Array(...)) / Variant(Tuple(...)) on both sides so this stays closed.
Final Verdict

Changes requested: the remaining blocker is the still-open Variant(Array(...)) / Variant(Tuple(...)) threshold cliff at src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp:506.

LLVM Coverage Report

Measured on commit b7729b0.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.80% +0.10%

Changed lines: Changed C/C++ lines covered: 49/51 (96.08%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Sep 20, 2026
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.
@groeneai
groeneai force-pushed the do-not-optimize-unexecutable-comparison-chains branch from 4d974a0 to 1b14057 Compare September 20, 2026 10:23
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)

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.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6c50553

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
Build profile diff infra, not reachable from this diff: the job aborts with a Python traceback out of run_comparison (ci/jobs/build_profile_diff_job.py:1623, reached from main() at :1623) when the CI logs cluster does not answer, instead of degrading to "no baseline". Its only work is reading that cluster; it neither builds nor runs the server. Fleet-wide in the last 24 hours: check_status = error on 320 rows across 320 distinct heads and 310 distinct pull requests, against 540 successes, and the job runs on pull requests only (0 rows at pull_request_number = 0). Open incident: #120462. Re-running or merging master cannot clear it while the endpoint keeps refusing #121048 (external, open). @ alexey-milovidov ruled on 2026-09-20 that this is the one to keep for this class (#120288 (comment)); my #118708 is stood down at his request
Stateless tests (amd_debug, parallel) / 05227_storage_settings_unknown_name true master, deterministic, not reachable from this diff: the server no longer stores the max_threads = DEFAULT reset on the CREATE, so SHOW CREATE prints SETTINGS disk = 'default' where the reference still expects SETTINGS disk = 'default', max_threads = DEFAULT. The in-job randomized-settings diagnosis reports the failure reproducible 223/223 runs with the same settings and 266/266 with randomization off, so it is not a randomization draw. On true master in the last 24 hours: 210 FAIL rows over 9 master heads and 13 distinct checks, first seen 05:31:02Z and last 14:04:49Z #121163 (mine, open)
Stateless tests (arm_binary, parallel) / 05227_storage_settings_unknown_name true master, deterministic, not reachable from this diff: the server no longer stores the max_threads = DEFAULT reset on the CREATE, so SHOW CREATE prints SETTINGS disk = 'default' where the reference still expects SETTINGS disk = 'default', max_threads = DEFAULT. The in-job randomized-settings diagnosis reports the failure reproducible 223/223 runs with the same settings and 266/266 with randomization off, so it is not a randomization draw. On true master in the last 24 hours: 210 FAIL rows over 9 master heads and 13 distinct checks, first seen 05:31:02Z and last 14:04:49Z #121163 (mine, open)

Mergeable Check and PR are the praktika aggregators of the rows above, not an independent failure. Census of the paginated check-runs at this head: 173 distinct names, 49 green, 121 skipped, 3 red, and zero still queued or in progress. Fast test and Style check are green.

Gates: (a) 0 of 173 checks queued or running; (b) Finish Workflow completed green and Mergeable Check completed; (c) 40.3 min since the last job finished, measured against the last completion at 2026-09-20T13:57:52Z; (d) all 3 ownable red rows owned, 0 ownerless, 0 new fix tasks needed.

Session id: cron:our-pr-ci-monitor:20260920-143138

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b7729b0

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
Build profile diff infra, the CI logs cluster refuses the read (ci/jobs/build_profile_diff_job.py traceback); 342 red rows over 294 PRs in 24h, 0 on master, and no re-run clears it #121048 (external, open)

The red PR status is the praktika rollup of the row above; it carries no failure of its own.

The 05227_storage_settings_unknown_name pair carried by the previous head 6c505533 is gone:
its owner #121163 merged at 2026-09-20T17:25:51Z. CIDB carries zero FAIL/ERROR test rows at this
sha, and the dedupped check-run census is 172 green or skipped against the one red above.

Session id: cron:our-pr-ci-monitor:20260921-000159

@fm4v

fm4v commented Sep 23, 2026

Copy link
Copy Markdown
Member

Closing in favour of #121719.

The root cause is in FunctionComparison: it admits a non-constant String against any type when resolving, and throws NO_COMMON_TYPE only at execution. This PR re-implements the execution rules of FunctionComparison inside LogicalExpressionOptimizerPass to predict which comparisons would throw, which drifts (the open Variant(Array(...)) blocker is one example). #121719 rejects the pair at resolution time instead, so the error is raised before any optimizer pass, at every chain length, without touching the optimizer.

@fm4v fm4v closed this Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 enable_analyzer = 0, none of which a predicate inside LogicalExpressionOptimizerPass can promise.

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 (26.10.1.1, 95a6488ae): one term and two terms raise 386, three terms answer 1.

#121196 is not subsumed by #121719, so I am leaving it open. Its pair has no String operand, so the new check returns early on it. Master, defaults, v = CAST([toInt64(number)], 'Variant(Array(Int64))'):

v = [toInt64(1)]                                                     1
v = [toInt64(1)] OR v = [toInt64(2)] OR v = [toInt64(3)]             Code 43, Unsupported types for IN
the same, optimize_min_equality_disjunction_chain_length = 100        3

getCompoundTypeDepth does not descend Variant, so the literals are measured at a depth the set builder will not read as a member list. That PR declines the merge through that same function exported from SetUtils rather than a copy of its arithmetic, but it is still a pass-side check of a downstream failure, so if you would rather have the pair rejected where the set is built, say so and I will move it there. I did not widen IN instead: for that pair only an already Variant-typed right-hand side works (every literal form is Code 43), so descending Variant there would also have to decide which alternative a bare Array(Int64) literal becomes.

One residual that #121719 leaves by design (the early return for isVariant() and hasDynamicStructure()): wrapping the constant keeps the length dependence. On master, toString(number) = CAST(1, 'Dynamic') raises 386 at one and at two terms, answers 2 at three terms, and raises 386 again at three terms with the threshold at 100. Variant(UInt8) is identical, and the != seam declines the same pair. Not wrong results (2 is what the explicit string constants answer), only acceptance depending on chain length. Your early-return list is the cheapest place to close that too, if you want it closed.

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-request PR origin: a maintainer pinged or directed groeneai pr-backward-incompatible Pull request with backwards incompatible changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

NO_COMMON_TYPE (Code 386) between 26.6.1.2150 and 26.8.1.235

3 participants