Skip to content

Require a converted constant to be a semantic point for a rewrite - #112272

Closed
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-chain-to-in-value-equivalence
Closed

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-chain-to-in-value-equivalence

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixes wrong results and a spurious TOO_LARGE_STRING_SIZE error when a chain of comparisons is rewritten into IN/NOT IN, or a two-term AND is folded, using a constant whose converted value does not compare the same way equals does. Affected constants include a float 0.0/-0.0 or NaN, a FixedString compared against a String column, an Enum compared against a String/FixedString column, a Variant/Dynamic/JSON constant, a string wider than a FixedString(N) column, and a constant that has no common type with a string column at all. A comparison over a JSON column, and one between a string column and such a constant, that the rewrites previously answered silently now correctly report NO_COMMON_TYPE.

Description

LogicalExpressionOptimizerPass rewrites x = c1 OR x = c2 OR x = c3 into x IN (c1, c2, c3) (tryReplaceOrEqualsChainWithIn), the notEquals counterpart into x NOT IN (...) (convertNotEqualsChainToNotIn), and folds a two-term AND in addComparisonFilter. All three consume the constant converted into the expression's type through tryConvertToColumnType, whose contract is only "does this convert losslessly?".

That is weaker than what the three consumers actually need, which is "is the converted Field a faithful semantic point for this type - does exact equality on it agree with what equals computes?". in builds a Set keyed on the converted value and matches it exactly (SetUtils.cpp -> convertFieldToType with strict), while the comparison it replaces is evaluated semantically in the wider of the two types; compareComparisonFilters and canonicalizeNotEqualsKey likewise treat the converted value as an exact point. Everywhere the two disagree, an optimization changes the answer - and in one case it makes a working query fail, because inserting the converted value into the set's column can throw.

Eleven divergence classes, all measured at default settings (both chain-length settings default to 3), one mechanism:

  • Float +0.0/-0.0. equals compares with accurateEquals where -0.0 == 0.0, while the set is keyed on the exact IEEE value: SELECT -0.0 = 0.0, -0.0 IN (0.0) is 1, 0. A chain over a column holding -0.0 loses that row.
  • Float NaN. No comparison matches a NaN, but nan IN (nan) is 1, so the chain gains a row.
  • FixedString padding against a String target. ColumnFixedString::operator[] yields all N bytes including the '\0' padding, so the set holds 'ab\0\0\0' while the column holds 'ab'. A full-width constant is unsound too, because zero-padded comparison also matches the value with trailing NULs.
  • A converted string wider than a FixedString(M) target. ColumnFixedString::insert throws TOO_LARGE_STRING_SIZE, so a query that answers correctly without the rewrite fails with it. Reachable from a FixedString(N > M) source and from a plain String source of size S > M alike.
  • Enum against a string-family target. equals casts both operands to the enum's label, while convertFieldToType stringifies the enum's raw integer, so the set key for 'a'::Enum8('a' = 1) against a String column is '1'.
  • A Variant expression. equals runs independently per active alternative; the set holds one discriminator-bearing key, and a constant Field carries no discriminator at all.
  • A Variant/Dynamic constant. ColumnVariant::operator[] and ColumnDynamic::operator[] return the bare underlying Field while FunctionVariantAdaptor/FunctionDynamicAdaptor compare using the active alternative's real type, so a source-type check sees only Variant and permits the rewrite. One shape additionally failed with TYPE_MISMATCH.
  • A nested NaN in the AND fold. The existing bail-out there inspects only a top-level Float64 Field, so Tuple(Float64) slips past it.
  • Distinct NaN payloads below an Array/Map. Container equality treats any two NaNs as equal, while a compound set key hashes the nested float's raw bytes.
  • A dynamic-structure expression in the fold. Both IN builders already decline these; the fold does not, and it answered 0 for a comparison over a JSON column whose own terms legitimately raise NO_COMMON_TYPE.
  • A constant with no common type with a string-family expression. equals on a string-family operand is accepted at analysis time but is only executable when the const-string path can cast the constant, which needs the constant to be the string side. So a String column against e.g. an Int64 constant, or against a multi-element Tuple or an Array constant, legitimately raises NO_COMMON_TYPE while the converted value round-trips, and all three rewrites answered instead - and a contradiction on an unrelated column could collapse the whole AND and drop the throwing operand entirely.

The fix adds one shared predicate next to tryConvertToColumnType - the function whose contract it strengthens - and calls it from all three consumers, keeping the genuinely set-specific checks in the two IN builders. The string-family rule is modelled on the equivalent guard in KeyCondition, which declines index analysis for the same padding reasons and with the same M >= N exemption.

The NaN check has a deliberate per-consumer depth. The fold compares two Fields with each other, so below an Array/Map boundary both sides go through the same compareAt, which treats any two NaNs as equal - the semantics already match and recursing deeper would only lose valid folds. A set instead matches a Field's hash against a column's raw bytes, so the deeper check is required there. Symmetrically, the float-zero rule is set-specific only: addComparisonFilter compares with accurateEquals, under which +0.0 == -0.0, so it already folds those cases correctly and sharing the rule would delete a correct fold.

The no-common-type rule is instead type-based and gated on the target, because the divergence is directional: the reverse pairing - a string-family constant against another type - is cast by the const-string path and stays rewritable, which is why Date, UUID, FixedString and Enum expressions with string constants must keep firing and are asserted to. It is also placed before conversion, so the parked filter carries no converted value and the global contradiction fold can veto the collapse. The rule covers composite (Tuple/Array/Map) constants as well: a multi-element tuple(...) or an Array against a string-family expression survives analysis, then raises NO_COMMON_TYPE from executeGeneric, and all three rewrites answered it instead. Only the spellings whose String rendering does not parse back - a single-element tuple(...) and a Map - were already declined by the round-trip guard. Both directions are asserted in the test.

The rules are value-based wherever the divergence is value-based, so the optimization keeps firing everywhere the converted value really is a semantic point: float constants that are neither zero nor NaN at any width or across widths, inf/-inf, columns containing -0.0/NaN when no constant is, FixedString(N) against a wider-or-equal FixedString(M), a String constant of size S <= M including one with a trailing NUL, an Enum expression with label or integer constants, Decimal scale pairs, Date with string constants, UUID, mixed integer widths, and LowCardinality columns. A blanket type-level exclusion of floats would silently disable all of those.

Disclosed trade-offs, each measured:

  • A Variant- or Dynamic-typed constant no longer participates, including the cases that agree today. A nested such constant can carry a different active alternative per element, so there is no single alternative to resolve from the constant; resolving one would be right for a scalar and silently wrong for a nested one.
  • The string-family rules are broader than the minimum needed for the reported symptoms: a full-width FixedString constant against a String column is also declined, and the size rule is keyed on the converted value's size rather than on the source type, so a plain String source is covered too.
  • Queries whose chain or fold is now correctly declined lose that optimization. Correct results beat the rewrite.

One reference line of another PR's test changes

04628_logical_optimizer_in_rewrite_variant_type.reference line 23 moves from 1 to 0. That test belongs to #111924 (@groeneai, merged), whose guard keeps the IN rewrite from changing a node's result type when a Variant expression is compared under the variant adaptor. Its comment read "the guard must key on the drift and not on the type", and that is still true of that guard: this change does not touch it, its setting = 0 line above is unchanged at 0, and with use_variant_default_implementation_for_comparisons = 1 the type drift really is gone so it no longer skips. What changed is that the chain is now declined one step earlier, by the converted-constant check, because a constant Field carries no discriminator and therefore cannot be a semantic point for a Variant expression. The comment is rewritten to say exactly that.

The shape that line asserted is not intrinsically safe either - its fixture is Variant(UInt256) with '1'/'2'/'3' constants, which happen to parse exactly; change only the constant and the same fixture diverges.

Two narrowings were considered and both are measurably unsound

The obvious objection is that a Variant with exactly one alternative has nothing to depend on per row, so the decline should apply only to multi-alternative Variants. Six single-alternative carriers say otherwise, all at default settings - for a Variant target the shared semantic-point rule matches none of its string-family, Tuple, Array or Map branches and falls through to accepting the constant, so every divergence above is live with one alternative:

single-alternative shape before ground truth
Variant(String) expression, toFixedString('ab', 5)-family constants 0 3
Variant(String) expression, Enum8 label constants 0 3
Tuple(Variant(String)) expression, tuple(toFixedString(...)) constants 0 2
Variant(FixedString(3)) expression, 'abcde' constants NOT_IMPLEMENTED 0
Variant(Tuple(Variant(Float64, UInt64))) expression, tuple(1)-family constants ILLEGAL_TYPE_OF_ARGUMENT 3
Variant(DateTime64(1, 'UTC')) expression, same-scale DateTime64(1, 'UTC') constants ILLEGAL_COLUMN 3

The second narrowing - unwrap the sole alternative and re-apply the existing leaf checks to it - fixes the first five and still fails the last. With constants of the identical type nothing is converted: tryConvertToColumnType returns at its equal-types fast path, the value round-trips trivially, and every leaf check passes. The failure is a property of the wrapper, not of the constant: the set column for a Variant expression is built nullable and ColumnNullable refuses a ColumnVariant nested column unconditionally. So no value-level or leaf-level predicate can be sound here, and the decline keys on the type.

The cost of that is three measured rewrites that are correct today and are now forgone - Variant(Float32) against Float64 constants, Variant(Enum8) against String labels, and Variant(UInt256) against Int64 - versus six carriers, three of which are silent wrong results and three of which are query failures. All three are asserted in the test with their results and with the rewrite not firing, so the trade is visible rather than implicit.

The dynamic-structure expression guard is not redundant with the constant-side check

The two rules leave different state behind, which is why both are needed. The expression guard in addComparisonFilter parks the filter before conversion, so its converted value is empty; the constant-side rule runs after conversion succeeded and parks a populated one. The global contradiction fold may only collapse an AND to false when no parked filter is missing its converted value, so only the expression guard can veto it - which is what keeps the query's own NO_COMMON_TYPE visible when a contradiction on an unrelated column would otherwise have collapsed the whole AND and dropped the throwing term. Without it, such a query's success would depend on optimize_redundant_comparisons. Measured on i Int32, c JSON(x String): (i = 1) AND (i = 2) AND (c != '{"x":1}'::JSON(x Int64)) answered 0 before and raises NO_COMMON_TYPE now. The guard keys on the expression type rather than on the individual comparison, because to be able to veto at all it has to park before conversion with no converted value; so a safe comparison over the same JSON column is vetoed too and that AND is retained as well. Results are unchanged either way, the cost is a forgone fold, and the same contradiction without a dynamic-structure term still folds. The two-expression row, the safe row's result and both plan shapes are asserted; the single-expression JSON fold row is closed by the same guard.

Recursion depth

The three constant walkers, both recursive type walks and the forEachChild callback call checkStackSize() at each composite recursion boundary, following FieldVisitorHash, which places it on its Tuple/Map/Array/Object operators and on none of its scalar ones. The callback needs it for the same reason as the rest: every forEachChild implementation invokes the callback from inside its own recursive frame, so the callback observes the accumulated nesting depth rather than a constant one. The walkers need it because tryConvertToColumnType returns immediately for equal types, so a nested same-type constant can reach them without having passed the check convertFieldToType performs. This is hardening, not a fix for an observed failure: a deeply nested constant already fails with a controlled TOO_DEEP_RECURSION from an earlier pass at the same depth with and without these walkers, and at default settings max_ast_depth rejects the shape long before that. IDataType::hasDynamicStructure() itself is left alone - it recurses unguarded, and it is called from 16 places outside its own overrides across 10 files, including two pre-existing ones in this pass, so guarding it belongs in IDataType and benefits all of them.

Not addressed here, knowingly: tryConvertToColumnType's round-trip check is top-level only, because convertFieldToType passes no source-type hint when recursing into Array/Tuple/Map elements, so a nested lossy leaf conversion escapes it. That belongs in convertFieldToType and is already being fixed there by #111399. Only its Variant-source form is closed here, since that PR does not touch the Variant branch.

Also left alone deliberately: both builders bypass the chain-length gate for a LowCardinality expression, so on such a column no setting turns the rewrite off. That is a separate optimization decision and only amplified the severity; this change makes those cases correct regardless of chain length, because the guard runs per constant on every rewrite attempt.

New test 04632_logical_optimizer_chain_to_in_value_equivalence asserts every affected shape against ground truth computed as one subquery column per comparison, so no equals-chain pattern is left for the pass to rewrite. It also asserts, via EXPLAIN QUERY TREE, that the optimization still fires on every shape where the converted value is a semantic point - that half is what a too-broad guard would break.

groeneai and others added 7 commits July 27, 2026 15:34
…a comparison chain

`LogicalExpressionOptimizerPass` rewrites `x = c1 OR x = c2 OR x = c3` into
`x IN (c1, c2, c3)` (and the `notEquals` counterpart into `NOT IN`), and folds a
2-term AND in `addComparisonFilter`. All three consume the constant converted
into the expression's type via `tryConvertToColumnType`, which only answers
"does this convert losslessly?".

That is weaker than what the consumers need. `in` builds a `Set` keyed on the
converted value and matches it EXACTLY, while `equals` compares semantically in
the widened type; `compareComparisonFilters` likewise treats the converted value
as an exact semantic point. Where the two disagree, the rewrite changes results
or fails the query outright:

- a float `+0.0`/`-0.0` constant is one class for `accurateEquals` but two
  distinct set keys, and a NaN matches no comparison while the set keys on its
  raw payload;
- a `FixedString` constant against a `String` target carries its '\0' padding
  into the set, while comparison is zero-padded;
- an `Enum` constant against a string-family target compares as its LABEL but
  converts to its stringified raw integer;
- a `Variant`/`Dynamic`/`JSON` constant is a bare `Field` with no discriminator,
  while the variant and dynamic adaptors compare using the active alternative's
  real type;
- a converted string wider than a `FixedString(M)` target cannot be inserted at
  all, so a working query fails with `TOO_LARGE_STRING_SIZE`.

Add one shared predicate beside `tryConvertToColumnType` and call it from all
three consumers, keeping the genuinely set-specific checks in the two `IN`
builders. The string-family rule is modelled on the equivalent guard in
`KeyCondition`, which declines index analysis for the same padding reasons and
with the same `M >= N` exemption. The NaN check has a per-consumer depth: the
fold compares two `Field`s through the same `compareAt`, so container NaN
semantics match below an `Array`/`Map` and it stops there, whereas a set matches
a hash against a column's raw bytes and must recurse.

The rules are value-based rather than type-based wherever the divergence is
value-based, so chains over floats that are neither zero nor NaN, cross-width
float constants, `inf`, `FixedString(N)` against a wider `FixedString(M)` and an
`Enum` expression with label or integer constants all keep being rewritten.

Co-Authored-By: Claude Fable 5 <[email protected]>
…iant decline

Add `checkStackSize()` to the composite branches of the three new `Field` walkers
and of the expression-type walk, mirroring `FieldVisitorHash`, which places it on
its `Tuple`/`Map`/`Array`/`Object` operators and on none of the scalar ones. The
walkers need it because `tryConvertToColumnType` returns immediately for equal
types, so a nested same-type constant reaches them without having passed the
check `convertFieldToType` performs. The type walk needs one too, since
`IDataType::forEachChild` recurses on its own.

`hasDynamicStructure()` and the `Variant` type walk are transitive scans of the
whole remaining subtree, and they were being re-run at every recursion level, so
a depth-N constant cost O(N^2) type-tree scans. Hoist that source-wide rejection
into a thin wrapper that runs once per constant.

Cover the single-alternative `Variant` expression, which was pinned by nothing.
The alternative count is not what makes such an expression unsafe: for a
`Variant` target the shared semantic-point rule matches none of its
string-family, `Tuple`, `Array` or `Map` branches and falls through, so the
divergence is live with exactly one alternative. Three of the new rows are
silent wrong results and three are working queries the rewrite turns into
`NOT_IMPLEMENTED`, `ILLEGAL_TYPE_OF_ARGUMENT` and `ILLEGAL_COLUMN`; the last one
uses constants of the identical type, so nothing is converted, every value-level
check passes, and the failure comes from the set column for a `Variant`
expression being built nullable while `ColumnNullable` refuses a `ColumnVariant`.
That is why the decline keys on the type. The three measured rewrites it forgoes
are correct today and are asserted as such, so the cost is visible.

Pin the dynamic-structure expression guard with the two-expression shape it
actually protects: a contradiction on another column reaches the global fold,
which may only collapse the whole `AND` when no parked filter is opaque, so
leaving the converted value empty is what keeps the query's own failure visible
instead of making it depend on `optimize_redundant_comparisons`.

One reference line of `04628_logical_optimizer_in_rewrite_variant_type` moves
from 1 to 0. Its result-type guard, added in ClickHouse#111924, still keys on the drift
rather than on the type and its `setting = 0` line is unchanged; the chain is now
declined by the separate converted-constant check instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment-only. Three of the doc-comment lines added by this branch used the
em-dash character, which is not allowed in our contributions, code comments
included. A colon and two commas carry the same meaning.

The rest of the file keeps the em-dashes it already had, since those lines are
not touched by this branch.

Co-Authored-By: Claude Fable 5 <[email protected]>
…esult

The row that was meant to bound the veto's breadth asserted only a count that is
false at runtime regardless of whether the AND collapsed, so it could not detect
the thing it existed to bound, and the comment beside it claimed the opposite of
what happens.

The guard has to park a dynamic-structure comparison before conversion, with no
converted value, or it cannot veto the global contradiction fold at all. It
therefore keys on the expression type, so a safe comparison over the same JSON
column is vetoed too and that AND is retained as well. Results are unchanged
either way; the cost is a forgone fold.

Measure it instead: keep the result assertion and add two EXPLAIN QUERY TREE rows
that pin the plan shape - the safe JSON comparison is vetoed (0), while the same
contradiction without a dynamic-structure term still folds (1). Deleting the
guard flips the first row to 1, which is what makes the pair a live control.

No source change.
`equals`/`notEquals` on a string-family operand is accepted at analysis time
("Everything can be compared with string by conversion") but is only executable
when the const-string path can cast the constant, which needs the CONSTANT to be
the string side. With a string-family expression and a constant outside
{String, FixedString, Enum} nothing rescues it and the comparison raises
NO_COMMON_TYPE - yet the constant still converts losslessly into a semantic
point, so all three rewrites (OR chain -> IN, notEquals chain -> NOT IN, and the
two-term AND fold) answered a query that legitimately fails. Worse, a
contradiction on an unrelated expression could collapse the whole AND and drop
the throwing operand entirely, making the answer depend on
optimize_redundant_comparisons.

The new predicate is type-only and gated on the TARGET, because the divergence is
directional: the reverse pairing, a string-family constant against another type,
is cast by the const-string path and must keep firing (Date, UUID, FixedString
and Enum expressions with string constants). A symmetric supertype test cannot
express that asymmetry and breaks those rows - measured.

In addComparisonFilter the check runs BEFORE tryConvertToColumnType, so the
parked filter carries no converted value and the global contradiction fold veto
can see it. Placing it after conversion leaves that carrier open, because the
veto only refuses to collapse when it finds a parked filter with no converted
value.

A composite source against a string-family target is deliberately not gated: it
takes a dedicated engine path and was measured inert, already rejected at
analysis time even as a single comparison with no chain to rewrite.
A composite constant against a string-family expression was exempted from the
no-common-type decline on the belief that such a comparison never reaches the
rewrites. That is only true of the spellings whose String rendering does not
parse back: tryConvertToColumnType renders the constant into the String target
via FieldVisitorToString and requires it to convert back, and while tuple(1)
renders as "tuple(1)" and a Map as "[('a',1)]" (neither reparses), a
multi-element tuple renders as "(1,2)" and an Array as "[1]", both of which do.
Those survived the guard, reached the exemption, and were rewritten -- returning
0 or ILLEGAL_TYPE_OF_ARGUMENT for a comparison that executeGeneric legitimately
answers with NO_COMMON_TYPE, in all three consumers and in the global
contradiction fold.

Drop the exemption so the branch is just the supertype test. All 24 must-fire
rows use scalar constants and reach tryGetLeastSupertype with the same pair as
before, so no firing case changes; the test's reference gains exactly one line.

The test's composite block is replaced with live coverage of every consumer on
multi-element Tuple and Array constants, plus the global-contradiction veto
asserted on the plan, and keeps the two non-reparsing spellings with the
measured reason they were already inert.

Also drop a checkStackSize() that sat at constant stack depth: the recursion in
that walk happens inside IDataType::forEachChild, which recurses internally and
unguarded, so the call could not observe the condition its placement implied.
The previous commit removed checkStackSize() from the callback in
hasVariantTypeRecursively on the reading that the callback runs at a constant
stack depth. That reading was wrong.

Every forEachChild implementation invokes the callback from inside its own
recursive frame: DataTypeTuple::forEachChild calls callback(*elem) and then
elem->forEachChild(callback), so the nested call reaches the callback one frame
deeper, and DataTypeArray, DataTypeMap, DataTypeVariant, DataTypeObject,
DataTypeNullable and DataTypeLowCardinality all have the same shape. A model of
that walk measures the callback's frame offset growing monotonically with
nesting depth (about 40 bytes per level at -O2, 80 at -O0), so the check
observes the accumulated depth and belongs where it was.

This is hardening only, not a live failure. The depth sweep answers 1 at
nesting depth 1300 and raises TOO_DEEP_RECURSION at 1600 both with and without
the check, because an earlier pass reaches its own limit first. Restoring it
keeps this walk consistent with the other new recursive walks in the file, all
of which carry the same check.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (7 review rounds, 6 independent gate rounds, 46 findings raised, 49 verdicts recorded)

Before opening this PR I reviewed the change myself, cold, and then had an independent model
re-review it against the frozen PR description. Rounds continued until both were clean. Below is
every finding and what I did with it. Nothing is hidden; where I disagreed I say why, with the
measurement.

Totals, derived by script from the per-round ledgers rather than from prose: 7 own-review
rounds raising 41 findings (2 blocker, 5 major, 34 nit), and 6 independent gate rounds raising 5
findings (2 blocker, 3 major). Those 46 findings produced 49 recorded verdicts across the round
ledgers: 21 AGREE, 8 DISAGREE with recorded evidence, 20 dropped as superseded by a later round's
rework. Six implementation rounds and one replan round followed. The final round found 0 gate
findings, and its only two findings of mine were in the PR text rather than the code.

❌ Blockers, both agreed and both fixed

# Finding Verdict and what changed
1 The no-common-type rule was missing entirely: a String column compared against e.g. an Int64, or a multi-element Tuple/Array, legitimately raises NO_COMMON_TYPE, and all three rewrites answered it instead. Worse, a contradiction on an unrelated column could collapse the whole AND and drop the throwing operand. AGREE. Added comparisonTypesHaveCommonType, gated on the target and placed before conversion so the parked filter carries no converted value and the global contradiction fold can veto the collapse. Six carrier rows plus the plan-level veto assertion added, each proven live against a mutant that neuters the leaf decline.
2 The rule exempted composite sources, so a multi-element tuple(...) or an Array constant against a string-family column still slipped through. AGREE. Exemption deleted; the string-family branch is now a plain supertype test. Nine further carrier rows added, all nine measured wrong before and correct after, with a mutant restoring the exemption reproducing the pre-fix column exactly.

⚠️ Majors

# Finding Verdict and what changed
3 The dynamic-structure guard was asserted only on the query's result, not on the plan, so a guard that fired for the wrong reason would still have looked green. AGREE. Assertion moved to the plan shape via EXPLAIN QUERY TREE, with the safe control and the plain-contradiction control beside it.
4 Em-dashes in the new comments. AGREE. Replaced with plain ASCII throughout the diff, the description and all six commit messages.
5 One commit removed a checkStackSize() from the Variant walk's callback and justified it, in an in-tree comment and in the commit message, with "the callback runs at a constant stack depth". AGREE, and the false premise was mine. It is wrong: every forEachChild implementation calls callback(*child) and then child->forEachChild(callback), so the nested invocation reaches the callback one frame deeper and a check inside it observes the type's accumulated nesting depth. Verified on all seven implementations in the tree. The guard is restored and the comment now states only what is true. This is hardening, not a live failure: the depth sweep answers 1 at nesting depth 1300 and raises TOO_DEEP_RECURSION at 1600 both with and without it, because an earlier pass reaches its own limit first.
6 The description said IDataType::hasDynamicStructure() "recurses unguarded at 46 call sites". AGREE. The figure was a grep artifact: 46 is the count of lines containing the token, and 22 of those are override declarations. Measured properly, there are 30 invocation lines, 14 of which are the recursive self-call inside the type's own override, leaving 16 external call sites across 10 files. Corrected in the description. The scope argument it supports is unaffected.
7 The test census published alongside this PR was stale: it was computed before the two no-common-type rounds added rows. AGREE. Re-derived by script from the shipped file: 122 assertions over 42 fixtures, of which 57 print a result beside ground truth, 37 assert plan shape, 9 are single-value folds and 19 are NO_COMMON_TYPE expectations, and 10 + 37 + 57 + 9 = 113 = the reference's line count exactly. Corrected.

💡 Alternatives raised and declined, and design questions settled by measurement

Rows 8, 9, 12 and 13 are proposals raised during review that I declined; rows 10 and 11 are asymmetries
in the shipped design that look like oversights on a first read, recorded here with the measurement
that makes each deliberate.

# Proposal or apparent asymmetry Why it stands as shipped
8 Make the float rule type-level (reject float constants outright) instead of value-based. The divergence is a property of the value, not the type: only +0.0/-0.0 and NaN diverge. A type-level exclusion would silently stop the optimization firing for every ordinary float constant, at any width and across widths, and for inf/-inf. Both halves are asserted: the diverging values are declined and the ordinary ones are asserted to keep firing.
9 Reuse the has() guard in HasToInPass instead of adding a predicate. It answers a different question. FunctionArrayIndex compares raw elements with no conversion, so has(['a'], enum_col) is 0 while enum_col = 'a' and enum_col IN ('a') are both 1. Its type-equality clause is load-bearing there and over-broad here; sharing one implementation would force one caller to be wrong.
10 The float-zero rule is wired into the two IN builders but not into the two-term AND fold. Deliberate. The fold compares with accurateEquals, under which +0.0 == -0.0, so it already folds those cases correctly; sharing the rule would delete a correct fold. The zero-fold rows are asserted to answer identically before and after.
11 The NaN check runs at a different depth per consumer, which reads like an inconsistency. Deliberate, and both directions are measured. The fold compares two Fields through the same compareAt, which treats any two NaNs as equal, so below an Array/Map boundary the semantics already match and recursing deeper would only lose valid folds. A set instead matches a Field's hash against a column's raw bytes, so two different NaN payloads disagree there and the deeper walk is required.
12 Guard IDataType::hasDynamicStructure() itself. Wrong layer and wrong PR: it is called from 16 places outside its own overrides, two of them pre-existing in this pass, so the guard belongs in IDataType where all of them benefit.
13 Fix tryConvertToColumnType's top-level-only round-trip check. Already being fixed at the right layer by #111399, which is open. Only its Variant-source form, which that PR does not touch, is closed here.

Also disclosed in the description rather than silently accepted

A Variant- or Dynamic-typed constant no longer participates even where it would agree today,
because a nested such constant can carry a different active alternative per element and resolving one
would be right for a scalar and silently wrong for a nested one. The string-family rules are broader
than the reported symptoms strictly require. Queries whose chain or fold is now correctly declined
lose that optimization. One reference line of another PR's test moves, for the reason given in the
description, and that test's own guard and its setting = 0 line are untouched.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Answer
a Deterministic repro? Yes. clickhouse local -n --queries-file tests/queries/0_stateless/04632_logical_optimizer_chain_to_in_value_equivalence.sql on an unfixed build produces 44 value-mismatch rows and aborts with Code 131 TOO_LARGE_STRING_SIZE, with both of the serverError NO_COMMON_TYPE rows that existed at that point reporting that the query succeeded where the error was expected; on the fixed build every row equals ground truth and it exits 0. The 17 further serverError rows added later split into 15 proven load-bearing against a mutant that neuters the specific rule they pin (six against a neutered leaf decline, nine against a restored composite-source exemption, each failing with "The query succeeded but the server error '386' was expected") and 2 that were already declined before this change by tryConvertToColumnType's round-trip guard - the single-element tuple(...) and the Map spellings, whose String rendering does not parse back. Those two are kept deliberately, each with an in-test comment recording that measured fact, so the third composite kind stays covered and the distinction is documented as being about the rendering rather than about the constant being composite. No randomization, no timing, no server needed - the divergence is a property of the constant, so it is deterministic and build-type independent (also measured on a release binary).
b Root cause explained? Yes. tryConvertToColumnType answers only "does this constant convert losslessly?", while all three of its consumers treat the converted Field as an exact semantic point: in/notIn key a Set on it and match exactly, and compareComparisonFilters/canonicalizeNotEqualsKey order it directly. The comparison being replaced is instead evaluated semantically in the wider of the two types. Eleven measured divergence classes follow from that one gap - float +0.0/-0.0 and NaN, FixedString padding against a String target, an oversized converted string against FixedString(M) (which throws on set insertion), Enum label vs stringified raw integer, a Variant expression's per-alternative execution, a Variant/Dynamic constant hiding its active alternative behind a bare Field, a nested NaN in the fold, distinct NaN payloads below an Array/Map, a dynamic-structure expression in the fold masking a real NO_COMMON_TYPE, and a constant with no common type with a string-family expression, where equals is only executable when the const-string path can cast the constant (so it needs the constant to be the string side) yet the converted value round-trips and all three rewrites answered instead. The Variant class holds with a single alternative too: for a Variant target the shared semantic-point rule matches none of its string-family, Tuple, Array or Map branches and falls through, so six single-alternative carriers are live at default settings - three silent wrong results and three working queries turned into NOT_IMPLEMENTED, ILLEGAL_TYPE_OF_ARGUMENT and ILLEGAL_COLUMN.
c Fix matches the root cause? Yes. It adds the missing precondition at the layer that produces the value - one shared predicate beside tryConvertToColumnType, called from all three consumers - rather than guarding the crash site or weakening a test. in, equals and Set all keep their documented, user-visible contracts and none is modified: -0.0 IN (0.0) being 0 and nan IN (nan) being 1 are IN's semantics by design, so changing them would be the wrong layer with a product-wide blast radius. The set-specific residue stays in the IN builders.
d Test intent preserved / new tests added? Yes. New test 04632_logical_optimizer_chain_to_in_value_equivalence - 122 assertions over 42 fixtures: 57 print a result beside ground truth computed as one subquery column per comparison, 37 assert plan shape via EXPLAIN QUERY TREE, 9 are single-value fold assertions and 19 are serverError NO_COMMON_TYPE expectations. The 113-line reference is the 57 + 37 + 9 output-producing rows plus 10 section headers; the 19 error expectations produce no stdout. One reference line of another PR's test does change: 04628_logical_optimizer_in_rewrite_variant_type.reference line 23 moves 1 -> 0, because the same Variant-expression chain is now declined one step earlier by the converted-constant check. That test's own result-type guard (from #111924) is untouched and still keys on the type drift, its setting = 0 line is unchanged, and its comment is rewritten to say so; nothing else in the file moves (verified by diffing the raw output against the old reference - exactly one changed line). Two of my own rows were found vacuous while auditing the generated reference (an Enum-label chain over a FixedString fixture matched zero rows) and were re-fixtured rather than left in.
e Demonstrated in BOTH directions? Yes. Pristine origin/master snapshot: 44 mismatch rows, both serverError rows unmet, rc=131, runner verdict FAIL. Fixed: 0 mismatches, rc=0, verdict OK. The three query-failure carriers were additionally measured per-carrier on the pristine build (Code 48 / Code 43 / Code 44), since the Code 131 aborts the file before them. Every one of the eleven symptom classes was measured before the fix at the exact values recorded during planning and after it at ground truth. Backed by a 25-mutation matrix with predictions written before any mutant was built: 21 of 22 detected as predicted in the first round, and 3 further mutations covering the two rejected narrowings and the constant-side dynamic rule, all 3 detected - including the one that shows the alternative narrowing recovers five of the six single-alternative carriers and still fails the sixth. Two further mutations cover the no-common-type rule: neutering its leaf decline turns all six new serverError rows into answers and flips the global-suppression plan row to the collapsed UInt64_0 shape while leaving the 15 must-not-break rows untouched (BROKEN_COUNT 0), and dropping its target gate for a symmetric supertype test breaks exactly the two rows the asymmetry protects (date string const and uuid string const, BROKEN_COUNT 2). A further mutation restoring a composite-source exemption inside that rule turns all nine composite rows back into wrong answers (43 for the two IN builders, 0 for the fold and for the global contradiction, whose plan row returns to the collapsed UInt64_0 shape) while leaving every must-fire row untouched. Mutant Build IDs 786c6496eaf8c821 and a00bf99f4f456299; after each restore the source md5 returned to b0ce84f5c2ce6a77 with zero mutation markers and the rebuild produced the bit-identical Build ID 6e149870350fa23a, matched by the running server's buildId(). The source was restored byte-identically after every mutant (md5 unchanged, zero mutation markers) and each rebuild returned the bit-identical Build ID 6790e70c2e16b074, which the running server's buildId() matched.
f General across code paths? Yes. The carriers were enumerated mechanically as every consumer of tryConvertToColumnType - addComparisonFilter, convertNotEqualsChainToNotIn, tryReplaceOrEqualsChainWithIn - and all three are fixed; two separate mutations disable the guard in each IN builder alone and each fails only that builder's rows, which is the sibling-gap proof. The fourth rewrite of the same family, RewriteHasToInVisitor, is already guarded and deliberately untouched: has() compares raw array elements with no conversion, so has(['a'], enum_col) is 0 while enum_col = 'a' is 1 (measured) - its type-equality clause is load-bearing there and would be over-broad here, so sharing one implementation would force one caller to be wrong. The no-common-type rule is wired at the same three sites, with one placement difference that is load-bearing: in the fold it runs BEFORE tryConvertToColumnType, so the parked filter carries no converted value and the global contradiction fold can veto the collapse (a mutation moving the decline after conversion leaves that row answering 0).
g Generalizes across inputs? Yes. The guards recurse through Nullable/LowCardinality/Array/Tuple/Map, on the constant's wrappers as well as the expression's; a mutation that makes them top-level-only fails exactly the nested rows. Two rules stop at an Array/Map boundary for measured reasons, and mutations in both directions pin that depth. Covered: bare/Nullable/LowCardinality/Array/Array(Array)/Tuple/named Tuple/Map(K,V)/Map(V,K) expressions; Float64, Float32 and cross-width constants; a UInt8 0 and a String 'nan' constant, neither of which is float-typed at all yet both convert into the diverging values; padded and full-width FixedString; the S <= M and S > M size boundaries; a NUL-bearing string constant; distinct NaN bit payloads built with reinterpret. The no-common-type rule recurses the same way and is asserted on a String expression, a FixedString(3) expression, a LowCardinality(String) expression and a Tuple(String) leaf. Composite constants are gated too, with all three consumers asserted on multi-element Tuple and Array constants, each measured wrong before the fix (43 for the two IN builders, 0 for the fold) and NO_COMMON_TYPE after; the two renderings that do not parse back (a single-element tuple(...), a Map) are kept as rows documenting that the round-trip guard had already declined them.
h Backward compatible? Yes. No setting added and no default changed, no serialization, format or protocol change, so no SettingsChangesHistory.cpp entry is required (confirmed by git grep). The change is analyzer-only. User-visible effects are exactly: corrected results, one spurious query failure removed (TOO_LARGE_STRING_SIZE), one previously-masked error now surfacing (NO_COMMON_TYPE on a dynamic-structure fold, where the un-folded query raises the same error), and some chains and two-term ANDs no longer being rewritten.
i Invariants and contracts preserved? Yes. The additions are pure predicates over (Field, DataTypePtr) - no mutation, no allocation, no new control flow: each rejection routes the filter through the opaque_filters / or_operands / output escape the code already had for a failed conversion. Every recursion checks the Field's discriminant before safeGet and fails closed (reports "not a semantic point") on any unrecognised Field/type pairing, so a shape it does not understand forgoes an optimization instead of throwing. A NULL-valued constant cannot reach the OR guard (excluded upstream) and the AND builder's equivalent nullable bail-out was confirmed rather than assumed. The pre-existing top-level NaN bail-out and the integer boundary-folding path are left in place, so neither becomes dead. Each composite recursion boundary of the four self-recursing value walkers calls checkStackSize(), following FieldVisitorHash, which places it on its Tuple/Map/Array/Object operators and on none of its scalar ones; the walkers need it because tryConvertToColumnType returns immediately for equal types, so a nested same-type constant can reach them without having passed the check convertFieldToType performs. The forEachChild callback carries the same call, because every forEachChild implementation invokes the callback from inside its own recursive frame (callback(*child) then child->forEachChild(callback)), so the callback observes the type's accumulated nesting depth rather than a constant one. Measured to be behaviour-neutral: a deeply nested constant hits the same controlled TOO_DEEP_RECURSION boundary at the same depth with and without the guards (works at 1300, raises at 1600, identical on both builds). The source-wide dynamic/Variant rejection was also hoisted out of the recursion, since re-running two transitive type-tree scans at every level was O(N^2) per constant.

Build ID: 6e149870350fa23a17277b3a0e030b996e3e0023
50/50 randomized runs of the new test: 50 passed, 0 failed.
Neighbour suite: 12 of 12 runnable neighbours pass, including 04628 after its one reference line was re-recorded.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @novikd - could you review this? LogicalExpressionOptimizerPass rewrites an equals chain into IN and folds a two-term AND using tryConvertToColumnType, whose contract is only "converts losslessly", while all three consumers need "the converted value is a semantic point that exact equality agrees with equals on"; the gap changes results for float 0.0/NaN, FixedString/Enum against a string column, Variant/Dynamic constants, and constants with no common type at all (one shape turns a working query into TOO_LARGE_STRING_SIZE, another silently answers a query that should raise NO_COMMON_TYPE).

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6b0e3c6]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

This PR hardens the OR -> IN, notEquals-chain -> NOT IN, and two-term AND fold rewrites around converted-constant semantics, and the added regression file covers the reported float, string-family, Dynamic/JSON, and NO_COMMON_TYPE cases. I still see one wrong-result gap in the touched fold path for plain Variant expressions, so the new "semantic point" contract is not yet true for all three consumers.

Findings

❌ Blockers

  • [src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp:1222] [dismissed by author -- https://github.com/Require a converted constant to be a semantic point for a rewrite #112272#discussion_r3665487847] addComparisonFilter still only opts out for hasDynamicStructure(). Plain Variant(...) targets continue into compareComparisonFilters / canonicalizeNotEqualsKey with bare Field values that have no discriminator, so under use_variant_default_implementation_for_comparisons = 0 a two-term AND over Variant(FixedString(...)) can still treat semantically-equal points as contradictory and change results. Suggested fix: add the same Variant expression opt-out here, or teach the fold-side semantic-point check to unwrap a Variant target safely before it uses the converted value as an exact point.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: close the remaining Variant-expression gap in addComparisonFilter, and add one focused regression row that exercises the two-term AND fold on a Variant(FixedString(...)) expression.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
/// not a comparable point: folding two such filters can answer a query that legitimately fails
/// (`NO_COMMON_TYPE`) when its terms are evaluated. Both `in`/`notIn` builders already decline
/// these; do the same here.
if (raw_type->hasDynamicStructure())

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.

The new opt-out here covers dynamic-structure expressions, but plain Variant(...) still falls through to compareComparisonFilters / canonicalizeNotEqualsKey, which compare the converted constants as raw Fields. That is only safe on the nullable default-implementation path, and tryOptimizeAndCompareNotEqualsChain already skips that path up front; under use_variant_default_implementation_for_comparisons = 0 the comparisons are non-nullable, so this code still runs on Variant expressions.

That leaves the two-term AND fold with the same semantic-point bug that expressionTypeIsSetSafe now fixes for IN: e.g. on Variant(String), two FixedString spellings of the same semantic string can still be treated as different (or even contradictory) points here even though both terms match the same row. I think addComparisonFilter needs a Variant expression opt-out equivalent to the IN builder before it starts using compareComparisonFilters on these constants.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed on the mechanism, on the reachability, and on the missing opt-out. Measured, and one detail of the worked example is different from what I found, which changes what the fix has to be.

Reachability is exactly as you describe. tryOptimizeAndCompareNotEqualsChain bails at LogicalExpressionOptimizerPass.cpp:2253 when the and node's result type is Nullable. At the default use_variant_default_implementation_for_comparisons = 1 a Variant comparison is Nullable(UInt8), so that bail-out fires; at 0 it is UInt8 and the fold runs. enable_pruning is optimize_redundant_comparisons, which defaults to 1, so nothing else gates it. And DataTypeVariant::hasDynamicStructure() reports only its alternatives' dynamic structure, so a plain Variant(...) does fall through the new opt-out at :1218 into compareComparisonFilters.

The carrier is the reverse direction of your example. With a Variant(String) expression, 'ab'::FixedString(2) and 'ab'::FixedString(4) do not both match the 'ab' row: against the String alternative the padded spelling matches nothing, so the two terms never match the same row and there is no divergence (oracle 0, keyed 0). The padded alternative has to be in the expression. On Variant(FixedString(4), UInt64) holding 'ab'::FixedString(4) and 7, with each comparison materialised as its own UInt8 subquery column as the oracle:

shape oracle keyed
v = 'ab'::FixedString(4) AND v = 'ab'::FixedString(2) 1 0
v = 'ab'::FixedString(4) AND v <= 'ab'::FixedString(2) 1 0
v = 'ab'::FixedString(4) AND v != 'ab'::FixedString(2) 0 1
single-alternative Variant(FixedString(4)), first shape 1 0
Tuple(Variant(FixedString(4), UInt64)), first shape 1 0

The third row diverges in the opposite direction, so it is not one-sided; the second shows it is not confined to equals/equals; the last two show the alternative count and one level of Tuple nesting are both irrelevant.

It is pre-existing, not introduced here. Every row above measures identically on the pre-change merge-base (9b24abd9, carrier file md5-identical to this PR's base) and on this PR's head, and a plain FixedString(4) expression with no Variant is correct on both (oracle 1, keyed 1), so it is specific to the Variant wrapper.

I am not folding it in, for two reasons. It is a distinct root cause from the converted-constant contract this PR strengthens, and this repository asks for one root cause per PR. More concretely, the remedy as stated would regress this PR: wiring expressionTypeIsSetSafe into addComparisonFilter rejects isVariant outright, which forgoes two folds that are correct today and that I measured firing here, a contradiction between two distinct String constants on Variant(String, UInt64) and a duplicate-constant prune on the same fixture. It also contradicts the deliberate control at 04632_logical_optimizer_chain_to_in_value_equivalence.sql:260, whose 0 exists to pin that no Variant rule was added to the fold. A blanket type-level reject is wider than needed anyway: at setting = 0 only string-family constants type-check against a Variant expression at all, a UInt64 constant and a bare integer literal both raise ILLEGAL_TYPE_OF_ARGUMENT, so the reachable surface is just the string-family alternatives.

The direction I want to evaluate instead is to let the shared semantic-point rule see through a Variant target and apply its existing string-family leaf checks to the alternative, rather than declining the wrapper by type. The PR body records why that is not available to the IN builders, the set column for a Variant expression is built nullable and ColumnNullable refuses a ColumnVariant; the fold has no set column, so that obstruction does not apply to it. That asymmetry is why it belongs in its own change.

I have opened a fix task for it with the matrix, the controls and that hazard recorded, and I will post the fixing PR link here when it opens.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The fixing PR is #113470.

One correction to what I wrote above. I said I wanted to evaluate letting the shared
semantic-point rule see through a Variant target and apply its string-family leaf checks
to the alternative, rather than declining by type. I measured that and it is not available:
ColumnVariant::compareAt orders discriminator-first, so on Variant(FixedString(4), UInt64)
every UInt64 row compares greater than any FixedString constant whatever its value. A
Field has nowhere to carry a discriminator, so no normalisation of the constant can make the
analyzer's order equal the runtime's, and the range cases stay wrong even once the equals cases
are repaired. That half is unfixable at the Field level, which is why the PR declines instead.

Two further shapes turned up while measuring, both of which rule out the narrower predicates
I had in mind. On Variant(FixedString(4), String) both constants match an alternative exactly
and the fold still diverges, so requiring an exact-alternative match is unsound. And the
transitive-derivation call site diverges independently, so the guard has to go in the shared
callee rather than at the chain scan.

So the cost you flagged is real and the PR accepts it: the folds on Variant(String, ...)
expressions that are correct today stop firing. Their results are unchanged, and the new test
pins each one as fired = 0 so a later narrowing of the guard cannot go unnoticed. The
04632 control at the line I cited is untouched.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 34be543

CI has fully finished on this head with no failures: 174 check-runs, all completed,
0 failures (Finish Workflow green), and CIDB records no FAIL or ERROR row for this
pull request. There is nothing to own.

Session id: cron:our-pr-ci-monitor:20260728-163000

…ue-equivalence

# Conflicts:
#	src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.80% 91.90% +0.10%
Branches 78.50% 78.60% +0.10%

Changed lines: Changed C/C++ lines covered: 176/184 (95.65%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6b0e3c6

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
Stress test (amd_debug) / Hung check failed, possible deadlock found not a deadlock: the server refuses every hung-check probe connection with Code: 241 (total) memory limit exceeded: would use 69.15 GiB ... current RSS: 6.86 GiB, maximum: 47.50 GiB. Untracked memory across all threads: -2.22 MiB, i.e. the memory tracker claims ten times the process's real resident size and reports negative untracked memory a fix task owns this at full effort, fixing-PR link to follow here

All 174 check-runs on this commit are completed and this is the only failing check.

Not caused by this PR. The diff is 5 files: LogicalExpressionOptimizerPass.cpp plus two stateless
test pairs, and an analyzer rewrite pass cannot change server-wide memory accounting. Read from the
hung_check.log artifact rather than the truncated CIDB row, the failure begins at
Connecting to ClickHouse server... before a single query runs, so nothing this PR changes is even
reachable. The label Hung check failed, possible deadlock found is a bucket name here, not a
diagnosis: clickhouse-test ends with Server is not responding. Cannot execute 'SELECT 1' query.

Breadth over 30 days for the accounting signature (Untracked memory across all threads: -):
817 rows across 218 distinct pull requests and 195 rows on master, spanning 19 different check
flavours, first seen 2026-07-10. A signature that fires on master 195 times is a trunk condition.

Session id: cron:our-pr-ci-monitor:20260730-230000

@vdimir vdimir left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This change is too bulky for this problem. We can either skip the optimization for floats, Dynamic, and FixedString, or simply document that this optimization uses strict comparison for some types.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed on scoping down. I will take the skip option and drop the general predicate.

Two notes before I cut it, both measured on master today (26.8.1.1).

The three families you named leave two wrong-results cases behind, same mechanism:

  • Enum constant against a String or FixedString column: the set is keyed on the enum's raw integer while equals compares the label. On a String column holding 'a','b','c','z', countIf(c = 'a'::Enum8('a' = 1, 'b' = 2, 'c' = 3) OR c = 'b'::Enum8(...) OR c = 'c'::Enum8(...)) returns 0 against a per-comparison ground truth of 3.
  • A Variant of static alternatives, for example Variant(FixedString(2), UInt64): 0 against 3 in the same shape. A Dynamic check does not catch it, because DataTypeVariant::hasDynamicStructure() only reports its alternatives' dynamic structure and so returns false here.

And one case is an error rather than a strict answer, so documenting it would not cover it: on FixedString(2), countIf(c = 'abc') returns 0, but countIf(c = 'abc' OR c = 'cde' OR c = 'efg') raises TOO_LARGE_STRING_SIZE. Skipping the FixedString family covers that one.

So the skip list I plan is floats, Dynamic, Variant, Enum against the string family, and FixedString. If you would rather have strictly the three you named, tell me and I will do exactly that.

@vdimir

vdimir commented Sep 7, 2026

Copy link
Copy Markdown
Member

@groeneai cut down patch as discussed above

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Understood. Dropping the general predicate and cutting this down to a type skip list in the rewrites: floats, Dynamic, Variant, FixedString, and Enum against the string family. I will push the reduced patch here.

@vdimir vdimir left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai this change is too bulky. Show small minimal repros for the issue we fixing in comment for later, maybe we will come up with better solution and close PR

@groeneai

Copy link
Copy Markdown
Collaborator Author

Minimal repros, default settings, current master:

-- 1. -0. = 0 is true, -0. IN (0) is false: 1, expected 2
SELECT count() FROM values('f Float64', -0., 1.) WHERE f = 0 OR f = 1 OR f = 2;
-- the NOT IN form: 1, expected 0
SELECT count() FROM values('f Float64', -0., 1.) WHERE f != 0 AND f != 1 AND f != 2;

-- 2. nan = nan is false, nan IN (nan) is true: 1, expected 0
SELECT count() FROM values('f Float64', nan) WHERE f = nan OR f = 1 OR f = 2;

-- 3. 'ab' = toFixedString('ab', 3) is true, the set holds 'ab\0': 0, expected 1
SELECT count() FROM values('s String', 'ab') WHERE s = toFixedString('ab', 3) OR s = toFixedString('cd', 3) OR s = toFixedString('ef', 3);

-- 4. s = 'abc' alone returns 0, the chain throws TOO_LARGE_STRING_SIZE
SELECT count() FROM values('s FixedString(2)', 'ab') WHERE s = 'abc' OR s = 'bcd' OR s = 'cde';

-- 5. v = '1' is true for the stored UInt64 1, v IN ('1') is false: 0, expected 3
SELECT count() FROM values('v Variant(String, UInt64)', 1, 2, 3) WHERE v = '1' OR v = '2' OR v = '3';

-- 6. case 3 with the constant wrapped in Dynamic: 0, expected 1
--    (an Enum constant inside Dynamic or inside a Tuple is wrong the same way)
SELECT count() FROM values('s String', 'ab') WHERE s = toFixedString('ab', 3)::Dynamic OR s = toFixedString('cd', 3)::Dynamic OR s = toFixedString('ef', 3)::Dynamic;

-- 7. the two-term AND fold, NaN inside a Tuple: 1, expected 0
SELECT count() FROM values('t Tuple(Float64, Float64)', (3., 3.)) WHERE t = (3., 3.) AND t <= (nan, 9.);

-- 8. the reverse: s = 1 alone throws NO_COMMON_TYPE, the chain returns 1
SELECT count() FROM values('s String', '1') WHERE s = 1 OR s = 2 OR s = 3;

With the rewrite disabled (optimize_min_equality_disjunction_chain_length = 100, optimize_min_inequality_conjunction_chain_length = 100 for the NOT IN form, optimize_redundant_comparisons = 0 for 7) every query gives the expected result. On the CI build of #117293, 1 to 4 are fixed and 5 to 8 still reproduce. 7 is #117379, which I will fix in a separate PR. The Enum constant case from the description is already fixed on master by #112647.

Should I close this PR now, or keep it open until there is a better solution?

@vdimir vdimir closed this Sep 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

For item 7: the separate PR is #117595 (open), which closes #117379.

javyxu pushed a commit to javyxu/ClickHouse that referenced this pull request Nov 18, 2026
…ssions

`optimize_redundant_comparisons` prunes an `AND` chain of comparisons on one
expression by converting each constant to the expression's type and treating the
converted `Field` as an exact orderable point. For a `Variant` expression that
premise is false in two independent ways, so the analysis silently drops or gains
rows.

First, `ColumnVariant::compareAt` orders discriminator-first: rows with different
discriminators compare by discriminator alone, values only when the discriminators
match. Measured on `Variant(FixedString(4), UInt64)`, both `UInt64` rows compare
greater than a `FixedString` constant regardless of their numeric value. A `Field`
has nowhere to carry a discriminator, so the analyzer's order is not the runtime
order and range comparisons diverge. This half cannot be repaired at the `Field`
level at all, which is why the remedy is to decline rather than to normalise the
constant.

Second, `convertFieldToType` returns `src` unchanged for a `Variant` target when
the constant's type is already an alternative or the `Field` is insertable as-is.
So `'ab'::FixedString(2)` stays `'ab'` while `'ab'::FixedString(4)` becomes
`'ab\0\0'`, two different `Field`s, yet at runtime both are converted into the
`FixedString(4)` alternative and match the same stored row. The analysis reads two
distinct equality points on one expression and folds the `AND` to `0`. For a plain
`FixedString(4)` expression both spellings converge on `'ab\0\0'`, which is why
non-`Variant` expressions are unaffected: the padding normalisation happens exactly
where the `Variant` fast path skips it.

`DataTypeVariant::hasDynamicStructure` reports only its alternatives' dynamic
structure, so the existing dynamic-structure declines do not catch a plain
`Variant(FixedString(4), UInt64)`, and `addComparisonFilter` had no `Variant` rule.

The guard goes in the shared callee rather than at a call site, because the
transitive-derivation path diverges independently and only a check in the callee
covers all three call sites at once. The filter is kept in the existing
`opaque_filters` bucket rather than returned early, since a filter there with no
converted value also vetoes the global fold-to-false collapse, so no new control
flow is introduced.

This deliberately forgoes three folds on `Variant(String, ...)` expressions that
are themselves sound. Their results are unchanged, verified with the optimizer
disabled, but the optimization no longer fires; the new test pins that cost so a
later narrowing of the guard cannot go unnoticed.

Reachable at `use_variant_default_implementation_for_comparisons = 0`. At the
default the comparison resolves to `Nullable(UInt8)` and the chain optimization
bails out on the `and` node's result type before reaching the analysis. `Dynamic`
was measured and does not diverge: its comparison is always `Nullable(UInt8)`, with
no setting to change that, so both call sites bail out. Confirmed positively rather
than by absence, with a duplicate-constant prune probe that leaves a `Dynamic`
query tree untouched while pruning a plain `FixedString(4)` one.

Split out of ClickHouse#112272 after a review comment there, per the one-root-cause-per-PR
rule. It is based on master and shares no helper with that branch.
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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants