Skip to content

Fix unsafe transitivity in optimize_and_compare_chain - #110621

Merged
yariks5s merged 12 commits into
masterfrom
fix/optimize-and-compare-chain-domains
Jul 29, 2026
Merged

yariks5s merged 12 commits into
masterfrom
fix/optimize-and-compare-chain-domains

Conversation

@yariks5s

@yariks5s yariks5s commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

Restrict inferred comparison chains to native-number and String domains so pair-specific conversions cannot produce invalid predicates.

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

Fix wrong query results from the optimize_and_compare_chain optimization (enabled by default): a condition derived by transitivity from a < b AND b < c could use different comparison semantics than the original conditions when the chain mixes types with pair-specific conversion rules (e.g. Enum vs String, Decimal vs Float64, FixedString of different widths). Transitive conditions are now derived only within groups of types sharing a single comparison order.

Version info

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

Restrict inferred comparison chains to native-number and `String` domains so pair-specific conversions cannot produce invalid predicates.
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4bc3860]

Summary: ✅


AI Review

Summary

This PR narrows optimize_and_compare_chain to comparison domains whose ordering stays stable across the whole chain, then explicitly re-enables safe cases such as same-scale DateTime64/Time64/Decimal, FixedString, exact-type comparisons, and const-string edges normalized to the counterpart type. I did not find a remaining code-level correctness issue in the current head after checking the live diff, the added tests, and every existing review thread; the only outstanding problem is the required changelog text.

PR Metadata
  • Changelog category: Bug Fix is correct for a default-on optimizer producing wrong results or analysis-time exceptions.
  • Changelog entry: required for Bug Fix, but the current entry does not satisfy the template. It is developer-facing, overly long, and ends mid-sentence instead of giving one user-readable release note.
  • Suggested replacement: Fixes incorrect filtering in the default-on optimize_and_compare_chain analyzer pass when chained comparisons mix types or string literals that use different coercion rules.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 15, 2026
yariks5s and others added 5 commits July 17, 2026 17:16
Teach `FunctionComparison` to expose a closed comparison-order domain and make `LogicalExpressionOptimizerPass` carry it through inferred chains. Comparisons with pair-dependent conversions now fail closed, while native numbers, strings, dates, and equal-scale time points retain the optimization.

Related: #110621
…mpare-chain-domains

# Conflicts:
#	src/Analyzer/Passes/LogicalExpressionOptimizerPass.cpp
Comment thread src/Functions/FunctionsComparison.h Resolved
Comment thread src/Functions/FunctionsComparison.h Resolved
Comment thread src/Functions/FunctionsComparison.h Resolved
Comment thread src/Functions/FunctionsComparison.h Resolved

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

LGTM! Clean fix.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 181/191 (94.76%) · Uncovered code

Full report · Diff report

@yariks5s
yariks5s added this pull request to the merge queue Jul 29, 2026
Merged via the queue into master with commit b7aeb78 Jul 29, 2026
351 of 353 checks passed
@yariks5s
yariks5s deleted the fix/optimize-and-compare-chain-domains branch July 29, 2026 11:41
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 29, 2026
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
feiyunwill pushed a commit to feiyunwill/ClickHouse that referenced this pull request Oct 5, 2026
… DateTime64

Since ClickHouse#110621, `optimize_and_compare_chain` joins a comparison into a
transitive chain only when both sides share one `ComparisonOrderDomain`,
and `TimePoint` is keyed by scale (`DateTime` 0, `DateTime64(s)` s). A
`DateTime` constant compared with a `DateTime64(6)` column therefore has
no domain and the edge is skipped. In the query of ClickHouse#123706
(`t1.c3 < e1 AND t1.c3 >= t2.c3 AND t1.c3 <= t2.c3 + INTERVAL 48 HOUR`,
`e1` a `DateTime`) `t2.c3 < e1` is no longer derived and t2 is read in
full: 26.7 prunes it to 4/29 parts, 26.8 and master read 29/29.

The comparison itself widens such a constant exactly to the column's
scale. Do the same once, in the step that already retypes String
constants (`tryNormalizeConstStringEdge`, now `tryNormalizeConstEdge`):
a `DateTime` or lower-scale `DateTime64` constant compared with a
`DateTime64` expression is converted with `tryConvertFieldToTypeExact`,
which returns Null on overflow or loss. The edge then joins the
expression's own `TimePoint(s)` domain. Every derived comparison is
between equal `DateTime64` scales, so it cannot rescale or throw, and
the inferred-domain check holds. A higher-scale or overflowing constant
stays out of the chain as before. `Date` constants are not included,
their conversion to a time point depends on the time zone.

Closes ClickHouse#123706

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

optimize_and_compare_chain derives a String vs DateTime64 comparison: ILLEGAL_TYPE_OF_ARGUMENT (Code 43) at default settings

3 participants