Repository navigation
Conversation
`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]>
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 ❌ Blocker, fixed: the screened comparison could still reach the ❌ Blocker, fixed: that same guard was bypassable with
❌ Fixed in the description: three claims that did not hold. An earlier draft said the fold is 💡 Noted, not blocking: an unmeasured claim was cut. The description asserted that the 💡 Noted, not blocking: seven test labels read as the opposite of what they assert. Arms named 💡 Noted, not blocking. Parking the filter leaves its converted value empty, which also vetoes the Disagreed, with evidence:
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260902-064100 |
|
Workflow [PR], commit [1bbb49a] Summary: ❌
AI ReviewSummaryThis PR prevents comparison pruning and the Final VerdictStatus: ✅ Approve |
|
cc @yakov-olkhovskiy @Avogar, could you review this? |
|
The screen this PR adds also seems to be needed one rewrite over, in Result is a silently dropped row at pure default settings (default 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 The PR description defers the OR side to #116852/#117293, but those cover only the |
|
Confirmed, on the published head Two additions from the measurement:
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
Your reading of #117293 checks out:
I am therefore opening this separately rather than folding it in: the mechanism is alternative re-selection on a |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 10 s compile time in total, 7 of them have a recent master baseline. |
`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]>
CI fix pushed:
|
CI finish ledger -
|
| 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
|
The nested-constant case is fixed in #117831: a |
|
The follow-up I promised in #117637 (comment) is open: #117959. It stops the |
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]>
Merged master: the conflict was with 66a9b39, and the resolution has one consequence worth stating66a9b39 ("Keep detecting an always-false equals chain when comparison pruning is off", #121007 / The consequence is that the self-typed screen now also sits above that new disabled-pruning Re-measured on today's master: the Also renamed the arm labels in the new test. Every |
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]>
CI finish ledger - 1bbb49aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261120-030037 |
Related: #113470
Related: #117595
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when an
ANDchain compares aDynamicorJSONvalue at any depth (for exampleArray(Dynamic)), or chains!=conditions on aVariantnested in a container. Such a value is ordered by its type before its value, which neitheroptimize_redundant_comparisons(enabled by default since 26.7) nor aNOT INset can express, so a condition that excludes a row could be dropped and the row returned. TheNOT INmerge is not gated by that setting.Description
optimize_redundant_comparisonsprunes a comparison implied by another on the same expression, ordering the constants'Fieldvalues by type tag. AVariant,DynamicorJSONvalue carries its own type, andIColumn::compareAtorders 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 aVariantexpression. This PR widens that one screen (comparisonOrdersTypeBeforeValue) toDynamicandJSONat any depth and to a constant operand that carries its own type, and keeps such anotEqualsout of thenotInmerge, whose set rebuilds its constants fromFields 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-levelJSONand anArray(UInt64)column against anArray(Dynamic)constant behave the same. WithArray(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 oneField, so the pass drops one as a duplicate. On master, which keeps both since #113470, the chain is merged intonotInand 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]