Repository navigation
Optimize AND comparison chains: detect conflicts, prune redundancies - #99736
Conversation
…chaining and reorder passes to detect transitive equality conflicts
…ains in LogicalExpressionOptimizerPass
|
Workflow [PR], commit [b5d858e] Summary: ✅
AI ReviewSummaryThis PR extends Findings❌ Blockers
Tests
Final VerdictStatus: |
e73fa86 to
37402ba
Compare
nihalzp
left a comment
There was a problem hiding this comment.
Thanks for working on it!
Let's place the optimization behind a setting which we can enable by default.
After the setting is added, let's duplicate the changed queries in the existing tests once with setting on and once with setting off. This will make sure we do not lose coverage.
|
Additionally, you may look at PR #98516 which contains some ideas that can be reused to improve cross-type comparison. |
…parisons in `LogicalExpressionOptimizerPass`
…on chain analysis
…story and disable it in 01625 constraint test
…ces to single operand
|
Hi @nihalzp, thanks for the suggestions! |
| SELECT 'eq_eq_same'; | ||
| SELECT * FROM 04032_t WHERE i = 3 AND i = 3 ORDER BY i SETTINGS optimize_and_compare_chain_pruning = 0; | ||
| SELECT * FROM 04032_t WHERE i = 3 AND i = 3 ORDER BY i SETTINGS optimize_and_compare_chain_pruning = 1; | ||
| EXPLAIN QUERY TREE SELECT * FROM 04032_t WHERE i = 3 AND i = 3 SETTINGS optimize_and_compare_chain_pruning = 0; |
There was a problem hiding this comment.
Instead of using EXPLAIN QUERY TREE, let's use EXPLAIN SYNTAX run_query_tree_passes = 1 which will give us a more concise output while still showing us that optimization is applied.
There was a problem hiding this comment.
Hi @nihalzp, I’ve switched to using EXPLAIN SYNTAX run_query_tree_passes = 1 per request. A single CI error is present but not related to this change.
|
Updated the branch with the latest |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 594/621 (95.65%) · Uncovered code |
…r single-record `EXPLAIN SYNTAX` These tests were added on master (#99736) with the pre-flip one-record-per-line output. Regenerated from the merged binary; the output is byte-identical to the old references after unescaping the embedded newlines. Co-Authored-By: Claude Fable 5 <[email protected]>
…nstants
`tryConvertToColumnType` converts a comparison constant to the column type with a
strict (lossless) conversion and lets the chain pruning fold/prune only when the
conversion succeeds. `strict` is supposed to reject any lossy conversion by returning
a null `Field`, but `convertFieldToType` does not honour that for `DateTime64`/`Time64`
scale reduction: it silently truncates a higher-scale value to a lower scale (e.g.
`1.23` of scale 2 becomes `1.2` of scale 1).
As a result the optimizer folded a comparison chain using a value different from the
original constant, changing query results versus the unoptimized query. For a
`DateTime64(1)` column,
`dt = toDateTime64('1970-01-01 00:00:01.20', 1) AND dt != toDateTime64('1970-01-01 00:00:01.23', 2)`
collapsed both constants to `1.2`, detected `equals` vs `notEquals` as a contradiction,
and folded the whole `AND` to `false` — dropping the row `1.20`, which must be kept
because `1.20 != 1.23`. The setting is enabled by default, so this affected results
silently.
Guard `tryConvertToColumnType` by requiring the strict conversion to be exactly
reversible, checked only for decimal-backed results (`DateTime64`/`Time64`/`Decimal`)
where this truncation can occur, leaving the already-correct string/integer/float
conversions untouched. Lossless finer-scale constants (e.g. `1.20` of scale 2 in a
`DateTime64(1)` column) are still optimized.
Addresses an unresolved review finding on
ClickHouse#99736
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…_redundant_comparisons Address the AI review Major on `LogicalExpressionOptimizerPass.cpp:422`: the round-trip reversibility guard in `tryConvertToColumnType` is the correctness barrier for several lossy `strict` conversions, but the existing regressions only cover `DateTime64` scale reduction (`04489`) and `DateTime` -> `Date`/`Date32` (`04498`). This adds `04499_redundant_comparisons_lossy_conversions` with focused `optimize_redundant_comparisons = 0/1` equivalence tests for the remaining guarded surfaces: - `Time64` scale reduction, - `DateTime64` -> `Date`/`Date32` truncation, - `Float64` -> `Float32` narrowing. Each scenario asserts the same result with the optimization enabled and disabled: the lossy "keep the row" cases stay at their unoptimized result (the guard skips the fold), while the lossless cases still fold. Verified locally against a build of this branch. Review: ClickHouse#99736 (comment)
The pairwise scan in `addComparisonFilter` compared each incoming filter against every surviving filter of the same expression. For a chain `x != c1 AND x != c2 AND ... AND x != cN` every distinct pair compares as NONE, so nothing is pruned and the scan is O(N^2) — roughly 50M `compareComparisonFilters` calls for 10k machine-generated exclusions under the default-on `optimize_redundant_comparisons`, before the linear `NOT IN` rewrite is reached. Split the per-expression storage by how filters participate in the analysis: equals/range filters keep the pairwise scan (they are self-pruning and stay at a couple of elements), notEquals filters live in a `std::map` keyed by their converted value (duplicate detection in one ordered lookup, a range predicate erases exactly the values it excludes, each value at most once), and non-lossless or NaN constants are stored aside since they never interact. Rewrites are unchanged; analysis of 10k/20k/40k chains now takes 0.56s/1.01s/1.99s wall (linear, within 1-2% of pruning disabled). ClickHouse#99736 Co-Authored-By: Claude Fable 5 <[email protected]>
The comments justified excluding non-deterministic expressions from comparison-chain pruning by claiming that syntactically identical calls such as `rand() % 2` are independent evaluations that may differ within a row. That contradicts the documented common subexpression elimination rule: expressions with the same AST are considered to have identical values and executed once. Reword the comments so the exclusion is described as a conservative choice not to rely on that folding, rather than resting on an incorrect premise. No behavior change. Per review comment: ClickHouse#99736 (comment) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`compareComparisonFilters` wrapped its body in a `try`/`catch (const Exception &)` that returned `NONE` on any exception, on the assumption that `accurateLess`/`accurateEquals`/`accurateLessOrEqual` might throw on incompatible `Field` types. That cannot happen here: both operands are `converted_value`, i.e. the constant converted to the same expression type, so the two fields always have the same type. `FieldVisitorAccurateLess`/`FieldVisitorAccurateEquals` handle equal-typed fields in their `std::is_same_v<T, U>` branch and only throw `BAD_TYPE_OF_FIELD` for genuinely incompatible type pairs, which do not arise. The `catch` was therefore inert and only masked would-be real errors. Drop the block so any unexpected comparison failure surfaces instead of being silently swallowed. No behavior change. Per review comment: ClickHouse#99736 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…mpare Optimize AND comparison chains: detect conflicts, prune redundancies
…s off `optimize_redundant_comparisons` (new in 26.7, ClickHouse#99736) gates the whole of `addComparisonFilter` behind an early return at the top of the function: with the setting off, every operand is parked in `opaque_filters` unanalysed, so the function never returns ALWAYS_FALSE, `found_conflict` is never set, and the AND is never collapsed to a constant false. Detecting that two `equals` on the same expression carry different values is older than that setting. `v26.6.1.1193-stable` calls `tryOptimizeAndEqualsNotEqualsChain` with no setting gate at all, and declares no `optimize_redundant_comparisons` (grep -c = 0); ClickHouse#99736 deleted that function and folded its contradiction check into the new, gated analysis. Since the setting is recorded in the 26.7 block of SettingsChangesHistory.cpp, every `compatibility` below 26.7 now removes a fold that 25.12 genuinely performed, and a query whose WHERE is always false executes its full plan. On the reported reproducer that is a LEFT JOIN onto an `argMax ... GROUP BY` subquery over 2.2M rows: 2,200,000 rows read where 0 are needed, 51 ms -> 3641 ms on the customer's data. So detect that one contradiction regardless of the setting, and leave pruning, boundary folding and strengthening (all genuinely introduced with it) gated. Neutralizing the history entry instead would be wrong: v26.7.1.1315-stable both ships the setting and records it in its own newest block, so the placement is correct, and that route also leaves an explicit `optimize_redundant_comparisons = 0` regressed. Why comparing against a single stored representative is equivalent to a full pairwise scan, which is what keeps the disabled path linear in the operands of the AND: the only question asked is whether two `equals` on this expression carry different values, every `equals` is compared against the representative, and `found_conflict` is only ever set, never cleared. The representative is recorded as a position rather than a pointer or iterator because `opaque_filters.push_back` reallocates; in disabled mode that vector only ever grows, since no erase path reaches it. The new block sits below every existing keep-opaque guard (nullable result, non-lossless conversion, NaN constant), so the disabled path is a strict subset of the enabled one and inherits any guard added above it, and it reaches the collapse through the single existing `found_conflict` site, so that site's non-convertible-operand veto still keeps a TYPE_MISMATCH the unoptimized query would raise from being suppressed. For EQUALS vs EQUALS `compareComparisonFilters` returns only PRUNE_RIGHT or ALWAYS_FALSE, never a STRENGTHEN_*, so nothing is mutated on this path. Three narrowings are deliberate. A duplicate `a = 1 AND a = 1` is still not deduplicated with pruning off, although 26.6 dropped it: that is pure evaluation cost with no result change. A non-convertible constant (`Int32 a = 3 AND a = 3.5`) still does not fold, because reusing the enabled path's lossless-conversion requirement is what keeps 26.6's wrong result for `Float64 a = 1 AND a = 1.0` away. And a contradiction `optimize_and_compare_chain` derives now folds the AND with pruning off, which is what its appended plain conjunct is for; 26.6 never derived one. Twelve reference lines change across the three 04032* files, every one an `optimize_redundant_comparisons = 0` case holding two `equals` on the same expression with different, losslessly convertible values. Closes: ClickHouse#121007 Closes: ClickHouse#121012 Co-Authored-By: Claude Opus 5 <[email protected]>
…-shifted bound Issue ClickHouse#121954 reports a valid query rejected at default settings with "Code: 43. No operation lessOrEquals between String and DateTime64(3)". The filter equates a String column with a date-like literal and also bounds a Date column by that same literal and by an interval-shifted one, so the AND chain derived a comparison between the String column and the DateTime64 upper bound, which no ordering supports. The defect is already fixed. Measured on the official builds through one byte-identical clickhouse local harness: Code 43 on 26.3.33.24 and 26.6.5.73, and 33 on 26.7.6.57, 26.8.2.7 and master 26.10.1.1. The change that closed it is d4c0509 in ClickHouse#99736 (merged 2026-07-20, first shipped in 26.7), which stopped the chain walk recursing through a constant intermediate node; the '2026-09-02' literal shared by the two conjuncts is exactly such a node. Master additionally carries ClickHouse#110621's ordering domains, which is why no single-line mutation on master can red this test and why the pre-fix red is taken from released code instead. Arm 1 is the reporter's query verbatim and the only arm that reds pre-fix. Arm 2 repeats it with optimize_and_compare_chain = 0, the reporter's own control. Arm 3 pins bound preservation: its rows sit one day past the interval-shifted bound and must be excluded, which catches a regression that drops the upper-bound conjunct. Both controls also pass on 26.6.5.73. The explicit SET optimize_and_compare_chain = 1 is load-bearing: clickhouse-test's SettingsRandomizer draws that setting off with probability 0.05 per run, and a run that drew it off would exercise nothing while still printing the expected counts. Of the branches still supported, only the 26.3 LTS carries the defect: Code 43 on 26.3.33.24 as well. Release coverage there would be a backport of ClickHouse#99736 rather than this test, so it is not carried here. A further arm pins the pass being live on the reporter's own chain rather than the fix. Results alone stay equal if the pass stops deriving anything, and an edge whose comparison domain is declined is dropped from the chain graph, so no walk happens and the counts do not move. The arm adds the same-domain edge c2 >= c3 to the reporter's chain, which gives it one legitimate transitive conjunct while the String column stays in its own domain, and compares the enabled and disabled trees by exact node count. It is a vacuity guard, not a second reproducer. Related: ClickHouse#121954 Related: ClickHouse#99736
Resolved #90081
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Optimize AND chains with multiple comparison conditions on the same expression: detect contradictions (e.g.,
a < 3 AND a > 5→false), prune redundant conditions (e.g.,a = 3 AND a < 5→a = 3).Documentation entry for user-facing changes
Summary
Extend
LogicalExpressionOptimizerPassto analyze and simplify AND chains of comparison conditions on the same expression (e.g.,a = 3 AND a < 5 AND a != 7). The optimizer now detects contradictions (rewrites tofalse), prunes redundant conditions, and handles cross-type constant comparisons viaconvertFieldToTypeStrict.Optimizations and fixes
i = 3 AND i < 5i = 3i = 3 AND i < 2falsei = 3 AND i != 5i = 3i = 3 AND i != 3falsei != 3 AND i < 3i < 3i < 5 AND i < 3i < 3i < 3 AND i >= 3falsei = 3 AND i = 3.0i = 3x = 3 AND x = y AND y = 5falsex < 3 AND y > 3 AND y < 10