This is an automated email from the ASF dual-hosted git repository.

englefly pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 7a807868398 [fix](nereids) Deduplicate literal prefixes in large IN 
predicates (#70917)
7a807868398 is described below

commit 7a8078683981ca8da24399b6e77f533a18ab0c1c
Author: minghong <[email protected]>
AuthorDate: Thu Nov 26 14:44:37 2026 +0800

    [fix](nereids) Deduplicate literal prefixes in large IN predicates (#70917)
    
    ### Background
    
    Nereids normalizes an `IN` predicate before cardinality estimation. The
    normalizer removes duplicate options, and a separate rule converts a
    single remaining option to an equality predicate.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #46794 (introduced the rewrite size limit)
    PR Type: Bugfix
    
    Problem Summary:
    
    An `IN` predicate with 201 copies of the same literal reaches
    cardinality estimation with all 201 options. Estimation can count
    repeated values separately. Deduplicating the leading literals lets that
    example normalize to a single equality while limiting the work on lists
    whose first 200 options have little repetition.
    
    ### Details
    
    - **Frequency:** Always when normalizing the 201-option repeated-literal
    example.
    - **Root cause:** `InPredicateDedup` skipped every list over 200
    options. `FilterEstimation` counts each surviving in-range literal,
    including duplicate copies.
    - **Why existing tests missed it:**
    `ExpressionRewriteTest.testInPredicateDedup` uses four options. The
    `test_simplify_in_predicate` SQL regression covers type coercion on
    short date and timestamp lists. Both stay within the rewrite limit.
    - **Fix:** Sample and deduplicate leading literals in one pass. If a
    101st distinct value occurs within the first 200 options, keep the
    original predicate. Otherwise, continue to the first nonliteral or the
    end of the list. Retain one copy of each literal in first-seen order,
    including NULL, and append the untouched suffix from the first
    nonliteral.
    - **Other paths and branches:** The Nereids normalization rule is shared
    by its plan entry points. Range inference and nonconstant extraction
    keep their own 200-option checks through the shared constant. The
    original deduplication limit is present on `branch-3.1`, `branch-4.0`,
    `branch-4.1`, and `branch-4.2`. This PR targets `master`.
    - **Behavior change:** Large lists with a repetitive leading section can
    produce a smaller predicate and different cardinality estimates. The
    first 200 options can reject the rewrite early. Once the sample
    qualifies, the scan can reach the end of the literal prefix.
    
    ### Testing
    
    - On `master` before the fix, the new rewrite test reproduced three
    failures. A list with 201 copies kept all of them, duplicate literals
    before a function survived, and a large `NOT IN` retained repeated
    NULLs.
    - On the candidate, the local FE unit-test runner passed all 94 tests in
    `InPredicateDedupTest`, `ExpressionRewriteTest`,
    `SimplifyInPredicateTest`, and `FilterEstimationTest`. The large-list
    fixture has 9,999 options under the default expression width limit.
    - FE Checkstyle reported zero violations.
    
    ### Release note
    
    Nereids now deduplicates repetitive literal prefixes in large `IN`
    lists, which can improve row estimates for generated queries with many
    repeated values.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details)
    - Does this need documentation: No
    - Pre-submission status: Ready
    
    ### AI Disclosure
    
    - Tool: OpenAI Codex (GPT-6)
    - Generated: Planner change, unit tests, and PR description
    - Human review: Not reported
---
 .../rules/expression/rules/InPredicateDedup.java   |  43 ++++++++-
 .../rules/expression/InPredicateDedupTest.java     | 104 +++++++++++++++++++++
 2 files changed, 142 insertions(+), 5 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/InPredicateDedup.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/InPredicateDedup.java
index 1be5971f6a2..034fffddbfb 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/InPredicateDedup.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/expression/rules/InPredicateDedup.java
@@ -22,10 +22,12 @@ import 
org.apache.doris.nereids.rules.expression.ExpressionPatternRuleFactory;
 import org.apache.doris.nereids.rules.expression.ExpressionRuleType;
 import org.apache.doris.nereids.trees.expressions.Expression;
 import org.apache.doris.nereids.trees.expressions.InPredicate;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Set;
 
@@ -36,15 +38,14 @@ import java.util.Set;
 public class InPredicateDedup implements ExpressionPatternRuleFactory {
     public static final InPredicateDedup INSTANCE = new InPredicateDedup();
 
-    // In many BI scenarios, the sql is auto-generated, and hence there may be 
thousands of options.
-    // It takes a long time to apply this rule. So set a threshold for the max 
number.
+    // Size limit for other IN rewrites and sample size for large-list 
deduplication.
     public static final int REWRITE_OPTIONS_MAX_SIZE = 200;
+    private static final int LARGE_IN_PREFIX_DISTINCT_LIMIT = 100;
 
     @Override
     public List<ExpressionPatternMatcher<? extends Expression>> buildRules() {
         return ImmutableList.of(
             matchesType(InPredicate.class)
-                    .when(inPredicate -> inPredicate.getOptions().size() <= 
REWRITE_OPTIONS_MAX_SIZE)
                     .then(InPredicateDedup::dedup)
                     .toRule(ExpressionRuleType.IN_PREDICATE_DEDUP)
         );
@@ -52,15 +53,47 @@ public class InPredicateDedup implements 
ExpressionPatternRuleFactory {
 
     /** dedup */
     public static Expression dedup(InPredicate inPredicate) {
+        List<Expression> options = inPredicate.getOptions();
+        if (options.size() > REWRITE_OPTIONS_MAX_SIZE) {
+            return dedupLiteralPrefix(inPredicate, options);
+        }
+
         ImmutableSet.Builder<Expression> newOptionsBuilder = 
ImmutableSet.builderWithExpectedSize(inPredicate.arity());
-        for (Expression option : inPredicate.getOptions()) {
+        for (Expression option : options) {
             newOptionsBuilder.add(option);
         }
 
         Set<Expression> newOptions = newOptionsBuilder.build();
-        if (newOptions.size() == inPredicate.getOptions().size()) {
+        if (newOptions.size() == options.size()) {
             return inPredicate;
         }
         return new InPredicate(inPredicate.getCompareExpr(), newOptions);
     }
+
+    private static Expression dedupLiteralPrefix(InPredicate inPredicate, 
List<Expression> options) {
+        Set<Literal> distinctPrefix = new LinkedHashSet<>();
+        int prefixEnd = 0;
+        for (; prefixEnd < options.size(); prefixEnd++) {
+            Expression option = options.get(prefixEnd);
+            if (!(option instanceof Literal)) {
+                break;
+            }
+            distinctPrefix.add((Literal) option);
+            // Continue past the sample only when it contains enough 
duplicates.
+            if (prefixEnd < REWRITE_OPTIONS_MAX_SIZE && distinctPrefix.size() 
> LARGE_IN_PREFIX_DISTINCT_LIMIT) {
+                return inPredicate;
+            }
+        }
+        if (distinctPrefix.size() == prefixEnd) {
+            return inPredicate;
+        }
+
+        // Keep the first non-literal option and every option after it in 
their original order.
+        List<Expression> compacted = 
ImmutableList.<Expression>builderWithExpectedSize(
+                        distinctPrefix.size() + (options.size() - prefixEnd))
+                .addAll(distinctPrefix)
+                .addAll(options.subList(prefixEnd, options.size()))
+                .build();
+        return new InPredicate(inPredicate.getCompareExpr(), compacted, 
inPredicate.isInferred());
+    }
 }
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/expression/InPredicateDedupTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/expression/InPredicateDedupTest.java
new file mode 100644
index 00000000000..92912fabb33
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/expression/InPredicateDedupTest.java
@@ -0,0 +1,104 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.expression;
+
+import org.apache.doris.nereids.rules.expression.rules.InPredicateDedup;
+import 
org.apache.doris.nereids.rules.expression.rules.InPredicateToEqualToRule;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.InPredicate;
+import org.apache.doris.nereids.trees.expressions.Not;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.Abs;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.NullLiteral;
+import org.apache.doris.nereids.types.IntegerType;
+
+import com.google.common.collect.ImmutableList;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+class InPredicateDedupTest extends ExpressionRewriteTestHelper {
+    // The default expression width limit of 10,000 also counts the compare 
expression.
+    private static final int LARGE_LIST_SIZE = 9_999;
+
+    private final SlotReference key = new SlotReference("k", 
IntegerType.INSTANCE);
+    private final ExpressionRuleExecutor dedupExecutor = new 
ExpressionRuleExecutor(
+            ImmutableList.of(bottomUp(InPredicateDedup.INSTANCE, 
InPredicateToEqualToRule.INSTANCE)));
+
+    @Test
+    void deduplicatesRepeatedLiteralListsOnBothSidesOfTheLimit() {
+        IntegerLiteral value = new IntegerLiteral(7);
+        for (int size : new int[] {200, 201, LARGE_LIST_SIZE}) {
+            InPredicate original = new InPredicate(key, 
Collections.nCopies(size, value));
+            Assertions.assertEquals(new EqualTo(key, value), 
dedupExecutor.rewrite(original, context),
+                    "list size " + size);
+        }
+    }
+
+    @Test
+    void keepsTheFunctionAndTheRestOfTheListInOrder() {
+        List<Expression> distinctPrefix = new ArrayList<>();
+        for (int value = 100; value > 0; value--) {
+            distinctPrefix.add(new IntegerLiteral(value));
+        }
+        List<Expression> options = new ArrayList<>();
+        for (int repeat = 0; repeat < 4; repeat++) {
+            options.addAll(distinctPrefix);
+        }
+        List<Expression> suffix = new ArrayList<>();
+        suffix.add(new Abs(new SlotReference("v", IntegerType.INSTANCE)));
+        suffix.addAll(Collections.nCopies(100, new IntegerLiteral(7)));
+        options.addAll(suffix);
+        List<Expression> expected = new ArrayList<>(distinctPrefix);
+        expected.addAll(suffix);
+
+        InPredicate original = new InPredicate(key, options);
+        InPredicate rewritten = (InPredicate) dedupExecutor.rewrite(original, 
context);
+        Assertions.assertEquals(expected, rewritten.getOptions());
+    }
+
+    @Test
+    void keepsLargeListsWithMoreThanOneHundredDistinctPrefixValues() {
+        List<Expression> options = new ArrayList<>();
+        for (int value = 0; value < 101; value++) {
+            options.add(new IntegerLiteral(value));
+        }
+        options.addAll(Collections.nCopies(LARGE_LIST_SIZE - options.size(), 
new IntegerLiteral(0)));
+
+        InPredicate original = new InPredicate(key, options);
+        Assertions.assertSame(original, dedupExecutor.rewrite(original, 
context));
+    }
+
+    @Test
+    void retainsOneNullInLargeNotInList() {
+        IntegerLiteral value = new IntegerLiteral(7);
+        NullLiteral nullValue = new NullLiteral(IntegerType.INSTANCE);
+        List<Expression> options = new ArrayList<>(Collections.nCopies(201, 
value));
+        options.add(nullValue);
+        options.add(nullValue);
+
+        Not original = new Not(new InPredicate(key, options));
+        Not expected = new Not(new InPredicate(key, ImmutableList.of(value, 
nullValue)));
+        Assertions.assertEquals(expected, dedupExecutor.rewrite(original, 
context));
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to