Skip to content

Optimize single-element IN to equality comparison - #98938

Open
amosbird wants to merge 16 commits into
ClickHouse:masterfrom
amosbird:optimize-in-to-equal
Open

amosbird wants to merge 16 commits into
ClickHouse:masterfrom
amosbird:optimize-in-to-equal

Conversation

@amosbird

@amosbird amosbird commented Mar 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds a new Analyzer pass ConvertInToEqualPass that rewrites x IN (v) → x = v and x NOT IN (v) → x != v (also handles globalIn/globalNotIn). This enables downstream optimizations that work on equality comparisons but not on IN expressions (e.g., key analysis, index usage). The pass is controlled by the optimize_in_to_equal setting (default: enabled).

Additionally extracts areTypesComparableForEquality and areTypesComparableForOrdering from FunctionsComparison.h into DataTypes/Utils.h to eliminate duplication and allow the pass to pre-validate type compatibility before converting — avoiding cases where IN accepts type pairs that equals would reject.

Changes:

  • New ConvertInToEqualPass in src/Analyzer/Passes/ — handles in, notIn, globalIn, globalNotIn
  • Pre-validates type compatibility using areTypesComparableForEquality before converting
  • New optimize_in_to_equal setting in Core/Settings.cpp (default: true)
  • Extracted areTypesComparableForEquality and areTypesComparableForOrdering into DataTypes/Utils.h/.cpp with shared areTypePairsCompatibleForComparison helper
  • Simplified FunctionsComparison.h to call the extracted functions
  • Updated gtest_transform_query_for_external_database tests to match new query plans
  • Comprehensive stateless test 03837_optimize_in_to_equal

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Optimize single-element IN clauses to equality comparisons (x IN (1) → x = 1), enabling better index utilization and downstream optimizations. Controlled by optimize_in_to_equal setting. Continuation of #61564.

Documentation entry for user-facing changes

  • Documentation is not required

Note

Medium Risk
Changes query-tree rewriting and comparison type-validation behavior, which can affect query semantics/plans in edge cases (NULL/Enum/type conversion), though guarded by a new optimize_in_to_equal setting and conservative skip rules.

Overview
Introduces a new Analyzer pass ConvertInToEqualPass (enabled by default via optimize_in_to_equal) that rewrites single-element x IN (v) to x = v and x NOT IN (v) to x != v, while skipping cases that would change semantics (e.g., NULL, Nullable LHS, Enums, compound constants) and performing strict constant type conversion.

Extracts comparison type-pair compatibility logic into DataTypes/Utils (areTypesComparableForEquality / areTypesComparableForOrdering) and updates FunctionComparison to use it, plus adjusts/extends tests and adds a new stateless test coverage for the optimization and its guardrails.

Written by Cursor Bugbot for commit fbae9e9. This will update automatically on new commits. Configure here.


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

@clickhouse-gh

clickhouse-gh Bot commented Mar 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b415078]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
03837_optimize_in_to_equal FAIL cidb
05034_merge_sibling_const_fold FAIL cidb
04327_106948_minmax_skip_index_nan FAIL cidb
05060_enum_in_variant_dynamic_in_set FAIL cidb
04695_date32_field_to_datetime_coercion FAIL cidb
04303_key_condition_ifnull_coalesce_boolean FAIL cidb
04401_key_condition_is_not_distinct_from FAIL cidb
05227_in_nan_minmax_pruning FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 6, 2026
@amosbird
amosbird force-pushed the optimize-in-to-equal branch from 1eada76 to 227d21e Compare March 6, 2026 15:50
@EmeraldShift

Copy link
Copy Markdown
Contributor

I wonder if there's a more general optimization opportunity here: is index analysis more efficient for e.g. x = 'A' OR x = 'B' than for x IN ('A', 'B')? What about for more elements?

I've long wondered about a specific example: if X is the ordering key for a table, can X in (...) for a set with cardinality N perform N binary searches rather than using the (slightly) more expensive generic exclusion search infrastructure?

@amosbird

amosbird commented Mar 7, 2026

Copy link
Copy Markdown
Collaborator Author

I wonder if there's a more general optimization opportunity here: is index analysis more efficient for e.g. x = 'A' OR x = 'B' than for x IN ('A', 'B')? What about for more elements?

Yes. We already have optimize_min_inequality_conjunction_chain_length and optimize_min_equality_disjunction_chain_length.

amosbird added 6 commits March 7, 2026 14:59
Move the type-pair compatibility logic from FunctionsComparison.h
into DataTypes/Utils.h so it can be reused by Analyzer passes.

Shared helper areTypePairsCompatibleForComparison covers: numeric
(excluding date vs number), string, date/datetime, UUID, IP, enum,
equal-size tuple, equal types, and common supertype checks.

FunctionsComparison::getReturnTypeImpl now calls the extracted
functions instead of inlining the checks.
New Analyzer pass that rewrites single-element IN to equality:
  x IN (v)         -> x = v
  x NOT IN (v)     -> x != v
  x globalIn (v)   -> x = v
  x globalNotIn (v)-> x != v

Pre-validates type compatibility via areTypesComparableForEquality
to skip cases where IN accepts type pairs that equals would reject.
Controlled by optimize_in_to_equal setting (default: true).
- Skip conversion when LHS is Nullable (IN/NOT IN have different NULL
  semantics than equals/notEquals)
- Skip conversion when LHS is Enum (equals/notEquals throw
  UNKNOWN_ELEMENT_OF_ENUM for unknown values, while IN/NOT IN silently
  treat them as non-matching)
- Add Nullable and Enum test cases to 03837_optimize_in_to_equal
- Disable optimization in 5 existing tests that rely on IN-specific
  behavior in EXPLAIN output or query log patterns
…ity(Enum) types

Use `isNullableOrLowCardinalityNullable` instead of `isNullable` to correctly
detect Nullable semantics wrapped in LowCardinality. Apply `removeLowCardinality`
before checking for Enum types to catch LowCardinality(Enum(...)) as well.

Add test cases for LowCardinality(Nullable(String)) verifying the pass preserves
`in`/`notIn` and maintains correct NULL propagation semantics.
Move `removeLowCardinality` to the top of the visitor so all downstream
checks (`isNullable`, `WhichDataType`, `areTypesComparableForEquality`)
operate on the unwrapped type. This fixes a bug where `LowCardinality(Date)`
could bypass the date-number compatibility guard in `areTypePairsCompatibleForComparison`,
and simplifies the Nullable and Enum checks by removing the need for
`isNullableOrLowCardinalityNullable` and per-site `removeLowCardinality` calls.
When the LHS and RHS types differ (e.g. String IN (1)), convert the
constant to match the LHS type using tryConvertFieldToType, mirroring
how IN builds its Set in SetUtils.cpp. Previously, the pass relied on
areTypesComparableForEquality which returned true for String vs UInt8,
but equals(String, UInt8) threw NO_COMMON_TYPE at execution time.

Now the integer 1 is converted to the string '1', producing
equals(x, '1') which FunctionComparison can execute correctly.
If conversion fails, the optimization is skipped conservatively.

Remove the optimize_in_to_equal=0 workaround from
03761_log_with_string_size.sql — the test now works correctly with
the optimization enabled.
@amosbird
amosbird force-pushed the optimize-in-to-equal branch from cb80a30 to 9c9ea8b Compare March 7, 2026 07:00
backQuote(getName()));
}
else if (!arguments[0]->isComparable() || !arguments[1]->isComparable())
{

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Refactored error messages lost diagnostic specificity

Low Severity

The refactoring collapsed three distinct error messages into one generic message. The original code distinguished between "not comparable for equality" (for equals/notEquals with types failing isComparableForEquality), "not comparable" (for ordering operators with types failing isComparable), and a generic type-pair mismatch. The new single message "Illegal types of arguments ({}, {}) of function {}" loses the "because some of them are not comparable for equality" / "because some of them are not comparable" suffixes, making it harder for users to understand why their comparison is invalid.

Fix in Cursor Fix in Web

amosbird added 4 commits March 7, 2026 15:41
Replace tryConvertFieldToType with convertFieldToTypeStrict to reject
lossy type conversions. tryConvertFieldToType allows precision loss
(e.g. Decimal(9,2) to Decimal(9,1), or Float64 1.5551 to Decimal(9,3)),
while IN uses convertFieldToTypeStrict which rejects such conversions.

This fixes 3 CI test failures:
- 02421_decimal_in_precision_issue_41125
- 02428_decimal_in_floating_point_literal
- 03209_parallel_replicas_lost_decimal_conversion
…sues

- 03837: add `no-old-analyzer` tag (EXPLAIN QUERY TREE requires analyzer)
- 02864: disable for IPv4 IN string (ParallelReplicas column name mismatch)
- 00386: disable for long IN pk test (ParallelReplicas column name mismatch)
- 03173: disable for partition pruning test (KeyCondition exception with invalid date strings)
Revert preemptive disables in 02864, 00386, 03173 — these tests check
query results which are identical with the optimization enabled.

For our test (03837), replace `no-old-analyzer` tag with
`SET enable_analyzer = 1` so the test runs in all configurations.
…n_to_equal

- 01756: re-add disable (splitByString('IN', query) genuinely incompatible)
- 03773: remove disable, update reference for EXPLAIN indexes output change
- 03532: remove disable (= and IN produce identical ProfileEvents)

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

amosbird and others added 5 commits March 9, 2026 19:45
…domization

- Add nullIn/globalNullIn/notNullIn/globalNotNullIn to ConvertInToEqualPass.
  These are safe because the pass already skips Nullable LHS, and nullIn
  only differs from in in NULL handling (irrelevant for non-Nullable).
- Simplify 03837 test: extract only function name from EXPLAIN QUERY TREE
  and strip node IDs to avoid brittle reference file.
- Fix 03773: force SET optimize_in_to_equal = 1 in analyzer=1 section to
  prevent randomized settings from breaking the reference.
# Conflicts:
#	src/Analyzer/QueryTreePassManager.cpp
#	src/Storages/tests/gtest_transform_query_for_external_database.cpp
…ssages

The refactor that extracted `areTypesComparableForEquality`/`areTypesComparableForOrdering`
into `DataTypes/Utils.h` collapsed three distinct error suffixes — "not comparable for
equality", "not comparable", and the generic type-pair mismatch — into a single generic
message. Reintroduce the `isComparableForEquality`/`isComparable` checks in
`FunctionComparison::getReturnTypeImpl` so users see *why* a comparison is invalid, while
keeping the extracted helpers for the type-pair check.
After merging master, `convertFieldToTypeStrict` no longer exists — it was
unified into `convertFieldToType` with a `strict` parameter that returns a
`Field` (with `Field::Null` indicating conversion failure or out-of-range value)
instead of `std::optional<Field>`. Update the call site accordingly.
The new setting was placed in the 26.3 block, but the test
`02995_new_settings_history` requires new entries to be in a block with
version > 26.4 (the baseline is `v26.4.1`). Move the entry to the 26.5
block and record the default change as `false` → `true` to reflect the
behavior change for upgrade scenarios.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98938&sha=5699c6a13bcf8b47627717cb1fbd0f8bc0dc8690&name_0=PR&name_1=Fast%20test
PR: ClickHouse#98938
@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 95.14% (137/144) · Uncovered code

Full report · Diff report

@abashkeev abashkeev added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 3, 2026
Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

- retargeted PR record [email protected] to 26.10 (settings-history check rule)

Also resolved conflicts in:
- `src/Functions/FunctionsComparison.h`
- `src/Storages/tests/gtest_transform_query_for_external_database.cpp`
- `tests/queries/0_stateless/03773_deterministic_functions_key_condition_explain.reference`

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@rienath rienath added the can be tested Allows running workflows for external contributors label Oct 8, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

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). external Author is not a member of the ClickHouse organization pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants