Skip to content

Do not prune a comparison of a value that carries its own type - #117637

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:no-prune-comparison-of-self-typed-value
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:no-prune-comparison-of-self-typed-value

Conversation

@groeneai

@groeneai groeneai commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113470
Related: #117595

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 wrong results when an AND chain compares a Dynamic or JSON value at any depth (for example Array(Dynamic)), or chains != conditions on a Variant nested in a container. Such a value is ordered by its type before its value, which neither optimize_redundant_comparisons (enabled by default since 26.7) nor a NOT IN set can express, so a condition that excludes a row could be dropped and the row returned. The NOT IN merge is not gated by that setting.

Description

optimize_redundant_comparisons prunes a comparison implied by another on the same expression, ordering the constants' Field values by type tag. A Variant, Dynamic or JSON value carries its own type, and IColumn::compareAt orders it by that type's place in the name-sorted alternative list before the value, so the bound judged looser can be the one that excludes the row. #113470 made the pass decline a Variant expression. This PR widens that one screen (comparisonOrdersTypeBeforeValue) to Dynamic and JSON at any depth and to a constant operand that carries its own type, and keeps such a notEquals out of the notIn merge, whose set rebuilds its constants from Fields and so loses the discriminator.

On 26.10.5.57, with Array(Dynamic) holding [1.0::Float64], a >= [1.0::Float64]::Array(Dynamic) AND a >= [2::Int64]::Array(Dynamic) returns 1 where the second bound alone returns 0; Array(JSON), top-level JSON and an Array(UInt64) column against an Array(Dynamic) constant behave the same. With Array(Variant(Date, UInt64)) holding [1::UInt64], a != [toDate(1)] AND a != [1::UInt64] AND a != [5::UInt64] (constants cast to the column type) returns 1 at defaults where the second condition alone returns 0: the first two constants are one Field, so the pass drops one as a duplicate. On master, which keeps both since #113470, the chain is merged into notIn and returns 1 for either constant order. All of these return 0 now.

Where the two orders agree, for example for a fully typed JSON, a sound fold is forgone, on answers that were already correct. #117595 asserts one such fold survives, so whichever merges second updates that arm.


Workflow [PR]
Sync PR [sync-upstream/pr/117637]

groeneai and others added 3 commits September 2, 2026 03:57
`optimize_redundant_comparisons` prunes a comparison implied by another on the
same expression by ordering the two constants' `Field` values by their own type
tag (`Field::Types::Which`). That order is only the comparison's order when the
comparison compares values.

A `Variant`, `Dynamic` or `JSON` value carries its own type, and `compareAt`
orders such a value by that type's place in the type's name-sorted alternative
list before it looks at the value: `ColumnVariant::compareAt` returns on the
discriminator, `DataTypeVariant` builds its alternative list through a
`std::map<String, DataTypePtr>` so discriminator order is name order,
`ColumnDynamic::compareAt` repeats it and compares type names for shared-variant
values, and `ColumnObject::compareAt` delegates each sorted path to its
`Dynamic`. For `Variant(Float64, Int64)` the two orders are exactly reversed
(`Float64` before `Int64` by name, `Int64` = 2 before `Float64` = 3 by tag), so
the bound the analysis judges looser is the one that actually excludes the row,
and pruning it returns a row the `WHERE` clause excludes.

`Field::Types` has no `Variant` member, so a converted constant simply does not
carry the discriminator. Unlike the nested-`NULL` case the screen therefore
cannot be on the constant; it has to be on the type. It is applied to both
operands because a comparison is evaluated at the least common supertype, which
carries such a value exactly when one of the operands does, and it is placed in
`addComparisonFilter`, the single callee through which all three call sites and
both `Field`-ordering consumers are reached: the pairwise
`compareComparisonFilters` scan and the `std::map<Field, ComparisonFilterInfo>`
that drops exact duplicate `notEquals` and erases the values a range makes
redundant. A screened filter keeps an empty converted value, which is the
established shape for a parked filter and which vetoes the global fold-to-false
collapse, so declining can only forgo a fold and can never suppress an exception
the comparison would have thrown.

The predicate needs both of its terms. `hasDynamicStructure` reaches `Dynamic`
and `JSON` at any depth, including a `JSON` with no declared path, which
`forEachChild` alone cannot see because `DataTypeObject::forEachChild` walks only
declared typed paths and `DataTypeDynamic` has no override at all. It is false
for a `Variant` of static alternatives, which `compareAt` orders by discriminator
all the same, so the `isVariant` self-test and walk supply that term.
`validateGroupByKeyType` and `resolveFunction` spell the two halves separately
for the same reason; this takes their union.

Measured at pure default settings on a debug build of the parent commit: a
top-level `JSON`, `Array(Dynamic)`, `Array(JSON)` and
`Array(Variant(Float64, Int64))` each answered 1 for a two-bound `AND` chain
whose second bound alone answers 0, and on `Array(Variant(Date, UInt64))`, where
`Date` and `UInt64` are one `Field` type, one of two different `notEquals`
conditions was dropped as an exact duplicate. All five answer 0 with this change.
`Array(Variant(Int64, String))`, whose name order and tag order agree, is
unaffected, as are the 43 tests of the optimizer and `Variant`/`Dynamic`/`JSON`
neighbourhood, with no reference churn.

The `notEquals`-to-`NOT IN` and `equals`-to-`IN` rewrites are deliberately not
changed. Their divergence reproduces with every optimization disabled and with a
hand-written single-element `IN`, and in its narrowest form on a plain
`Array(Float64)` holding `[-0.0]` with no self-typed value anywhere, so it is the
pre-existing set-membership-versus-comparison class rather than this one.

Related: ClickHouse#113470
Related: ClickHouse#116852
Related: ClickHouse#117293
…rd branches

The guard added in the previous commit parks a comparison of a self-typed value
in `opaque_filters`, but pass 2 hands every opaque `notEquals` filter straight
back to `convertNotEqualsChainToNotIn`, which rebuilds its constant from a
`Field`. A `Field` cannot carry a discriminator, which is the whole reason the
guard exists, and `convertNotEqualsChainToNotIn`'s only type screen is
`hasDynamicStructure()`, false for a `Variant` of static alternatives. Because
the guard also keeps predicates the `Field`-keyed duplicate map used to drop, a
chain can now reach the default merge threshold of 3 that previously fell below
it, so on `Array(Variant(Date, UInt64))` holding `[1::UInt64]` the chain
`a != [1::UInt64] AND a != [toDate(1)] AND a != [5::UInt64]` answered 1 where
the previous commit's parent answered 0.

Carry one flag on the parked filter and route it to the ordinary operands
instead of the merge. The change stays inside `optimize_redundant_comparisons`'
own bucket: with the setting off, the merge still applies and still answers
wrongly, which is the pre-existing set-membership-versus-comparison behaviour
tracked by ClickHouse#116852 and being changed by ClickHouse#117293 at those exact lines.

The test could not detect two branches of the guard disappearing, and all of its
references were `0`, so it also passed if the pass, the setting or the analyzer
never ran. Add an arm where only the constant carries its own type (an ordinary
`Array(UInt64)` column against `Array(Dynamic)` constants, which is the only
shape that reaches the constant-operand check: a static `Variant` constant
against an ordinary column has no supertype, and a scalar column against a
self-typed constant is already held aside by the nullable-result screen), arms
for both constant orders of the merged chain, and four `EXPLAIN QUERY TREE`
oracles, each paired with the same shape on an ordinary type so that the
optimization silently ceasing to fire is caught. Pin `enable_analyzer`, since
the pass exists only there.

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit produced `orders_type_before_value` after
`addComparisonFilter` had already returned for `optimize_redundant_comparisons =
0`, and `:2079` is the flag's only consumer. But the `notEquals`-to-`NOT IN`
merge is not gated by that setting: `tryOptimizeAndCompareNotEqualsChain` is
called unconditionally and `enable_pruning` only reaches the pruning analysis. So
with the setting off, a self-typed chain of at least
`optimize_min_inequality_conjunction_chain_length` conditions still merged, and
the set re-keyed constants rebuilt from discriminator-less `Field`s. On
`Array(Variant(Date, UInt64))` holding `[1::UInt64]`, both constant orders of
`a != [1::UInt64] AND a != [toDate(1)] AND a != [5::UInt64]` answered 1 where the
conjunct `a != [1::UInt64]` alone answers 0. Evaluate the predicate once, above
that early return; both routings stay where they were.

The previous commit's message claimed that behaviour was "the pre-existing
set-membership-versus-comparison behaviour tracked by ClickHouse#116852 and being changed
by ClickHouse#117293". That attribution was wrong. ClickHouse#116852 is about `String` versus
`FixedString` padding equivalence, and ClickHouse#117293 screens exactly that with
`stringFamilyPairIsNotEqualityEquivalent`; both mechanisms need no self-typed
value at all. The shape above shares one `Field` tag and contains no float and no
`String`, so it is a discriminator instance that neither covers, and it belongs
here. The genuinely separate class those two own is still deliberately untouched:
it reproduces on a plain `Array(Float64)` holding `[-0.0]` with every
optimization disabled. Nothing is added inside either always-active rewrite.

Declining a merge cannot change a value, and an ordinary type still merges at
that setting, which a new plan oracle asserts.

`isVariant(type)` also had no arm, on the stated grounds that a top-level
`Variant` always resolves to `Nullable(UInt8)` and is parked by the
nullable-result screen first. That was measured on the wrong shape. With
`use_variant_default_implementation_for_comparisons = 0`, which
`04628_logical_optimizer_in_rewrite_variant_type` already sets on a `Variant`
column, every top-level static `Variant` comparison resolves to plain `UInt8` and
is ordered by discriminator: for `Variant(Float64, Int64)` every `Float64`
alternative sorts before every `Int64` one whatever the values are, so the two
orders disagree whenever the `Float64` constant is numerically greater. On a row
holding `9e9::Float64`, `b >= 5.0::Float64 AND b >= 2::Int64` answered 1 without
this guard while the second conjunct alone answers 0. The term is the only path
to that shape, because `DataTypeVariant::forEachChild` yields each alternative
and never the `Variant` itself. Add a result arm, a plan oracle and an
ordinary-scalar pairing for it.

Every new arm is attributed to a binary that reddens it: the parent commit for
the two merge arms, and three mutants built on this tree for the rest, each
reddening exactly its own arms and nothing else. The 43-test optimizer and
`Variant`/`Dynamic`/`JSON` neighbourhood stays green with no reference churn, and
the new test is green over 50 randomized runs.

Related: ClickHouse#113470
Related: ClickHouse#116852
Related: ClickHouse#117293

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, all blockers fixed before publication)

An independent reviewer read the resulting code cold, without the implementation notes, and a
second model then re-reviewed the whole diff. Findings and verdicts:

❌ Blocker, fixed: the screened comparison could still reach the notEquals-to-NOT IN merge.
The first version of this change parked a self-typed comparison in the pass's opaque bucket, and pass
2 hands every opaque notEquals back to that merge. The merge rebuilds its constant from a Field,
which is exactly the representation that cannot carry a discriminator, and its only type screen is
hasDynamicStructure, false for a Variant of static alternatives. Because the fix keeps predicates
the old Field-keyed map used to drop as duplicates, a chain could now reach the default merge
threshold of 3 that previously fell below it. On Array(Variant(Date, UInt64)) holding
[1::UInt64], a != [1::UInt64] AND a != [toDate(1)] AND a != [5::UInt64] answers 0 on master and
answered 1 with the first version, at pure default settings. A screened comparison now stays an
ordinary predicate through to emission, and both constant orders answer 0.

❌ Blocker, fixed: that same guard was bypassable with optimize_redundant_comparisons = 0.
The NOT IN merge is active regardless of that setting, but the flag marking a comparison ineligible
for it was only produced on the pruning path, so with the setting off the chain above merged and
answered 1 again. The flag is now computed for every comparison the pass collects, before the
pruning-disabled return, so eligibility follows the comparison rather than the setting. The
divergence is pre-existing at that setting, not introduced here; it was fixed rather than deferred
because it is the same root cause, in the same function, and no other change owns it.

⚠️ Major, fixed: the test could not detect the guard disappearing, nor the optimization silently
not running.
Every assertion was a result-only zero, so the file stayed green if the pass, the
setting or the analyzer never ran, and neither of the predicate's two operand branches was
distinguished by any arm. Added EXPLAIN QUERY TREE oracles asserting the screened conjunct survives,
plus a positive control on an ordinary Array type asserting the fold still happens, plus the
notIn present/absent pairs for the two blockers above. Every arm was attributed to the binary it
reddens on, including deliberate mutants that delete each guard branch and one that screens every
type.

❌ Fixed in the description: three claims that did not hold. An earlier draft said the fold is
kept where the two orders agree, for example Variant(Int64, String). It is not: the screen is on
the type, so it gives up that fold too, and the measurement behind the claim showed only that the
answer for that shape was unchanged because it was already correct. A later draft attributed the
merge divergence above to #116852 and #117293, which are the String versus FixedString padding
mechanism and do not cover a discriminator. The final draft still said that nothing is screened with
optimize_redundant_comparisons = 0, which the second blocker fix had just made false. All three
corrected, and the changelog entry now records that the merge half is not gated by that setting.

💡 Noted, not blocking: an unmeasured claim was cut. The description asserted that the OR-side
equals-to-IN rewrite "has the same hole". Reading establishes only that it rebuilds its constants
from Fields the same way and carries no screen; what actually reproduces there is the
set-membership divergence below, which needs no self-typed value. The sentence now says only what was
measured.

💡 Noted, not blocking: seven test labels read as the opposite of what they assert. Arms named
... chain pruned pin exactly the case where the new guard declines to prune, and plan, self-typed notIn merges asserts zero notIn nodes. The assertions and their expected values are
correct, and each was attributed to a binary that reddens it, so this is display text only: pruned
would read better as pruning enabled, chain kept, and merges as skipped.

💡 Noted, not blocking. Parking the filter leaves its converted value empty, which also vetoes the
AND-to-false collapse when a self-typed comparison appears anywhere in the chain. That guard is
if (!filter.converted_value) return;, so it can only forgo the collapse and never fold to a
different value; the answer matches optimize_redundant_comparisons = 0 exactly.

Disagreed, with evidence:

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

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, at pure default settings, no non-default setting of any kind. CREATE TABLE tad (id UInt32, a Array(Dynamic)) ENGINE = MergeTree ORDER BY id; INSERT INTO tad VALUES (1, [1.0::Float64]); SELECT count() FROM tad WHERE a >= [1.0::Float64]::Array(Dynamic) AND a >= [2::Int64]::Array(Dynamic); answers 1; the second bound alone answers 0. Same for Array(JSON), Array(Variant(Float64, Int64)), a top-level JSON, a notEquals chain on Array(Variant(Date, UInt64)), and an ordinary Array(UInt64) column compared against Array(Dynamic) constants. Nothing probabilistic.
b Root cause explained? Yes. IColumn::compareAt orders a value that carries its own type by that type's place in the name-sorted alternative list before it looks at the value, while the pruning analysis orders the two constants' Field values by Field::Types::Which. For Variant(Float64, Int64) the two orders are exactly reversed (Float64 before Int64 by name, Int64 before Float64 by tag), so the bound judged looser is the one that excludes the row. The discriminator cannot be represented in a Field, so the screen has to be on the type, not on the constant.
c Fix matches root cause? Yes. One predicate on the property that makes the ordering unsound, evaluated in addComparisonFilter (the single callee through which every Field-ordering consumer in the analysis is reached) and recorded on the filter so a comparison parked for that reason is also not handed to the notEquals to notIn merge, which rebuilds its constant from a Field and so cannot carry the discriminator either. Not a widened bound, not a no-random-* tag, not a guard at the point of the wrong answer.
d Test intent preserved / new tests added? Yes. New 05103_redundant_comparisons_dynamically_typed: 7 scenarios, 19 result assertions and 8 plan oracles, no no-* tags. Every arm pins the setting under test and optimize_and_compare_chain, which the runner randomizes, and the file pins enable_analyzer because the pass exists only under the analyzer. No existing test was weakened or removed, and 43 tests in the optimizer and Variant/Dynamic/JSON neighbourhood pass with zero reference churn.
e Both directions demonstrated? Yes, attributed per arm against five binaries. Every wrong shape goes 1 to 0 against its own ground truth (the excluding bound alone, or the same query with the optimization disabled and the merge disarmed). On a pristine base built from the same tree, 11 arms redden. Three mutants pin the rest, each rebuilt on the final source: deleting only the constant-operand half of the predicate reddens exactly one arm; deleting only its Variant self-term reddens exactly the two top-level arms; making the predicate screen every type reddens exactly the four ordinary-type controls and nothing else. No arm is vacuous, and those four controls are what detect the optimization silently ceasing to fire, which no count() arm can see.
f Fix is general across code paths? Yes. All three addComparisonFilter call sites through the shared callee; both Field-ordering consumers (pairwise compareComparisonFilters and the std::map<Field, ComparisonFilterInfo> duplicate and ordered-erase paths); the emission path that would otherwise hand a parked notEquals back to the merge. Because the merge is not gated by optimize_redundant_comparisons, the predicate is evaluated before that setting's early return, so the guard holds with pruning both on and off. The global fold-to-false collapse is vetoed by the empty converted value, which can only forgo the collapse and never fold to a different value. No screen was added inside either always-active set rewrite: a separate divergence exists there which needs no self-typed value at all (it reproduces on plain Array(Float64) with a signed-zero constant, and on String versus FixedString), so that one is the pre-existing set-membership-versus-comparison class of #116852 and #117293 rather than this bug, and #117293 is already editing those exact lines.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Both predicate terms were verified recursive in tree through Array, Tuple, Map, Nullable, LowCardinality and Variant; the hasDynamicStructure self-test is what reaches a plain JSON, whose only children are its declared paths, and the isVariant self-test is what reaches a top-level Variant, since DataTypeVariant::forEachChild yields each alternative and never the Variant itself. Measured at the top level, inside a container, for a Variant of static alternatives, and with the self-typed value on the constant side only. Two boundaries of that last class were measured too: a static Variant constant against an ordinary column has no supertype and throws ILLEGAL_TYPE_OF_ARGUMENT, and a scalar column against a self-typed constant is already held aside by the nullable-result screen. The screen is on the type, so it also fires where the two orders happen to agree, such as Variant(Int64, String), and gives up a fold that was sound there; the measured answer for that pair is 0 on both binaries, so only the fold is forgone.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changes, so no SettingsChangesHistory.cpp entry is due; no new setting, error code, serialization or format change; no experimental gate. The one behaviour change with optimize_redundant_comparisons = 0 is that a self-typed notEquals chain is no longer merged into notIn there, which turns a wrong answer into the correct one (measured 1 to 0 against a ground truth of 0); ordinary types still merge at that setting exactly as before, asserted by a plan oracle.
i Invariants and contracts preserved? Yes. An empty converted value is the established shape for a parked filter and emission reads the original node, so the change can only forgo a fold or a merge, never produce a different value. The flag defaults to false and is now computed for every filter before any early return, so the pruning bucket and the merge always agree on it. The predicate newly runs on the pruning-disabled path, so all three construction sites were checked for a null constant: the only site that can pass that flag guards it with an explicit early continue, and the other two either pick the non-null one of a pair or already dereference it. No lock, allocation, lifetime or concurrency surface: a pure predicate on a DataTypePtr during query analysis, with no error or early-return path that can leave state behind.

Session id: cron:clickhouse-impl-slot-4:20260902-064100

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1bbb49a]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
02346_text_index_transform_access FAIL cidb
05320_promql_duplicate_series_one_to_one_matching NOT_FAILED cidb
05059_promql_empty_by_group NOT_FAILED cidb
05033_lazy_materialization_column_function_structure_equals NOT_FAILED cidb
04353_text_index_explicit_tokenizer_argument NOT_FAILED cidb
05410_time_series_tags_functions_parallel_replicas_expired_context NOT_FAILED cidb
05137_join_fixed_string_zero_bytes_runtime_filter NOT_FAILED cidb
01710_projection_with_mixed_pipeline NOT_FAILED cidb
05234_promql_result_timestamp_scale NOT_FAILED cidb
05076_promql_label_manipulation_label_names NOT_FAILED cidb
1 more test cases not shown

AI Review

Summary

This PR prevents comparison pruning and the notEquals-to-notIn rewrite from losing type-dependent comparison semantics for Variant, Dynamic, and JSON, including nested types and typed constants. Reviewed the current diff and surrounding code at 1bbb49af8bdd819faba4589be37f4e67a4d6e2c3, together with all prior discussion. No actionable findings remain; the previous inline finding about the parallel-replica exclusion is fixed. The new regression test, 05103_redundant_comparisons_dynamically_typed, passes in CI. No local tests were run.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @Avogar, could you review this? optimize_redundant_comparisons decides which of two bounds is redundant by ordering the constants' Field values by type tag, but a Variant, Dynamic or JSON value is compared by its type's place in the name-sorted alternative list before its value, and for Variant(Float64, Int64) those two orders are exactly reversed, so the bound that excludes the row was the one dropped. The same Field blind spot reaches the notEquals-to-NOT IN merge, which that setting does not gate, so the screen is recorded on the comparison rather than applied only on the pruning path.

@zlareb1

zlareb1 commented Sep 2, 2026

Copy link
Copy Markdown
Member

The screen this PR adds also seems to be needed one rewrite over, in tryReplaceOrEqualsChainWithIn in the same file. That rewrite rebuilds the IN set constant as a tuple of raw Fields, and a Field carries no discriminator either — the sentence from the ComparisonFilter comment applies to it verbatim. Its current screens all miss a Variant nested inside a container: hasDynamicStructure is false for a Variant of static alternatives, the lossless-conversion check short-circuits on from_type->equals(*expr_type) for an exactly-typed constant, and the nullable-result screen only catches a top-level Variant (in over Array(Variant(...)) resolves to plain UInt8).

Result is a silently dropped row at pure default settings (default optimize_min_equality_disjunction_chain_length is 3):

CREATE TABLE t (id UInt32, a Array(Variant(Date, UInt64))) ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1, [1::UInt64]);

SELECT count() FROM t
WHERE a = [toDate(1)]::Array(Variant(Date, UInt64))
   OR a = [1::UInt64]::Array(Variant(Date, UInt64))
   OR a = [5::UInt64]::Array(Variant(Date, UInt64));

This returns 0; the correct answer is 1 (the second disjunct is an exact match). The single equals alone returns 1, and setting optimize_min_equality_disjunction_chain_length = 100 returns 1, with EXPLAIN confirming the in rewrite is what fires in the failing case. [toDate(1)] and [1::UInt64] share the identical Field (Array[UInt64(1)]), so the conversion back to Array(Variant(Date, UInt64)) picks one alternative for both set elements, and the UInt64-discriminated stored row no longer matches.

The PR description defers the OR side to #116852/#117293, but those cover only the String/FixedString padding leg (stringFamilyPairIsNotEqualityEquivalent cannot screen a Variant), so this leg survives even after both merge. Since this PR already introduces comparisonOrdersTypeBeforeValue, consulting it in the tryReplaceOrEqualsChainWithIn decline next to the existing hasDynamicStructure check would close the gap cheaply.

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed, on the published head 572a0238 and identically on its pristine base, so pre-existing. Your query answers 0 at defaults and 1 with optimize_min_equality_disjunction_chain_length = 100, with EXPLAIN QUERY TREE showing one in and no surviving equals.

Two additions from the measurement:

  1. The shared Field is not needed. Three distinct constants [1::UInt64], [5::UInt64], [7::UInt64] against a stored [1::UInt64] also answer 0, and 1 with the chain-length control. Rebuilding from a Field re-picks an alternative, so one element is enough.
  2. A top-level Variant is exposed at pure defaults too: b = 1::UInt64::Variant(Date, UInt64) OR b = 5::UInt64::Variant(Date, UInt64) OR b = 7::UInt64::Variant(Date, UInt64) over a UInt64-discriminated row answers 0, control 1. The nullable-result screen catches that shape only at use_variant_default_implementation_for_comparisons = 0.

The root sits below the pass:

SELECT materialize([1::UInt64]::Array(Variant(Date, UInt64))) =  [1::UInt64]::Array(Variant(Date, UInt64));  -- 1
SELECT materialize([1::UInt64]::Array(Variant(Date, UInt64))) IN ([1::UInt64]::Array(Variant(Date, UInt64)),
                                                                  [5::UInt64]::Array(Variant(Date, UInt64))); -- 0

x IN (x, ...) is already false with no chain and no rewrite, so a screen in tryReplaceOrEqualsChainWithIn keeps the pass from manufacturing a wrong IN but leaves a hand-written one wrong. in refuses Array(Dynamic) with Code: 43, and Variant is refused in GROUP BY and ORDER BY with Code: 44 unless allow_suspicious_types_in_* is set, while Array(Variant(...)) in a set is silently wrong.

Your reading of #117293 checks out: stringFamilyPairIsNotEqualityEquivalent recurses through its Array branch to Variant against Variant, matches no tuple, array or map branch, fails the string leaf and returns false. The description cites those two only for the separate accurateEquals divergence; that sentence reads both ways, so I have tightened it.

comparisonOrdersTypeBeforeValue is not reusable at that site as it stands. A single-alternative Variant is measurably unaffected, Variant(UInt256) and Array(Variant(UInt256)) both answering correctly either way, and 04628_logical_optimizer_in_rewrite_variant_type records that exact shape still being rewritten, on the stated ground that the guard must key on the drift and not on the type. The predicate is true for it, so consulting it there flips that assertion.

I am therefore opening this separately rather than folding it in: the mechanism is alternative re-selection on a Field round trip rather than comparison order, the screen needs its own shape, and it should take a position on a self-typed value in a set and not only on the rewrite. That also keeps it off the lines #117293 changes. I will link it here when it opens.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1bbb49af8 with master c50de3b98 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 10 s compile time in total, 7 of them have a recent master baseline.

Job report

`Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)`
fails the new test deterministically with

    Code: 70. Cannot convert type UInt8 to Variant(Float64, Int64).
    Conversion to Variant allowed only for types from this Variant

A secondary server receives the query as text, and a folded constant is printed
as a bare literal: an `Int64` 2 becomes `2`, which re-parses as `UInt8`, and the
internal `_CAST` back to `Array(Variant(Float64, Int64))` refuses a type that is
not one of the alternatives.

This is the case ClickHouse#111136 deliberately left open. That pull request fixed the same
error for a scalar `Variant` constant, by casting the literal to the exact member
type first in `ConstantNode::toASTImpl`, and its description records that
constants of `Variant` type nested inside compound constants are not covered by
it. Measured on 26.9 through a plain distributed query, so no parallel replicas
and no table are needed:

    SELECT 42::UInt64::Variant(UInt64, String)
      FROM remote('127.0.0.1:PORT', system.one) SETTINGS prefer_localhost_replica = 0;
    -- 42

    SELECT [42::UInt64]::Array(Variant(UInt64, String))
      FROM remote('127.0.0.1:PORT', system.one) SETTINGS prefer_localhost_replica = 0;
    -- Code: 70

The arm that fails sets `optimize_redundant_comparisons = 0`, so the analysis this
pull request changes never runs on it. Against a local three-replica rig built
from the arm's own two config files, that arm serializes the identical remote
query and raises the same error on the published head and on its pristine base.

No choice of constants avoids it here. The property under test is a constant
whose discriminator cannot be recovered from its `Field`, which is exactly what
the text round trip drops, so a constant that survives the round trip is a
constant that no longer arms the test.

`no-parallel-replicas` is the existing marker for this, and 484 stateless tests
carry it, including `04628_logical_optimizer_in_rewrite_variant_type` (the sibling
test for the `IN` rewrite in this same pass) and
`04105_key_condition_nested_lc_variant`. It skips the file on the ParallelReplicas
arm and forces `enable_parallel_replicas = 0` elsewhere, so every other arm keeps
running it unchanged. Verified both directions: tagged, the arm's own invocation
reports `SKIPPED` and an ordinary run reports `OK` even against a server whose
default profile enables parallel replicas; with the tag line removed and nothing
else changed, both invocations fail with the error above.

Related: ClickHouse#111136
Related: ClickHouse#74366

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

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI fix pushed: no-parallel-replicas on the new test

Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) failed the new test on
3 of 3 reruns with Code: 70. Cannot convert type UInt8 to Variant(Float64, Int64). A secondary
server receives the query as text, and a folded constant prints as a bare literal: an Int64 2
becomes 2, re-parses as UInt8, and the internal _CAST back to Array(Variant(Float64, Int64))
refuses a type that is not one of the alternatives.

This is the case #111136 left open. It fixed the same error for a scalar Variant constant, and its
description records that constants of Variant type nested inside compound constants are not covered
by it. On 26.9, with a plain distributed query and no table:

SELECT 42::UInt64::Variant(UInt64, String)
  FROM remote('127.0.0.1:9000', system.one) SETTINGS prefer_localhost_replica = 0;   -- 42

SELECT [42::UInt64]::Array(Variant(UInt64, String))
  FROM remote('127.0.0.1:9000', system.one) SETTINGS prefer_localhost_replica = 0;   -- Code: 70

The failing arm sets optimize_redundant_comparisons = 0, so the analysis this pull request changes
never runs on it. Against a local three-replica rig built from that job's own two config files, the
arm serializes the identical remote query and raises the same error on this head and on its pristine
base, so the limitation is pre-existing here.

No choice of constants avoids it: the property under test is a constant whose discriminator cannot be
recovered from its Field, which is exactly what the text round trip drops, so a constant that
survives the round trip no longer arms the test. The sibling test for the IN rewrite in this same
pass, 04628_logical_optimizer_in_rewrite_variant_type, carries the same tag. Verified both
directions: tagged, that job's own invocation reports SKIPPED and an ordinary run reports OK even
against a server whose default profile enables parallel replicas; with the tag line removed and
nothing else changed, both invocations fail with the error above.

I am tracking the nested-constant case separately and will link the fix here when it opens.

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e4aa9fec9206a11e1755d0d7e13b1798b1ec3774

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
Parser memory check / Resolve master binary No master ``clickhouse-examples`` artifact was found. #110081 dropped the suppression of the workflow segment in the S3 prefix, so ci/jobs/parser_memory_check.py probes a hand-spelled REFs/master/<sha>/build_arm_release/ key that now 403s on every master sha it walks. CI-infra, and this diff touches no ci/ file: over 24 h the check reports error on 170 distinct pull requests against 17,271 success rows, and 0 on master #117701 (mine, merged 2026-09-02T16:49:23Z), rule 3c: measured ABSENT from this tree (0 occurrences of the symbol it adds at e4aa9fec9206, 1 at its merge commit d4f4f2a50e0f, pre-fix control 0)
LLVM Coverage / Generate LLVM Coverage Diff Report, Print Uncovered Code the same S3 prefix change at the coverage call site: the baseline lookup and the report links are hand-spelled the same way. 606 failure rows across 96 distinct pull requests in 24 h, 0 on master #117718 (external, open)
Stress test (amd_msan) / Hung check failed, possible deadlock found one cancelled INSERT left in the processlist, no victims and no convoy. hung_check.log gives query_kind: Insert, is_cancelled: 1, elapsed: 1263.96, written_rows: 65537, carrier log_comment: 03464_projections_with_subcolumns.sql, and the stuck thread sits in the MergeTree write path (MergeTreeDataPartWriterWide, writeColumn, MergeTreeSink). So a raised cancellation is not honored inside the column write, which no analyzer change can reach. Breadth puts it outside this diff: 22 rows on 18 distinct pull requests plus 2 master runs in 14 d for this parametrization alone (159 rows over 12 Stress test flavours). It is not the h3 polygon family: query_kind is Insert, not Select, and there is no pointInPolygon or iterStepPolygon frame #108357 (external, open)

I am not merging master to pick #117701 up in this tick. Mergeable Check gates on all three rows
and two of the owners are still open, so a rerun now cannot make this head green. One later update
collects them instead of spending two CI cycles.

The praktika report has 0 DROPPED nodes of 175, so this is real signal and not a build-gate
cascade: 148 OK, 19 SKIPPED. My diff is src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp
plus one stateless test.

Session id: cron:our-pr-ci-monitor:20260902-220000

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

The nested-constant case is fixed in #117831: a Variant constant below the top level of a compound constant now names its active member type per element, so Array(Variant(...)) survives serialization to a secondary server. That PR does not assert anything about the no-parallel-replicas tag added here, which needs its own measurement.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

The follow-up I promised in #117637 (comment) is open: #117959.

It stops the OR-to-IN rewrite from re-selecting a Variant alternative, by carrying each constant into the tuple as its own column and by refusing the rewrite where the constant and the expression are not a named identity. The serialization half stays with #117831.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
groeneai and others added 2 commits September 23, 2026 12:56
One conflict, in `src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp`.
Master's 66a9b39 ("Keep detecting an always-false equals chain when
comparison pruning is off") deleted the early `if (!enable_pruning)` return at
the top of `addComparisonFilter`, which is where this branch sets
`orders_type_before_value`. Kept the assignment and took master's deletion: the
flag is still computed for every filter before any keep-opaque guard, which is
what the `notEquals` to `notIn` merge needs, since it reads `opaque_filters` in
both pruning modes.

The self-typed screen therefore now also sits above master's new
disabled-pruning `equals` contradiction check, and keeps a self-typed comparison
out of it. That is the direction that cannot invent a result: with pruning off
the new block only ever collapses an AND to false, and it decides that through a
`Field`, which carries no discriminator, so for a value that orders by its type
first the only safe answer is to leave the conjuncts alone. Master's own stated
invariant for that block is that it inherits every guard above it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Every `optimize_redundant_comparisons = 1` arm was labelled `chain pruned`,
which names the setting rather than the outcome and reads as the opposite of
what the arm proves: each one is there because a self-typed comparison is not
pruned. Its `= 0` twin was labelled `chain kept`, which is true of both arms and
so distinguishes neither. The plan arm that counts zero `notIn` nodes was
labelled `notIn merges` for the same reason, next to a `notIn skipped with
pruning off` arm asserting the same zero.

Labels only, in the test this pull request adds. Every expected count is
unchanged and all 27 labels stay distinct; corrupting one reference label still
fails the test, and restoring it passes.

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

Copy link
Copy Markdown
Collaborator Author

Merged master: the conflict was with 66a9b39, and the resolution has one consequence worth stating

66a9b39 ("Keep detecting an always-false equals chain when comparison pruning is off", #121007 /
#121012) deleted the early if (!enable_pruning) return at the top of addComparisonFilter, which is
where this branch sets orders_type_before_value. I kept the assignment and took the deletion, so the
flag is still computed for every filter before any keep-opaque guard, which is what the notEquals to
notIn merge needs: it reads opaque_filters in both pruning modes.

The consequence is that the self-typed screen now also sits above that new disabled-pruning equals
contradiction check, and keeps a self-typed comparison out of it. With pruning off that block only
ever collapses an AND to false, and it decides that through a Field, which carries no discriminator,
so for a value that orders by its type first, declining is the only answer that cannot invent a
result. Its own stated invariant is that it inherits every guard above it.

Re-measured on today's master: the Array(Dynamic) chain still returns 1 where the single excluding
bound returns 0. On the merged head it returns 0, and 05103, 05230, 04628 and the three
04032_and_comparison_filter* tests pass locally.

Also renamed the arm labels in the new test. Every optimize_redundant_comparisons = 1 arm was called
chain pruned, which names the setting rather than the outcome and reads as the opposite of what the
arm proves; counts and oracles are unchanged.

The tag was added because a `Variant` constant nested inside a container did not
survive the query-text round trip to a secondary server: the folded `Field`
printed as a bare literal, the replica re-parsed it as a different type, and the
internal `_CAST` back to the `Variant` refused it.

ClickHouse#117831 fixed exactly that case and is now merged into this branch, so the
analyzer names the member type per element. The remote query for the
`Array(Variant(Float64, Int64))` arms now reads

    _CAST(array(_CAST(_CAST(2, 'Int64'), 'Variant(Float64, Int64)')), 'Array(Variant(Float64, Int64))')

where it previously read `_CAST([2], 'Array(Variant(Float64, Int64))')`.

Measured on the failing CI arm's own cluster configuration: with the tag removed
the test passes 10/10 runs with parallel replicas enabled by the profile, and 5/5
under the runner's `--no-parallel-replicas` flag, against the unchanged
reference. Parallel replicas is engaged rather than skipped: 58 secondary
queries, the `Array(Variant)` chain itself executed on a replica, and
`ParallelReplicasUsedCount` set on 36 queries. As a positive control, the
pre-ClickHouse#117831 bare-literal form still fails `Code: 70` through the same carrier, so
the test passes because of the serialization fix and not because the remote path
went dead.

Dropping the tag puts this regression back under parallel-replica runs. The
rationale paragraph goes with it, since it describes a defect that is now fixed.

Co-Authored-By: Claude Opus 5 <[email protected]>
Resolve the conflict with ClickHouse#113470, which declines a `Variant` expression in
`addComparisonFilter`: the one screen is now `comparisonOrdersTypeBeforeValue`,
which also covers `Dynamic` and `JSON` and a self-typed constant, and also keeps
such a `notEquals` out of the `notIn` merge (on master an `Array(Variant(Date,
UInt64))` chain still answers 1 there at defaults, where the answer is 0).

Port the predicate from the removed `IDataType::forEachChild` (ClickHouse#119118) to
`anyInTypeTree`, and use `getComparisonFilterExpressionNode` for the expression
type, as the key is now a template parameter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1bbb49a

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
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 02346_text_index_transform_access fails only in the plan-based job, on 7 unrelated PRs since 2026-11-19; the test fix merged after this run started #133095 (external, merged)

Session id: cron:our-pr-ci-monitor:20261120-030037

This branch has not been deployed

No deployments
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-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants