Skip to content

Fix LogicalExpressionOptimizer chain->IN rewrites for Variant and dynamic-structure expressions - #111924

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-or-to-in-rewrite-type-drift
Jul 26, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-or-to-in-rewrite-type-drift

Conversation

@groeneai

@groeneai groeneai commented Jul 25, 2026 •

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):

Fixed three bugs in the analyzer rewrites that turn a chain of comparisons into IN/NOT IN (x = c1 OR x = c2 OR ..., x != c1 AND x != c2 AND ..., and has(const_array, x)). For a Variant expression with use_variant_default_implementation_for_comparisons = 0 the rewrite changed the expression result type from UInt8 to Nullable(UInt8), which raised a LOGICAL_ERROR from the query-tree validation check in debug and sanitizer builds. For an expression with a dynamic structure (Dynamic, Array(Dynamic), JSON) the rewrite made a working query fail with Illegal type ... of argument of function in, because IN rejects such arguments. Both directions also returned wrong results when a constant does not convert losslessly to the expression's type, such as a DateTime constant with a time of day compared against a Date column.

Description

The LogicalExpressionOptimizer pass rewrites x = c1 OR x = c2 OR ... into x IN (c1, c2, ...), and symmetrically x != c1 AND x != c2 AND ... -> x NOT IN (...); HasToInPass rewrites has(const_array, x) -> x IN (const_array). Each replaces a node whose ancestors were already resolved against the old result type, and neither IN nor NOT IN accepts the same set of argument types, or compares values the same way, as the comparisons it replaces. Three separate defects follow.

1. Result type changes from UInt8 to Nullable(UInt8) for Variant. With use_variant_default_implementation_for_comparisons = 0, equals/notEquals on a Variant expression resolve to UInt8, but the resulting in/notIn resolve through FunctionBaseVariantAdaptor to Nullable(UInt8). has() never uses that adaptor (it does not use the default implementation for NULLs) so it always returns UInt8, while the in() it is rewritten to always does for a Variant needle. Debug and sanitizer builds report this from the query-tree ValidationChecker as Function ... expects argument N to have UInt8 type but receives Nullable(UInt8) after running LogicalExpressionOptimizer pass. In release builds that check is compiled out, and the aggregate function created during analysis for the captured UInt8 argument type is used as-is by the planner (only window functions are re-created from the actual argument types), so the divergence reaches execution.

2. A working query starts failing for a dynamic structure. in/notIn reject arguments whose type has a dynamic structure outright, and do not use the default implementation for Dynamic, so resolving the rewritten node throws Illegal type Array(Dynamic) of argument of function notIn (error 43) out of the optimizer pass, in every build type. This affects Dynamic as well as types that merely contain one (Array(Dynamic), Map/Tuple/Variant over Dynamic) and JSON.

3. The rewrites silently return wrong results when the constants are not compared as they were. Two independent causes, one per direction.

convertNotEqualsChainToNotIn built the right-hand side as ConstantNode(Tuple), so the element types were re-derived from the Field values by FieldToDataType. That collapses DateTime to UInt32, DateTime64 to a plain Decimal64, an Enum to its underlying integer and so on, and the rewritten notIn then compares against different values than the chain it replaced. tryReplaceOrEqualsChainWithIn has passed an explicit DataTypeTuple built from ConstantNode::getResultType() since #66344 for this exact reason; the NOT IN direction never did.

Keeping the types is necessary but not sufficient, in either direction: the set converts every element to the expression's type, while the comparison it replaces is evaluated in the wider of the two. Where that conversion is lossy the two disagree.

-- d Date, four rows 2020-01-01 .. 2020-01-04
SELECT count() FROM t WHERE d != parseDateTimeBestEffort('2020-01-01')
                       AND d != parseDateTimeBestEffort('2020-01-02')
                       AND d != parseDateTimeBestEffort('2020-01-03');
-- 4 with the rewrite, 1 without it: the constants lost their DateTime type

SELECT count() FROM t WHERE d = toDateTime('2020-01-01 12:00:00')
                        OR d = toDateTime('2020-01-02 12:00:00')
                        OR d = toDateTime('2020-01-03 12:00:00');
-- 3 with the rewrite, 0 without it: no row equals a constant with a time of day,
-- but each constant truncates onto a row once it enters the set

The fix keeps the original chain whenever the rewrite cannot preserve the type, cannot be built, or would not compare the same values:

  • tryReplaceOrEqualsChainWithIn: skip when the expression has a dynamic structure (checked before the in node is resolved, since resolving it is what throws), and skip when the resulting in is nullable while none of the replaced equals was. The second guard keys on the drift, not on the type, so the rewrite still fires for a Variant column once use_variant_default_implementation_for_comparisons = 1 makes equals nullable too, and the existing k = 1 OR k = NULL re-wrapping is unaffected.
  • convertNotEqualsChainToNotIn: the same two guards, plus the typed tuple. Here the nullability guard needs no drift term: the caller returns early when the AND is nullable, and AND is nullable whenever any operand is, so a surviving non-nullable AND implies every notEquals was non-nullable.
  • both chain builders additionally skip the rewrite when a constant does not convert losslessly to the expression's type. This reuses tryConvertToColumnType(), which the comparison-filter folding in this same pass already uses for that question, and whose comment block documents exactly this DateTime to Date truncation. A NULL constant is excluded before either chain is collected, so it never reaches the check.
  • HasToInPass: add Variant to the needle-type exclusion list it already keeps for Nullable/LowCardinality/Dynamic/... for exactly this reason. has() never takes the variant adaptor, so the drift is unconditional there and the type is the right key.

Query semantics change only where they were wrong (defects 2 and 3); a skipped rewrite leaves the original chain, which was already correct. The optimization still fires for every type where in/notIn preserves both the result type and the comparison, and the regression test asserts that fires/skips split with EXPLAIN QUERY TREE in both directions, including the Variant column with the setting on and a plain needle for has(), so a blanket "exclude Variant" guard cannot pass unnoticed.

Found by the AST fuzzer, STID 0250-20a8, on a windowFunnel(...)((b = '10') OR (b = '22') OR (b = '6'), ...) shape where b is Variant(UInt256) and the job pins compatibility = 24.3 (hence use_variant_default_implementation_for_comparisons = 0, the default before 26.1 and still a supported configuration). Defect 3 was found by the automated review of this PR.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108715&sha=e0ab38d92bcb293849e8bf35e1932a7ae8b94316&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

I found no open issue for this signature, so the report URL above is the provenance.

Version info

  • Merged into: 26.8.1.156 (included in 26.8 and later)

groeneai and others added 2 commits July 25, 2026 19:10
…e for Variant

The LogicalExpressionOptimizer pass rewrites `x = c1 OR x = c2 OR ...` into
`x IN (c1, c2, ...)` (and the `notEquals` AND -> NOT IN and `has` -> `in`
counterparts). For a Variant expression with
use_variant_default_implementation_for_comparisons = 0 (the default before
26.1, and still a supported/documented configuration), `equals`/`notEquals`
resolve to UInt8, but the resulting `in`/`notIn` resolve through
FunctionBaseVariantAdaptor to Nullable(UInt8). The rewrite then changes the
node's result type, which ancestors already captured -> the query-tree
ValidationChecker throws LOGICAL_ERROR (debug/sanitizer builds abort). Found
by the AST fuzzer, STID 0250-20a8, on the windowFunnel + OR-chain shape.

Add a type-preservation guard to each of the three chain->IN conversions:
skip the rewrite for a group whose in/notIn replacement resolves more nullable
than the comparisons it replaces (tryReplaceOrEqualsChainWithIn,
convertNotEqualsChainToNotIn), and add Variant to the needle-type exclusion
list that HasToInPass already keeps for the same reason. Also skip the OR->IN
rewrite for a Dynamic-structure expression, which `in` rejects outright. When
the rewrite cannot preserve the type it keeps the original chain, so semantics
are unchanged and the optimization still fires for every type where in/notIn
preserves the type (String, Nullable, LowCardinality, Variant with the setting
on).

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108715&sha=e0ab38d92bcb293849e8bf35e1932a7ae8b94316&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The AND path had the same defect the OR path was already guarded against:
notIn rejects arguments with a dynamic structure outright, and the rewrite
resolves the function before the nullability-drift guard runs, so the
optimizer turned a working query into ILLEGAL_TYPE_OF_ARGUMENT.

The earlier reasoning that this could not happen keyed on exact Dynamic,
where notEquals gets the nullability adaptor and the caller bails out on the
resulting nullable AND. Array(Dynamic) and JSON get no adaptor while
hasDynamicStructure() is transitively true, so their comparisons stay UInt8,
the AND stays UInt8, the caller does not bail, and building notIn throws.

Move the check before the function is built, mirroring the OR path. The two
guards stay separate: Variant(UInt256) has no dynamic structure, so only the
nullability-drift guard covers it.

The test now exercises both directions for Dynamic, Array(Dynamic) and JSON,
and asserts that the rewrite still fires for the same Variant column once
use_variant_default_implementation_for_comparisons makes equals nullable, so
a guard keyed on the type instead of the drift cannot pass unnoticed.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent reviewer plus an independent model
(engine: codex; 2 review rounds, 6 gate findings + 8 reviewer findings total).

# Sev Finding Verdict Evidence / action
1 ❌ convertNotEqualsChainToNotIn lacks the hasDynamicStructure() pre-guard that the OR path has, so notIn resolution throws out of the pass (LogicalExpressionOptimizerPass.cpp:1082, in.cpp:53-58) AGREE — fixed @ f58fc4e Raised independently by the reviewer and the gate, and reproduced: Code: 43 Illegal type Array(Dynamic) of argument of function notIn on both the guard-reverted build and the pristine base. The nullability adaptors key on top-level isDynamic/isVariant, so Array(Dynamic)/JSON get none, notEquals stays UInt8, the AND stays UInt8, and the caller's nullable bail-out never fires. Guard hoisted before resolveAsFunction.
2 ⚠️ The test cannot fail if finding 1 regresses: every AND-direction row uses Variant(UInt256), and the only dynamic-structure row was OR-only AGREE — fixed @ f58fc4e Added Array(Dynamic) and JSON rows in BOTH the in and notIn direction. With the guard reverted the test now fails (exit 43, 11 reference lines missing); with it restored the file matches.
3 ⚠️ Variant-with-the-setting-ON preservation was verified but never committed, so a blanket "exclude Variant" guard would pass the test unchanged AGREE — fixed @ f58fc4e Committed the setting-ON EXPLAIN QUERY TREE assertion. Both over-broad variants now fail it: widening the guard to result_type->isNullable(), and replacing it with a blanket isVariant(), each flip that row 1 -> 0.
4 ⚠️ The changelog entry described only the type-drift bug, while the diff also fixes the release-visible Illegal type ... of function in failure for dynamic-structure expressions AGREE — fixed in the description in.cpp:53-58 is not gated on DEBUG_OR_SANITIZER_BUILD, so that half fails in every build type. Both bug classes are now enumerated in the changelog entry and the description.
5 💡 Two obsolete no-op SET allow_experimental_{variant,dynamic}_type lines; an over-broad comment on the notIn preservation block AGREE — fixed @ f58fc4e Both settings confirmed MAKE_OBSOLETE at Settings.cpp:8679-8680 and deleted; the comment now states that with the setting ON the caller returns before conversion, so only setting = 0 is asserted.
6 💡 The release-build claim in the changelog entry asserted an outcome without naming a mechanism AGREE — fixed in the description Now cites the mechanism: QueryTreePassManager.cpp:203 compiles the check out, and PlannerAggregation.cpp:26 reuses the analysis-time aggregate function (the re-create-from-actual-types loop at PlannerExpressionAnalysis.cpp:386-421 covers window functions only).
7 💡 Remove the no-parallel-replicas tag from the new test DISAGREE The tag is protective here. tests/clickhouse-test:1627-1640 shows that without it the runner may inject enable_parallel_replicas=1 + cluster_for_parallel_replicas='parallel_replicas' when automatic_parallel_replicas_mode randomizes to 2; this test's core assertions are EXPLAIN QUERY TREE row counts, and a neighbor run of 00621_regression_for_in_operator failed with CLUSTER_DOESNT_EXIST parallel_replicas under exactly that randomization. The cited precedent asserts query results rather than query-tree shape, and 3 of the 84 stateless tests using EXPLAIN QUERY TREE already carry this tag. The coverage given up is parallel-replica execution of a 4-row Memory table, which exercises nothing in the pass under test.
8 💡 Add a Related: link to the pull request whose CI run produced the report URL DISAGREE That pull request is only where the fuzzer happened to fire; it does not touch LogicalExpressionOptimizerPass.cpp, HasToInPass.cpp, or any Variant comparison path, and the same signature also appears on another unrelated pull request. A #NNNNN reference would create a cross-reference back-link falsely connecting unrelated work and notifying its author, which a maintainer has asked me not to do; the prescribed alternative is the CI report URL, which the description already carries in full canonical form.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Also verified by reading, with no finding: the OR guard keys on the type drift rather than on the
type (so Nullable, LowCardinality, LC(Nullable) and Variant-with-the-setting-ON still
rewrite); the AND guard needs no drift term because a surviving non-nullable AND implies every
notEquals was non-nullable (FunctionsLogical.cpp:697-724); the has() exclusion is correctly
keyed on the type because has() never takes the variant adaptor (arrayIndex.h:518) while the
in() it becomes always does (in.cpp:190); and the sibling rewrites are safe
(InverseDictionaryLookupPass already casts back to the original type, CNF.cpp:385-401 re-resolves
the same argument types, and the old-analyzer optimizer runs before type resolution).

Session id: cron:clickhouse-review-slot-10:20260725-222600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET enable_analyzer=1, use_variant_default_implementation_for_comparisons=0, optimize_min_equality_disjunction_chain_length=3; then CREATE TABLE t0 (b Variant(UInt256)) ENGINE=Memory; INSERT INTO t0 VALUES (1); SELECT NOT ((b='10') OR (b='22') OR (b='6')) FROM t0; aborts on master with expects argument 1 to have UInt8 type but receives Nullable(UInt8) after running LogicalExpressionOptimizer pass.
b Root cause explained? With the setting off, equals(Variant, const) resolves to UInt8, but the in the pass builds resolves through FunctionBaseVariantAdaptor to Nullable(UInt8). The OR->IN rewrite then changes the OR node's result type after ancestors (here windowFunnel's argument) already captured UInt8 -> query-tree ValidationChecker throws LOGICAL_ERROR.
c Fix matches root cause? Yes. The pass must not change a node's result type; the fix keeps the original comparison chain when in/notIn would resolve more nullable than the replaced comparisons. Not a symptom guard (no ValidationChecker exemption, no runtime cast that would throw on NULL variant rows).
d Test intent preserved / new tests added? New stateless test 04628_logical_optimizer_in_rewrite_variant_type.sql added: all four carriers, the dynamic-structure rows in BOTH the in and notIn direction (Dynamic, Array(Dynamic), JSON), plus EXPLAIN QUERY TREE fires/skips assertions. Test liveness proven by reverting each guard in turn: every guard has at least one row that fails without it. No existing test weakened.
e Both directions demonstrated? Yes. Master build (Build ID 85da7339...) aborts on the repro (rc=134); fixed build (Build ID 2e6d5ceb...) returns correct results. Running the whole test with the rewrite disabled (chain lengths = 100) gives byte-identical data rows, so semantics are unchanged.
f Fix is general across code paths? Yes. All chain->IN carriers fixed at the source: tryReplaceOrEqualsChainWithIn (OR->IN), convertNotEqualsChainToNotIn (AND of notEquals -> NOT IN), and HasToInPass (has(const_array,x) -> in). Both failure modes are guarded in BOTH conversion functions symmetrically: the nullability drift, and the dynamic-structure rejection that makes building the function throw. Safe siblings verified: InverseDictionaryLookupPass already wraps in a cast; CNF in<->notIn re-resolves the same types; the old-analyzer optimizer is AST-level (pre-type-resolution).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified the optimization still FIRES for String, Nullable(UInt8), LowCardinality(String), LC(Nullable(String)), UInt8-with-NULL-literal (is_any_nullable cast path), and Variant with the setting ON; it SKIPS only for Variant under the adaptor (setting off) and for dynamic-structure expressions (Dynamic, Array(Dynamic), JSON), which in/notIn reject outright. The guard keys on the observed type drift, not on the type name: a blanket isVariant() guard fails the committed test.
h Backward compatible? (maintainer-approved exception only) Yes. No settings added or changed, no SettingsChangesHistory.cpp entry needed. The only behavior change is that a previously-aborting (debug) / type-confused (release) query now runs with its original, unchanged semantics.
i Invariants and contracts preserved? Yes. The invariant "an analyzer pass must not change a node's result type" is now upheld in the remaining direction; the guards fire before a mismatched type can leak to already-resolved ancestors, and each skipped-group path reuses the same std::move(... back_inserter(...)) restoration the existing below-threshold branch uses, so the chain is preserved intact on every early-exit path.

Session id: cron:clickhouse-impl-slot-5:20260725-213300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @yakov-olkhovskiy — could you review this? It stops the LogicalExpressionOptimizer chain->IN rewrites (OR of equals, AND of notEquals, and has(const_array, x)) from changing the node's result type for a Variant expression under the variant comparison adaptor, and from building an in/notIn over a dynamic-structure argument that the function rejects outright. Each rewrite now keeps the original chain in those cases.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8191c97]

Summary: ✅


AI Review

Summary

This PR fixes several analyzer chain -> IN rewrite bugs around Variant, dynamic-structure arguments, and lossy Date/DateTime conversions. I still found one remaining correctness gap: float chains are still rewritten even though equals/notEquals and IN/NOT IN do not agree on -0.0 versus +0.0, so the optimization can still silently change query results.

Findings

❌ Blockers

  • [src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp:2498] The new lossless-conversion guard is not sufficient for Float*. A chain such as f = 0.0 OR f = 1.0 (or f != 0.0 AND ...) still rewrites, but equals/notEquals treat -0.0 and +0.0 as equal while in/notIn use a Set keyed on raw float bits, so the rewritten predicate can return a different result. Suggested fix: reject float expressions/constants in both chain builders, mirroring HasToInPass, or replace the guard with an equivalence test that matches IN membership semantics rather than only conversion losslessness.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 26, 2026
groeneai added 5 commits July 26, 2026 04:31
…rite

convertNotEqualsChainToNotIn built the right-hand tuple as
ConstantNode(Tuple), so the element types were re-derived from the Field
values by FieldToDataType. That collapses DateTime to UInt32, DateTime64
to a plain Decimal64, an Enum to its underlying integer and so on, and
the rewritten notIn then compares against different values than the
notEquals chain it replaced.

Two observed effects, both with optimize_min_inequality_conjunction_chain_length
reached:

  d Date, ts DateTime
  d  != parseDateTimeBestEffort(...) AND ...  -- matched every row
  ts != toDate(...) AND ...                   -- matched every row

The results were silently wrong: with the rewrite disabled the same
queries return one row, with it enabled they return all four.

tryReplaceOrEqualsChainWithIn already passes an explicit DataTypeTuple
built from ConstantNode::getResultType() for this exact reason (the
OR -> IN direction had the same bug, fixed in ClickHouse#66344). Do the same here.

Found by the automated review of ClickHouse#111924.
The existing has() regression only checked the result, which the query
tree ValidationChecker protects in debug and sanitizer builds. Reverting
the Variant exclusion in HasToInPass therefore passed a release stateless
run. Assert the absence of the `in` node with EXPLAIN QUERY TREE instead,
and assert it still fires for a plain UInt8 needle so a blanket guard
cannot pass either.
Preserving the constant types is necessary but not sufficient. The set
converts each element to the expression's type, while the comparison it
replaces is evaluated in the wider of the two types, so a lossy
conversion makes the two disagree:

  d Date
  d != toDateTime('2020-01-01 12:00:00') AND ...

The row 2020-01-01 promotes to midnight and does differ from the
constant, so the predicate holds, but the constant truncates to
2020-01-01 and the set matches the row instead.

Reuse tryConvertToColumnType(), which the comparison-filter folding in
this pass already uses for exactly this question, and keep the original
chain when any constant fails to round-trip.
Call the ValidationChecker failure a logical error rather than an abort:
it throws a LOGICAL_ERROR exception, it does not abort the server.

Trim the lossless-conversion comment down to the invariant at that line;
the reasoning belongs in the commit that introduced the check.
The equals chain has passed the resolved constant types to the set since
ClickHouse#66344, but preserving the types is not the whole requirement: the set
still converts each element to the expression's type while the comparison
is evaluated in the wider of the two.

  d Date
  d = toDateTime('2020-01-01 12:00:00') OR ...   -- matched 3 rows, should match none

Every row differs from a non-midnight constant, so the chain selects
nothing, but each constant truncates onto a row and the set matches it.
Same mechanism and same fix as the notEquals direction; a NULL constant
is excluded before the chain is collected, so `k = 1 OR k = NULL` is
unaffected.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, and fixed in 8191c97. The asymmetry was real: tryReplaceOrEqualsChainWithIn has passed an explicit DataTypeTuple built from ConstantNode::getResultType() since #66344 (issue #64487), and convertNotEqualsChainToNotIn never did, so FieldToDataType re-derived the element types. On the previous head, four rows 2020-01-01 .. 2020-01-04 in a Date column:

d != parseDateTimeBestEffort('2020-01-01') AND (2 more)   -- 4 rows rewritten, 1 not rewritten
dt != toDate('2020-01-01') AND (2 more)                   -- 4 rows rewritten, 1 not rewritten

The tuple resolved to Tuple(UInt32, UInt32, UInt32) instead of Tuple(DateTime, DateTime, DateTime). Silently wrong results, not just a type mismatch.

Two corrections to the suggested scope, both found by verifying it:

Carrying the types over is not sufficient on its own. The set converts every element to the expression's type, while the comparison it replaces is evaluated in the wider of the two, so a lossy conversion still makes them disagree. For a Date expression, d != toDateTime('2020-01-01 12:00:00') holds for the row 2020-01-01 (which promotes to midnight, and midnight differs from noon), but the constant truncates onto that row and the set matches it. Adding only the typed tuple therefore turned a correct 4 into a wrong 1. Both builders now also require every constant to round-trip through tryConvertToColumnType(), the helper addComparisonFilter in this same pass already uses for that question.

The same lossless requirement was missing in the OR -> IN direction, which the report did not cover: d = toDateTime('2020-01-01 12:00:00') OR (2 more) returned 3 rows rewritten versus 0 not rewritten. Fixing only the AND side would have left the sibling defect open, so both are fixed.

DateTime64 against Date (Expected: Date. Got: Decimal64.) fails identically with and without the rewrite, so that one is a separate in coercion issue and is out of scope here.

Not addressed, and not regressions from this PR. equals compares via accurateEquals in the widened type while in builds a set keyed on the converted raw representation, so the two also disagree for signed zero on floats (-0.0 = 0.0 is 1, -0.0 IN (0.0) is 0) and for zero padding on mixed String/FixedString. Both reproduce byte for byte on the pre-existing head f58fc4e, in both chain directions, and HasToInPass already excludes floats and non-equivalent types for exactly this reason while neither chain builder does. That is a different root cause on carriers this PR does not touch, so it belongs in its own change rather than bundled into a fuzzer fix.

Test 04628 covers each carrier in both directions and asserts the fires/skips split with EXPLAIN QUERY TREE, so reverting any single guard fails it. Verified with the guard reverted: the new rows return 4/4/0 against a reference of 1/1/1.

/// The set converts each element to the expression's type, while the comparison it
/// replaces is evaluated in the wider of the two: a lossy conversion makes them disagree.
/// A NULL constant is excluded above, so it never reaches this check.
if (!tryConvertToColumnType(literal, expr_type))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This still misses the same-value mismatch that HasToInPass already had to special-case for floats. tryConvertToColumnType succeeds for Float*, so both this OR -> IN branch and the analogous NOT IN branch above will still rewrite chains like f = 0.0 OR f = 1.0 / f != 0.0 AND .... But equals/notEquals treat -0.0 and +0.0 as equal, while in/notIn go through a Set keyed on the raw float bits, so a row f = -0.0 changes result after the rewrite. Please reject float expressions/constants here as well, or add a stronger equivalence check than “lossless conversion”.

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.

Declining this one, with measurements. I checked the specific new interaction you point at, because a47b8af and 8191c97 did not exist when I first looked at signed zero, and your reading of them is correct: tryConvertToColumnType succeeds for Float64 -> Float64, so the new lossless check is a no-op on this carrier and both rewrites still fire. The EXPLAIN QUERY TREE still shows the in/notIn node and the tuple resolves to Tuple(Float64, Float64, Float64), which is what it is meant to do.

What it is not is a regression from this PR. Rows (-0.0, 1.0, 2.0, 3.0) in a Float64 column, counting with the rewrite on (chain_length = 3) versus off (100):

                                              rewrite ON   rewrite OFF
f != 0.0 AND f != 1.0 AND f != 2.0                2            1
f  = 0.0 OR  f  = 1.0 OR  f  = 2.0                2            3

Ground truth per row agrees with the off column (-0.0 != 0.0 is 0, so one row survives the conjunction). I then rebuilt the pass from the pristine base version of the file, with none of this PR's changes in it, and got 2 / 1 and 2 / 3 again, identical in both directions. The divergence predates this PR in both builders, and the OR side has had it since #66344.

I would rather not fold the fix in here. Signed zero is one of three symptoms of a single different root cause: equals compares via accurateEquals in the widened type, while in builds a set keyed on the converted raw representation. The same mismatch produces wrong results for mixed String/FixedString, where equals ignores trailing zero padding and the set does not, and for tuples with nullable elements, where equality yields NULL and top-level membership yields UInt8. Note that tryConvertToColumnType deliberately exempts string sources from its round-trip check, so no strengthening of the lossless test reaches the padding case; the correct shape is a value-equivalence precondition, not a stronger conversion check.

HasToInPass already carries exactly that precondition for has(arr, x) -> x IN (arr): it excludes floats outright, isFloat so BFloat16 is covered too, and otherwise requires the two types to be equivalent under raw Field comparison or both to be native integers. Neither chain builder has an equivalent. Lifting that predicate into the two chain builders, most likely by factoring it out of HasToInPass so all three rewrites share one implementation, is the right change, and it needs its own type matrix asserting that the rewrite still fires for the safe types rather than silently turning into a plan regression.

That is a separate change on carriers this PR does not touch, and this PR is a P0 fuzzer fix for type and nullability drift. I have opened a fix task for the value-mismatch class with the baseline measurements above recorded, and I am tracking it separately rather than dropping it.

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 follow-up I said I was tracking separately is now open: #112272.

It covers the value-mismatch class from this thread and nine further divergences found while
investigating it, across all three consumers of tryConvertToColumnType rather than just the
notEquals builder. The float half is value-based rather than type-based, because only +0.0/-0.0
and NaN actually diverge and a type-level exclusion would silently stop the rewrite firing for
every ordinary float constant.

@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 68/68 (100.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov 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.

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Jul 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 26, 2026
Merged via the queue into ClickHouse:master with commit 4af577e Jul 26, 2026
351 of 352 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 26, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…rite

convertNotEqualsChainToNotIn built the right-hand tuple as
ConstantNode(Tuple), so the element types were re-derived from the Field
values by FieldToDataType. That collapses DateTime to UInt32, DateTime64
to a plain Decimal64, an Enum to its underlying integer and so on, and
the rewritten notIn then compares against different values than the
notEquals chain it replaced.

Two observed effects, both with optimize_min_inequality_conjunction_chain_length
reached:

  d Date, ts DateTime
  d  != parseDateTimeBestEffort(...) AND ...  -- matched every row
  ts != toDate(...) AND ...                   -- matched every row

The results were silently wrong: with the rewrite disabled the same
queries return one row, with it enabled they return all four.

tryReplaceOrEqualsChainWithIn already passes an explicit DataTypeTuple
built from ConstantNode::getResultType() for this exact reason (the
OR -> IN direction had the same bug, fixed in ClickHouse#66344). Do the same here.

Found by the automated review of ClickHouse#111924.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…te-type-drift

Fix LogicalExpressionOptimizer chain->IN rewrites for Variant and dynamic-structure expressions
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 pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants