Skip to content

Optimize AND comparison chains: detect conflicts, prune redundancies - #99736

Merged
alexey-milovidov merged 102 commits into
ClickHouse:masterfrom
wudidapaopao:optimize_and_compare
Jul 20, 2026
Merged

alexey-milovidov merged 102 commits into
ClickHouse:masterfrom
wudidapaopao:optimize_and_compare

Conversation

@wudidapaopao

@wudidapaopao wudidapaopao commented Mar 17, 2026 •

Copy link
Copy Markdown
Contributor

Resolved #90081

Changelog category (leave one):

  • Improvement

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

  • Documentation is written (mandatory for new features)

Summary

Extend LogicalExpressionOptimizerPass to 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 to false), prunes redundant conditions, and handles cross-type constant comparisons via convertFieldToTypeStrict.

Optimizations and fixes

Category Example Before After
equals + range prune i = 3 AND i < 5 kept i = 3
equals + range conflict i = 3 AND i < 2 kept false
equals + notEquals prune i = 3 AND i != 5 kept i = 3
equals + notEquals conflict i = 3 AND i != 3 kept false
notEquals implied by range i != 3 AND i < 3 kept i < 3
range tightening i < 5 AND i < 3 kept i < 3
empty range detection i < 3 AND i >= 3 kept false
cross-type lossless i = 3 AND i = 3.0 false i = 3
transitive conflict x = 3 AND x = y AND y = 5 kept false
transitive redundant chain x < 3 AND y > 3 AND y < 10 redundant x < 10 added no redundant inference

@clickhouse-gh

clickhouse-gh Bot commented Mar 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b5d858e]

Summary: ✅


AI Review

Summary

This PR extends LogicalExpressionOptimizerPass with optimize_redundant_comparisons, integer-boundary folding, range tightening, contradiction detection, and a large regression-test suite. The pruning logic is substantially improved, but two blocker-level behavior regressions remain: the new folds still assume compared expressions are exception-free, and they can erase evaluations that the original AND must perform. Status: ⚠️ Request changes.

Findings

❌ Blockers

  • [src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp:906] The new boundary-fold path can drop the only evaluation of a deterministic expression that may throw. tryFoldBoundaryOrRewriteFloatForIntColumn returns ALWAYS_TRUE / ALWAYS_FALSE before the original operand is kept anywhere, so a query like WHERE toUInt8(s) < 300 AND 1 can stop throwing under optimize_redundant_comparisons = 1 even though it still throws with the optimization off. The guard currently skips only non-deterministic expressions; it also needs to reject expressions whose evaluation can still raise.
  • [src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp:1966] Once any contradiction is found, the pass still replaces the whole AND with 0 without proving that earlier or sibling non-comparison operands are safe to erase. That is a real semantic change for new contradiction shapes introduced by this PR: e.g. WHERE toUInt8(s) AND i < 0 AND i > 10 now folds to 0, suppressing the exception from the first operand even though the unoptimized query must evaluate it first. Folding to constant false needs the same kind of “nothing we are dropping can throw” proof, not just the current converted_value check for non-convertible constants.
Tests
  • ⚠️ Add a focused stateless repro where the throwing operand appears before the foldable comparison, for example match(dictGetString(...), '[unclosed') AND id < 0 or toUInt8(s) AND i < 0 AND i > 10. The current suite covers non-convertible constants and the already-short-circuiting id < 0 AND match(...) order, but it does not prove that the new pruning preserves exception behavior when the dropped operand would have been evaluated first.
Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 17, 2026
@wudidapaopao
wudidapaopao force-pushed the optimize_and_compare branch from e73fa86 to 37402ba Compare March 17, 2026 14:23
@nihalzp nihalzp self-assigned this Mar 18, 2026

@nihalzp nihalzp 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.

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.

@nihalzp

nihalzp commented Mar 18, 2026

Copy link
Copy Markdown
Member

Additionally, you may look at PR #98516 which contains some ideas that can be reused to improve cross-type comparison.

@wudidapaopao

wudidapaopao commented Mar 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @nihalzp, thanks for the suggestions!
I've incorporated ideas from PR #98516 and added float-to-int conversions and early pruning when integer values fall outside the range.
I also introduced a new setting optimize_and_compare_chain_pruning (enabled by default) and duplicated the test queries with the setting both on and off.

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;

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

Updated the branch with the latest master (merge commit b5d858ec66c, clean auto-merge — GitHub reported the PR as conflicting, but no textual conflicts remained after the previous reconciliation of tryConvertFieldToType). Verified locally: full clickhouse binary builds, the settings-changes history contains only this PR's optimize_redundant_comparisons entry (no orphans), compatibility='25.8' correctly resets the setting, and all 9 related stateless tests pass via clickhouse local. The only real CI failure on the previous head was 03915_exchange_tables_race (server abort on Arguments of 'multiply' have incorrect data types), which is the known flaky race #110133 with a fix in progress in #110048 — unrelated to this PR.

@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.10% 86.20% +6.10%
Functions 91.00% 92.10% +1.10%
Branches 72.20% 78.20% +6.00%

Changed lines: Changed C/C++ lines covered: 594/621 (95.65%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 20, 2026
Merged via the queue into ClickHouse:master with commit 46d3337 Jul 20, 2026
179 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 20, 2026
alexey-milovidov added a commit that referenced this pull request Jul 21, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…_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)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…mpare

Optimize AND comparison chains: detect conflicts, prune redundancies
pull Bot pushed a commit to sjoerd2025/ClickHouse that referenced this pull request Sep 23, 2026
…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]>
evillique pushed a commit to evillique/ClickHouse that referenced this pull request Sep 24, 2026
…-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
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-improvement Pull request with some product improvements 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.

Redundant filter removal

7 participants