Repository navigation
Conversation
|
Workflow [PR], commit [b415078] Summary: ❌
|
1eada76 to
227d21e
Compare
|
I wonder if there's a more general optimization opportunity here: is index analysis more efficient for e.g. I've long wondered about a specific example: if X is the ordering key for a table, can |
Yes. We already have |
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.
cb80a30 to
9c9ea8b
Compare
| backQuote(getName())); | ||
| } | ||
| else if (!arguments[0]->isComparable() || !arguments[1]->isComparable()) | ||
| { |
There was a problem hiding this comment.
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.
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)
…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
LLVM Coverage Report
Changed lines: 95.14% (137/144) · Uncovered code |
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]>


Summary
Adds a new Analyzer pass
ConvertInToEqualPassthat rewritesx IN (v)→x = vandx NOT IN (v)→x != v(also handlesglobalIn/globalNotIn). This enables downstream optimizations that work on equality comparisons but not onINexpressions (e.g., key analysis, index usage). The pass is controlled by theoptimize_in_to_equalsetting (default: enabled).Additionally extracts
areTypesComparableForEqualityandareTypesComparableForOrderingfromFunctionsComparison.hintoDataTypes/Utils.hto eliminate duplication and allow the pass to pre-validate type compatibility before converting — avoiding cases whereINaccepts type pairs thatequalswould reject.Changes:
ConvertInToEqualPassinsrc/Analyzer/Passes/— handlesin,notIn,globalIn,globalNotInareTypesComparableForEqualitybefore convertingoptimize_in_to_equalsetting inCore/Settings.cpp(default: true)areTypesComparableForEqualityandareTypesComparableForOrderingintoDataTypes/Utils.h/.cppwith sharedareTypePairsCompatibleForComparisonhelperFunctionsComparison.hto call the extracted functionsgtest_transform_query_for_external_databasetests to match new query plans03837_optimize_in_to_equalChangelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Optimize single-element
INclauses to equality comparisons (x IN (1)→x = 1), enabling better index utilization and downstream optimizations. Controlled byoptimize_in_to_equalsetting. Continuation of #61564.Documentation entry for user-facing changes
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_equalsetting and conservative skip rules.Overview
Introduces a new Analyzer pass
ConvertInToEqualPass(enabled by default viaoptimize_in_to_equal) that rewrites single-elementx IN (v)tox = vandx NOT IN (v)tox != 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 updatesFunctionComparisonto 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]