Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@
import org.apache.doris.nereids.trees.expressions.IsNull;
import org.apache.doris.nereids.trees.expressions.Not;
import org.apache.doris.nereids.trees.expressions.Slot;
import org.apache.doris.nereids.trees.expressions.SlotReference;
import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.util.ExpressionUtils;
import org.apache.doris.nereids.util.PlanUtils;
import org.apache.doris.nereids.util.TypeUtils;
Expand All @@ -45,6 +47,11 @@
* Eliminate Predicate `is not null`, like
* - redundant `is not null` predicate like `a > 0 and a is not null` -> `a > 0`
* - `is not null` predicate is generated by `InferFilterNotNull`
*
* For generated IS NOT NULL on variable-length types (VARCHAR, STRING, JSON, etc.),
* the predicate is kept even when implied by other predicates, because the null bitmap
* check is much cheaper than reading variable-length data and serves as an efficient
* pre-filter at the scan level.
*/
public class EliminateNotNull implements RewriteRuleFactory {
@Override
Expand Down Expand Up @@ -83,12 +90,26 @@ private List<Expression> removeGeneratedNotNull(Collection<Expression> exprs, Ca
// predicatesNotContainIsNotNull infer nonNullable slots: `id`
// slotsFromIsNotNull: `id`, `name`
// remove `name` (it's generated), remove `id` (because `id > 0` already contains it)
//
// However, for variable-length types (STRING, VARCHAR, JSON, etc.), generated IS NOT NULL
// is kept even when implied, because null bitmap check is much cheaper than reading
// variable-length data, serving as an efficient pre-filter.
Set<Expression> predicatesNotContainIsNotNull = Sets.newLinkedHashSet();
List<Slot> slotsFromIsNotNull = Lists.newArrayList();
Set<Slot> generatedVariableLengthSlots = Sets.newLinkedHashSet();

for (Expression expr : exprs) {
// remove generated `is not null`
if (!(expr instanceof Not) || !((Not) expr).isGeneratedIsNotNull()) {
if (expr instanceof Not && ((Not) expr).isGeneratedIsNotNull()
&& ((Not) expr).child() instanceof IsNull
&& ((IsNull) ((Not) expr).child()).child() instanceof SlotReference) {
// generated IS NOT NULL
Slot slot = (SlotReference) ((IsNull) ((Not) expr).child()).child();
if (isVariableLengthType(slot.getDataType())) {
slotsFromIsNotNull.add(slot);
generatedVariableLengthSlots.add(slot);
}
// fixed-length type: skip (remove)
} else {
Optional<Slot> notNullSlot = TypeUtils.isNotNull(expr);
if (notNullSlot.isPresent()) {
slotsFromIsNotNull.add(notNullSlot.get());
Expand All @@ -104,7 +125,8 @@ private List<Expression> removeGeneratedNotNull(Collection<Expression> exprs, Ca
ImmutableSet.Builder<Expression> keepIsNotNull
= ImmutableSet.builderWithExpectedSize(slotsFromIsNotNull.size());
for (Slot slot : slotsFromIsNotNull) {
if (slot.nullable() && !inferNonNotSlots.contains(slot)) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This rebuilds a kept generated varlen IS NOT NULL as plain new Not(new IsNull(slot)), so the isGeneratedIsNotNull marker is lost. Downstream rewrites still branch on that bit (ConstantPropagation.canReplaceExpression() and RangeInference), so a case like name = 'abc' can still fold the retained pre-filter away later in the pipeline. Can we preserve the generated marker for the predicates we intentionally keep here?

if (slot.nullable()
&& (!inferNonNotSlots.contains(slot) || generatedVariableLengthSlots.contains(slot))) {
keepIsNotNull.add(new Not(new IsNull(slot)));
}
}
Expand All @@ -116,6 +138,11 @@ private List<Expression> removeGeneratedNotNull(Collection<Expression> exprs, Ca
.build();
}

private static boolean isVariableLengthType(DataType type) {
return type.isStringLikeType() || type.isJsonType()
|| type.isVariantType() || type.isComplexType();
}

private static boolean containsNot(Plan plan) {
for (Expression expression : plan.getExpressions()) {
if (expression.containsType(Not.class)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
// 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.rewrite;

import org.apache.doris.catalog.AggregateType;
import org.apache.doris.catalog.Column;
import org.apache.doris.catalog.HashDistributionInfo;
import org.apache.doris.catalog.KeysType;
import org.apache.doris.catalog.OlapTable;
import org.apache.doris.catalog.PartitionInfo;
import org.apache.doris.catalog.Type;
import org.apache.doris.nereids.CascadesContext;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.GreaterThan;
import org.apache.doris.nereids.trees.expressions.IsNull;
import org.apache.doris.nereids.trees.expressions.Not;
import org.apache.doris.nereids.trees.expressions.Slot;
import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
import org.apache.doris.nereids.trees.plans.RelationId;
import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
import org.apache.doris.nereids.util.LogicalPlanBuilder;
import org.apache.doris.nereids.util.MemoPatternMatchSupported;
import org.apache.doris.nereids.util.MemoTestUtils;
import org.apache.doris.nereids.util.PlanChecker;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.util.List;

/**
* Tests for EliminateNotNull rule.
* Verifies that generated IS NOT NULL predicates are:
* - Removed for fixed-length types (INT, BIGINT, etc.) when implied by other predicates
* - Kept for variable-length types (STRING, VARCHAR, JSON, etc.) even when implied,
* because null bitmap check is cheaper than reading variable-length data
*/
class EliminateNotNullTest implements MemoPatternMatchSupported {
// Table with nullable columns: id(INT, nullable), name(STRING, nullable)
private static final LogicalOlapScan scan1 = newNullableScan(0, "t1");

@BeforeAll
static void makeSureSlotIdStable() {
scan1.getOutput();
}

private static LogicalOlapScan newNullableScan(long tableId, String tableName) {
List<Column> columns = ImmutableList.of(
new Column("id", Type.INT, false, AggregateType.NONE, true, "0", ""),
new Column("name", Type.STRING, false, AggregateType.NONE, true, "", ""));
HashDistributionInfo hashDistributionInfo = new HashDistributionInfo(3,
ImmutableList.of(columns.get(0)));
OlapTable table = new OlapTable(tableId, tableName, columns,
KeysType.DUP_KEYS, new PartitionInfo(), hashDistributionInfo);
table.setIndexMeta(-1, tableName, table.getFullSchema(), 0, 0, (short) 0,
org.apache.doris.thrift.TStorageType.COLUMN, KeysType.DUP_KEYS);
return new LogicalOlapScan(RelationId.createGenerator().getNextId(), table,
ImmutableList.of("db"));
}

@Test
void testRemoveGeneratedIsNotNullForFixedLengthType() {
// id IS NOT NULL(generated) AND id > 1 → remove IS NOT NULL (INT is fixed-length)
Slot idSlot = scan1.getOutput().get(0);
Expression generatedIsNotNull = new Not(new IsNull(idSlot), true);
Expression greaterThan = new GreaterThan(idSlot, new IntegerLiteral(1));

LogicalPlan plan = new LogicalPlanBuilder(scan1)
.filter(ImmutableSet.of(greaterThan, generatedIsNotNull))
.build();

PlanChecker checker = PlanChecker.from(MemoTestUtils.createConnectContext(), plan);
checker.getCascadesContext().bottomUpRewrite(new EliminateNotNull());
checker.matches(
logicalFilter(logicalOlapScan())
.when(f -> f.getConjuncts().size() == 1)
.when(f -> f.getConjuncts().stream()
.allMatch(e -> e instanceof GreaterThan))
);
}

@Test
void testKeepGeneratedIsNotNullForVariableLengthType() {
// name IS NOT NULL(generated) AND name > 'abc' → keep IS NOT NULL (STRING is variable-length)
Slot nameSlot = scan1.getOutput().get(1);
Expression generatedIsNotNull = new Not(new IsNull(nameSlot), true);
Expression greaterThan = new GreaterThan(nameSlot, new StringLiteral("abc"));

LogicalPlan plan = new LogicalPlanBuilder(scan1)
.filter(ImmutableSet.of(greaterThan, generatedIsNotNull))
.build();

PlanChecker checker = PlanChecker.from(MemoTestUtils.createConnectContext(), plan);
checker.getCascadesContext().bottomUpRewrite(new EliminateNotNull());
checker.matches(
logicalFilter(logicalOlapScan())
.when(f -> f.getConjuncts().size() == 2)
);
}

@Test
void testRemoveStandaloneGeneratedIsNotNullForFixedLengthType() {
// id IS NOT NULL(generated) alone → removed (INT, no pre-filter value)
Slot idSlot = scan1.getOutput().get(0);
Expression generatedIsNotNull = new Not(new IsNull(idSlot), true);

LogicalPlan plan = new LogicalPlanBuilder(scan1)
.filter(ImmutableSet.of(generatedIsNotNull))
.build();

PlanChecker checker = PlanChecker.from(MemoTestUtils.createConnectContext(), plan);
checker.getCascadesContext().bottomUpRewrite(new EliminateNotNull());
checker.matches(logicalOlapScan());
}

@Test
void testKeepStandaloneGeneratedIsNotNullForVariableLengthType() {
// name IS NOT NULL(generated) alone → kept (STRING, cheap null bitmap pre-filter)
Slot nameSlot = scan1.getOutput().get(1);
Expression generatedIsNotNull = new Not(new IsNull(nameSlot), true);

LogicalPlan plan = new LogicalPlanBuilder(scan1)
.filter(ImmutableSet.of(generatedIsNotNull))
.build();

PlanChecker checker = PlanChecker.from(MemoTestUtils.createConnectContext(), plan);
checker.getCascadesContext().bottomUpRewrite(new EliminateNotNull());
checker.matches(
logicalFilter(logicalOlapScan())
.when(f -> f.getConjuncts().size() == 1)
);
}

@Test
void testEndToEndInferAndEliminateForVariableLengthType() {
// Full pipeline: name > 'abc' → InferFilterNotNull adds IS NOT NULL → EliminateNotNull keeps it
Slot nameSlot = scan1.getOutput().get(1);
Expression greaterThan = new GreaterThan(nameSlot, new StringLiteral("abc"));

LogicalPlan plan = new LogicalPlanBuilder(scan1)
.filter(ImmutableSet.of(greaterThan))
.build();

PlanChecker checker = PlanChecker.from(MemoTestUtils.createConnectContext(), plan);
CascadesContext ctx = checker.getCascadesContext();
ctx.topDownRewrite(new InferFilterNotNull());
ctx.bottomUpRewrite(new EliminateNotNull());
checker.matches(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

These assertions only check conjunct counts after a local InferFilterNotNull + EliminateNotNull sequence. They would still pass even if the kept predicate loses its isGeneratedIsNotNull marker, which is exactly what downstream passes use. Please add a regression that either asserts the retained predicate is still marked as generated, or runs the full rewriter / ConstantPropagation path so we know the pre-filter survives end-to-end.

logicalFilter(logicalOlapScan())
.when(f -> f.getConjuncts().size() == 2)
);
}

@Test
void testEndToEndInferAndEliminateForFixedLengthType() {
// Full pipeline: id > 1 → InferFilterNotNull adds IS NOT NULL → EliminateNotNull removes it
Slot idSlot = scan1.getOutput().get(0);
Expression greaterThan = new GreaterThan(idSlot, new IntegerLiteral(1));

LogicalPlan plan = new LogicalPlanBuilder(scan1)
.filter(ImmutableSet.of(greaterThan))
.build();

PlanChecker checker = PlanChecker.from(MemoTestUtils.createConnectContext(), plan);
CascadesContext ctx = checker.getCascadesContext();
ctx.topDownRewrite(new InferFilterNotNull());
ctx.bottomUpRewrite(new EliminateNotNull());
checker.matches(
logicalFilter(logicalOlapScan())
.when(f -> f.getConjuncts().size() == 1)
.when(f -> f.getConjuncts().stream()
.allMatch(e -> e instanceof GreaterThan))
);
}
}
Loading