Repository navigation
Conversation
…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]>
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 Totals, derived by script from the per-round ledgers rather than from prose: 7 own-review ❌ Blockers, both agreed and both fixed
|
| # | 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.
Pre-PR validation gate
Build ID: |
|
cc @KochetovNicolai @novikd - could you review this? |
|
Workflow [PR], commit [6b0e3c6] Summary: ❌
AI ReviewSummaryThis PR hardens the Findings❌ Blockers
Final Verdict
|
| /// 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()) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - 34be543CI has fully finished on this head with no failures: 174 check-runs, all Session id: cron:our-pr-ci-monitor:20260728-163000 |
…ue-equivalence # Conflicts: # src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 176/184 (95.65%) · Uncovered code |
CI finish ledger - 6b0e3c6Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
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: Breadth over 30 days for the accounting signature ( Session id: cron:our-pr-ci-monitor:20260730-230000 |
vdimir
left a comment
There was a problem hiding this comment.
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.
|
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:
And one case is an error rather than a strict answer, so documenting it would not cover it: on So the skip list I plan is floats, |
|
@groeneai cut down patch as discussed above |
|
Understood. Dropping the general predicate and cutting this down to a type skip list in the rewrites: floats, |
|
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 ( Should I close this PR now, or keep it open until there is a better solution? |
…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.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes wrong results and a spurious
TOO_LARGE_STRING_SIZEerror when a chain of comparisons is rewritten intoIN/NOT IN, or a two-termANDis folded, using a constant whose converted value does not compare the same wayequalsdoes. Affected constants include a float0.0/-0.0orNaN, aFixedStringcompared against aStringcolumn, anEnumcompared against aString/FixedStringcolumn, aVariant/Dynamic/JSONconstant, a string wider than aFixedString(N)column, and a constant that has no common type with a string column at all. A comparison over aJSONcolumn, and one between a string column and such a constant, that the rewrites previously answered silently now correctly reportNO_COMMON_TYPE.Description
LogicalExpressionOptimizerPassrewritesx = c1 OR x = c2 OR x = c3intox IN (c1, c2, c3)(tryReplaceOrEqualsChainWithIn), thenotEqualscounterpart intox NOT IN (...)(convertNotEqualsChainToNotIn), and folds a two-termANDinaddComparisonFilter. All three consume the constant converted into the expression's type throughtryConvertToColumnType, whose contract is only "does this convert losslessly?".That is weaker than what the three consumers actually need, which is "is the converted
Fielda faithful semantic point for this type - does exact equality on it agree with whatequalscomputes?".inbuilds aSetkeyed on the converted value and matches it exactly (SetUtils.cpp->convertFieldToTypewithstrict), while the comparison it replaces is evaluated semantically in the wider of the two types;compareComparisonFiltersandcanonicalizeNotEqualsKeylikewise 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:
+0.0/-0.0.equalscompares withaccurateEqualswhere-0.0 == 0.0, while the set is keyed on the exact IEEE value:SELECT -0.0 = 0.0, -0.0 IN (0.0)is1, 0. A chain over a column holding-0.0loses that row.NaN. No comparison matches aNaN, butnan IN (nan)is1, so the chain gains a row.FixedStringpadding against aStringtarget.ColumnFixedString::operator[]yields allNbytes 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.FixedString(M)target.ColumnFixedString::insertthrowsTOO_LARGE_STRING_SIZE, so a query that answers correctly without the rewrite fails with it. Reachable from aFixedString(N > M)source and from a plainStringsource of sizeS > Malike.Enumagainst a string-family target.equalscasts both operands to the enum's label, whileconvertFieldToTypestringifies the enum's raw integer, so the set key for'a'::Enum8('a' = 1)against aStringcolumn is'1'.Variantexpression.equalsruns independently per active alternative; the set holds one discriminator-bearing key, and a constantFieldcarries no discriminator at all.Variant/Dynamicconstant.ColumnVariant::operator[]andColumnDynamic::operator[]return the bare underlyingFieldwhileFunctionVariantAdaptor/FunctionDynamicAdaptorcompare using the active alternative's real type, so a source-type check sees onlyVariantand permits the rewrite. One shape additionally failed withTYPE_MISMATCH.NaNin theANDfold. The existing bail-out there inspects only a top-levelFloat64Field, soTuple(Float64)slips past it.NaNpayloads below anArray/Map. Container equality treats any twoNaNs as equal, while a compound set key hashes the nested float's raw bytes.INbuilders already decline these; the fold does not, and it answered0for a comparison over aJSONcolumn whose own terms legitimately raiseNO_COMMON_TYPE.equalson 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 aStringcolumn against e.g. anInt64constant, or against a multi-elementTupleor anArrayconstant, legitimately raisesNO_COMMON_TYPEwhile the converted value round-trips, and all three rewrites answered instead - and a contradiction on an unrelated column could collapse the wholeANDand 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 twoINbuilders. The string-family rule is modelled on the equivalent guard inKeyCondition, which declines index analysis for the same padding reasons and with the sameM >= Nexemption.The
NaNcheck has a deliberate per-consumer depth. The fold compares twoFields with each other, so below anArray/Mapboundary both sides go through the samecompareAt, which treats any twoNaNs as equal - the semantics already match and recursing deeper would only lose valid folds. A set instead matches aField's hash against a column's raw bytes, so the deeper check is required there. Symmetrically, the float-zero rule is set-specific only:addComparisonFiltercompares withaccurateEquals, 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,FixedStringandEnumexpressions 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-elementtuple(...)or anArrayagainst a string-family expression survives analysis, then raisesNO_COMMON_TYPEfromexecuteGeneric, and all three rewrites answered it instead. Only the spellings whoseStringrendering does not parse back - a single-elementtuple(...)and aMap- 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
NaNat any width or across widths,inf/-inf, columns containing-0.0/NaNwhen no constant is,FixedString(N)against a wider-or-equalFixedString(M), aStringconstant of sizeS <= Mincluding one with a trailing NUL, anEnumexpression with label or integer constants,Decimalscale pairs,Datewith string constants,UUID, mixed integer widths, andLowCardinalitycolumns. A blanket type-level exclusion of floats would silently disable all of those.Disclosed trade-offs, each measured:
Variant- orDynamic-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.FixedStringconstant against aStringcolumn is also declined, and the size rule is keyed on the converted value's size rather than on the source type, so a plainStringsource is covered too.One reference line of another PR's test changes
04628_logical_optimizer_in_rewrite_variant_type.referenceline 23 moves from1to0. That test belongs to #111924 (@groeneai, merged), whose guard keeps theINrewrite from changing a node's result type when aVariantexpression 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, itssetting = 0line above is unchanged at0, and withuse_variant_default_implementation_for_comparisons = 1the 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 constantFieldcarries no discriminator and therefore cannot be a semantic point for aVariantexpression. 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
Variantwith exactly one alternative has nothing to depend on per row, so the decline should apply only to multi-alternativeVariants. Six single-alternative carriers say otherwise, all at default settings - for aVarianttarget the shared semantic-point rule matches none of its string-family,Tuple,ArrayorMapbranches and falls through to accepting the constant, so every divergence above is live with one alternative:Variant(String)expression,toFixedString('ab', 5)-family constants03Variant(String)expression,Enum8label constants03Tuple(Variant(String))expression,tuple(toFixedString(...))constants02Variant(FixedString(3))expression,'abcde'constantsNOT_IMPLEMENTED0Variant(Tuple(Variant(Float64, UInt64)))expression,tuple(1)-family constantsILLEGAL_TYPE_OF_ARGUMENT3Variant(DateTime64(1, 'UTC'))expression, same-scaleDateTime64(1, 'UTC')constantsILLEGAL_COLUMN3The 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:
tryConvertToColumnTypereturns 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 aVariantexpression is built nullable andColumnNullablerefuses aColumnVariantnested 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)againstFloat64constants,Variant(Enum8)againstStringlabels, andVariant(UInt256)againstInt64- 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
addComparisonFilterparks 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 anANDtofalsewhen no parked filter is missing its converted value, so only the expression guard can veto it - which is what keeps the query's ownNO_COMMON_TYPEvisible when a contradiction on an unrelated column would otherwise have collapsed the wholeANDand dropped the throwing term. Without it, such a query's success would depend onoptimize_redundant_comparisons. Measured oni Int32, c JSON(x String):(i = 1) AND (i = 2) AND (c != '{"x":1}'::JSON(x Int64))answered0before and raisesNO_COMMON_TYPEnow. 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 sameJSONcolumn is vetoed too and thatANDis 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-expressionJSONfold row is closed by the same guard.Recursion depth
The three constant walkers, both recursive type walks and the
forEachChildcallback callcheckStackSize()at each composite recursion boundary, followingFieldVisitorHash, which places it on itsTuple/Map/Array/Objectoperators and on none of its scalar ones. The callback needs it for the same reason as the rest: everyforEachChildimplementation 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 becausetryConvertToColumnTypereturns immediately for equal types, so a nested same-type constant can reach them without having passed the checkconvertFieldToTypeperforms. This is hardening, not a fix for an observed failure: a deeply nested constant already fails with a controlledTOO_DEEP_RECURSIONfrom an earlier pass at the same depth with and without these walkers, and at default settingsmax_ast_depthrejects 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 inIDataTypeand benefits all of them.Not addressed here, knowingly:
tryConvertToColumnType's round-trip check is top-level only, becauseconvertFieldToTypepasses no source-type hint when recursing intoArray/Tuple/Mapelements, so a nested lossy leaf conversion escapes it. That belongs inconvertFieldToTypeand is already being fixed there by #111399. Only itsVariant-source form is closed here, since that PR does not touch theVariantbranch.Also left alone deliberately: both builders bypass the chain-length gate for a
LowCardinalityexpression, 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_equivalenceasserts 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, viaEXPLAIN 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.