This is an automated email from the ASF dual-hosted git repository.
yujun777 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 d2111336efa [opt](ivm) Explore a smaller hash build for NULL repair
anti joins (#71071)
d2111336efa is described below
commit d2111336efa0b1a64d98d65d86bb633fc5d9ed71
Author: yujun <[email protected]>
AuthorDate: Tue Dec 1 07:23:43 2026 +0800
[opt](ivm) Explore a smaller hash build for NULL repair anti joins (#71071)
### Background
During incremental materialized view refresh, a change on the
null-producing side of an equi-join can add or remove a NULL-extended
row. When the matching key is non-unique, the refresh groups the changed
keys and uses an anti join against the pre-refresh or post-refresh
snapshot to detect that transition.
### What problem does this PR solve?
Issue Number: None
Related PR: #70922 (the INNER and CROSS JOIN optimization)
PR Type: Performance
Problem Summary: A NULL repair anti join can build its hash table over a
large snapshot even when the refresh affects a few keys. If invalid
statistics automatically disable join reordering, the optimizer can
still consider building this particular anti join on the affected keys.
### Details
- **Why it was slow:** The existing LEFT ANTI orientation uses the
snapshot as its hash build input. In a directional A/B test, the hash
build consumed 8 million rows to evaluate 32 affected keys.
- **Optimization:** Identify the anti join generated for non-unique
equality keys. After a statistics check automatically disables
reordering, offer one RIGHT ANTI alternative in the same Memo group when
the rewritten join still supports hashing and the snapshot exceeds the
configured broadcast row limit. The optimizer compares the existing
orientation and the new one.
- **Results:** With an 8-million-row snapshot and 32 keys, test queries
on the same single-BE ASAN runtime on a Xeon Platinum 8457C host
returned the same 16 unmatched keys. Both plans used bucket shuffle.
Across five interleaved warm runs per direction, median client wall time
was 1.49 s for LEFT ANTI and 0.28 s for RIGHT ANTI. The hash build
operator reported a peak of 109.78 MB and 30.52 MB, respectively. With a
16-row snapshot, LEFT ANTI chose broadcast and ran in 0.07 s median,
compared with 0.13 s for RIGHT ANTI. These measurements cover the
isolated anti join.
- **Applicability and cost:** Local exploration adds at most one
orientation per eligible join. Snapshot scans can still be large, and
the cost model accounts for shuffle. Small snapshots keep their
automatic broadcast option. Explicit reordering and distribution
decisions take precedence.
### Testing
- FE package and Checkstyle passed.
- Passed 551 IVM and MTMV FE unit tests. The focused optimizer and
statistics run also passed all 75 tests.
- All 132 IVM regression suites passed across the directory run and a
targeted rerun of three suites. Two existing fixtures required the
default database name. The updated NULL-repair suite passed with
regenerated expected results.
- The new suite checks automatic broadcast for a small snapshot, RIGHT
ANTI for a large snapshot after invalid stats disable reorder, and LEFT
ANTI when reorder is disabled explicitly. It covers first-match
insertion, last-match deletion, and deletion with a duplicate match
remaining.
### Release note
Incremental refresh can reduce the hash build footprint of eligible NULL
repair anti joins against large snapshots.
---
.../apache/doris/mtmv/ivm/IvmJoinDeltaHandler.java | 1 +
.../org/apache/doris/nereids/StatementContext.java | 9 ++
.../jobs/cascades/OptimizeGroupExpressionJob.java | 7 ++
.../rules/exploration/join/JoinCommute.java | 52 +++++++---
.../rules/exploration/join/JoinReorderContext.java | 11 +++
.../doris/nereids/stats/StatsCalculator.java | 26 +++--
.../mtmv_p0/ivm/test_ivm_null_repair_anti_join.out | 13 +++
.../ivm/test_ivm_null_repair_anti_join.groovy | 110 +++++++++++++++++++++
8 files changed, 202 insertions(+), 27 deletions(-)
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmJoinDeltaHandler.java
b/fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmJoinDeltaHandler.java
index 5604454c9dc..9c7b1f4df7b 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmJoinDeltaHandler.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmJoinDeltaHandler.java
@@ -676,6 +676,7 @@ class IvmJoinDeltaHandler {
LogicalJoin<Plan, Plan> antiJoin = new
LogicalJoin<>(JoinType.LEFT_ANTI_JOIN,
antiConjuncts.build(), ImmutableList.of(),
join.getDistributeHint(),
affectedKeys, nullSideSnapshot.first,
JoinReorderContext.EMPTY);
+ antiJoin.getJoinReorderContext().markIvmNullRepairAntiJoin();
return projectNullSideRepairEvent(deltaContext, antiJoin,
deltaKeys.keySlots, dmlFactor);
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java
index 1d05d7c2aa7..feb6a7af0e2 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/StatementContext.java
@@ -370,6 +370,7 @@ public class StatementContext implements Closeable {
private Set<PlannerHook> plannerHooks = new HashSet<>();
private String disableJoinReorderReason;
+ private boolean joinReorderDisabledByStats;
private Backend groupCommitMergeBackend;
@@ -2294,6 +2295,14 @@ public class StatementContext implements Closeable {
return tableId;
}
+ public boolean isJoinReorderDisabledByStats() {
+ return joinReorderDisabledByStats;
+ }
+
+ public void markJoinReorderDisabledByStats() {
+ joinReorderDisabledByStats = true;
+ }
+
public Optional<String> getDisableJoinReorderReason() {
return Optional.ofNullable(disableJoinReorderReason);
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/cascades/OptimizeGroupExpressionJob.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/cascades/OptimizeGroupExpressionJob.java
index 1761f6f7351..580065852ac 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/cascades/OptimizeGroupExpressionJob.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/cascades/OptimizeGroupExpressionJob.java
@@ -24,6 +24,7 @@ import org.apache.doris.nereids.jobs.JobType;
import org.apache.doris.nereids.memo.GroupExpression;
import org.apache.doris.nereids.rules.Rule;
import org.apache.doris.nereids.rules.RuleSet;
+import org.apache.doris.nereids.rules.exploration.join.JoinCommute;
import org.apache.doris.nereids.rules.exploration.mv.MaterializedViewUtils;
import com.google.common.collect.ImmutableList;
@@ -103,6 +104,12 @@ public class OptimizeGroupExpressionJob extends Job {
int joinNumBushyTree = context.getCascadesContext().getConnectContext()
.getSessionVariable().getMaxJoinNumBushyTree();
if (isDisableJoinReorder) {
+ CascadesContext cascadesContext = context.getCascadesContext();
+ if (cascadesContext.getStatementContext().isIvmMTMVRewrite()
+ &&
cascadesContext.getStatementContext().isJoinReorderDisabledByStats()
+ && !cascadesContext.isLeadingDisableJoinReorder()) {
+ return Collections.singletonList(JoinCommute.IVM_NULL_REPAIR);
+ }
return Collections.emptyList();
} else if (isDpHyp) {
return getRuleSet().getDPHypReorderRules();
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/join/JoinCommute.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/join/JoinCommute.java
index 8d6a9bfeac0..930b1df143d 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/join/JoinCommute.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/join/JoinCommute.java
@@ -17,6 +17,7 @@
package org.apache.doris.nereids.rules.exploration.join;
+import org.apache.doris.nereids.memo.Group;
import org.apache.doris.nereids.rules.Rule;
import org.apache.doris.nereids.rules.RuleType;
import org.apache.doris.nereids.rules.exploration.OneExplorationRuleFactory;
@@ -41,6 +42,8 @@ public class JoinCommute extends OneExplorationRuleFactory {
public static final JoinCommute BUSHY = new JoinCommute(SwapType.BUSHY,
false);
public static final JoinCommute NON_INNER = new
JoinCommute(SwapType.BUSHY, true);
+ public static final Rule IVM_NULL_REPAIR =
BUSHY.buildIvmNullRepairCommute();
+
private final SwapType swapType;
private final boolean justNonInner;
@@ -68,19 +71,42 @@ public class JoinCommute extends OneExplorationRuleFactory {
.whenNot(join -> JoinUtils.shouldNestedLoopJoin(join)
&&
NestedLoopJoinNode.canParallelize(JoinType.toJoinOperator(join.getJoinType()))
&&
!NestedLoopJoinNode.canParallelize(JoinType.toJoinOperator(join.getJoinType().swap())))
- .then(join -> {
- // Use swap() to properly handle ASOF JOIN MATCH_CONDITION
commutation
- LogicalJoin<? extends Plan, ? extends Plan> newJoin =
join.swap();
-
newJoin.getJoinReorderContext().copyFrom(join.getJoinReorderContext());
- newJoin.getJoinReorderContext().setHasCommute(true);
- if (swapType == SwapType.ZIG_ZAG && isNotBottomJoin(join))
{
-
newJoin.getJoinReorderContext().setHasCommuteZigZag(true);
- }
- if (newJoin.getJoinType().isOuterJoin()) {
- newJoin =
JoinUtils.adjustJoinConjunctsNullable(newJoin);
- }
- return newJoin;
- }).toRule(RuleType.LOGICAL_JOIN_COMMUTE);
+ .then(this::commute)
+ .toRule(RuleType.LOGICAL_JOIN_COMMUTE);
+ }
+
+ private Rule buildIvmNullRepairCommute() {
+ return logicalJoin()
+ .when(join -> join.getJoinType().isLeftAntiJoin())
+ .when(join ->
join.getJoinReorderContext().isIvmNullRepairAntiJoin())
+ .when(this::checkReorder)
+ .whenNot(LogicalJoin::hasDistributeHint)
+ .whenNot(LogicalJoin::isMarkJoin)
+ .whenNot(join -> join.getHashJoinConjuncts().isEmpty())
+ .thenApply(ctx -> {
+ LogicalJoin<GroupPlan, GroupPlan> join = ctx.root;
+ Group snapshot = join.right().getGroup();
+ // Keep the original plan whenever its snapshot could
qualify for automatic broadcast.
+ // The row cutoff alone suffices to disqualify broadcast
without relying on column widths.
+ double rowLimit =
ctx.cascadesContext.getConnectContext().getSessionVariable()
+ .getBroadcastRowCountLimit();
+ return snapshot.isStatsReliable() &&
snapshot.getStatistics().getRowCount() > rowLimit
+ ? commute(join) : null;
+ })
+ .toRule(RuleType.LOGICAL_JOIN_COMMUTE);
+ }
+
+ private LogicalJoin<? extends Plan, ? extends Plan>
commute(LogicalJoin<GroupPlan, GroupPlan> join) {
+ LogicalJoin<? extends Plan, ? extends Plan> newJoin = join.swap();
+ newJoin.getJoinReorderContext().copyFrom(join.getJoinReorderContext());
+ newJoin.getJoinReorderContext().setHasCommute(true);
+ if (swapType == SwapType.ZIG_ZAG && isNotBottomJoin(join)) {
+ newJoin.getJoinReorderContext().setHasCommuteZigZag(true);
+ }
+ if (newJoin.getJoinType().isOuterJoin()) {
+ newJoin = JoinUtils.adjustJoinConjunctsNullable(newJoin);
+ }
+ return newJoin;
}
enum SwapType {
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/join/JoinReorderContext.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/join/JoinReorderContext.java
index 716df428b14..17aad480192 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/join/JoinReorderContext.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/join/JoinReorderContext.java
@@ -41,6 +41,8 @@ public class JoinReorderContext {
private boolean isLeadingJoin = false;
private boolean isSaltJoinGenerated = false;
+ // Provenance of this join, retained when clear() resets exploration state.
+ private boolean ivmNullRepairAntiJoin;
public JoinReorderContext() {
}
@@ -57,6 +59,7 @@ public class JoinReorderContext {
this.hasCommuteZigZag = joinReorderContext.hasCommuteZigZag;
this.isLeadingJoin = joinReorderContext.isLeadingJoin;
this.isSaltJoinGenerated = joinReorderContext.isSaltJoinGenerated;
+ this.ivmNullRepairAntiJoin = joinReorderContext.ivmNullRepairAntiJoin;
}
/**
@@ -73,6 +76,14 @@ public class JoinReorderContext {
isSaltJoinGenerated = false;
}
+ public boolean isIvmNullRepairAntiJoin() {
+ return ivmNullRepairAntiJoin;
+ }
+
+ public void markIvmNullRepairAntiJoin() {
+ ivmNullRepairAntiJoin = true;
+ }
+
public boolean hasCommute() {
return hasCommute;
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
index d10d0a4b12b..e2bc82bf2e7 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
@@ -255,26 +255,16 @@ public class StatsCalculator extends
DefaultPlanVisitor<Statistics, Void> {
LOG.debug("disable join reorder since row count not
available: "
+ scan.getTable().getNameWithFullQualifiers());
}
- try {
- context.getConnectContext().getSessionVariable()
- .setVarOnce(SessionVariable.DISABLE_JOIN_REORDER,
"true");
- } catch (Exception e) {
- LOG.error("disable NereidsJoinReorderOnce failed", e);
- }
+ disableJoinReorderForInvalidStats(context);
return Optional.of("table[" + scan.getTable().getName() + "]
row count is invalid");
}
if (scan instanceof OlapScan) {
// ndv abnormal
Optional<String> reason =
calculator.checkNdvValidation((OlapScan) scan, rowCount);
if (reason.isPresent()) {
- try {
- context.getConnectContext().getSessionVariable()
-
.setVarOnce(SessionVariable.DISABLE_JOIN_REORDER, "true");
- if (enableDebugLog) {
- LOG.debug("disable join reorder since col stats
invalid: " + reason.get());
- }
- } catch (Exception e) {
- LOG.error("disable NereidsJoinReorderOnce failed", e);
+ disableJoinReorderForInvalidStats(context);
+ if (enableDebugLog) {
+ LOG.debug("disable join reorder since col stats
invalid: " + reason.get());
}
return reason;
}
@@ -283,6 +273,14 @@ public class StatsCalculator extends
DefaultPlanVisitor<Statistics, Void> {
return Optional.empty();
}
+ private static void disableJoinReorderForInvalidStats(CascadesContext
context) {
+ SessionVariable sessionVariable =
context.getConnectContext().getSessionVariable();
+ if (!sessionVariable.isDisableJoinReorder()
+ &&
sessionVariable.setVarOnce(SessionVariable.DISABLE_JOIN_REORDER, "true")) {
+ context.getStatementContext().markJoinReorderDisabledByStats();
+ }
+ }
+
/**
* estimate
*/
diff --git
a/regression-test/data/mtmv_p0/ivm/test_ivm_null_repair_anti_join.out
b/regression-test/data/mtmv_p0/ivm/test_ivm_null_repair_anti_join.out
new file mode 100644
index 00000000000..990d4a7eedb
--- /dev/null
+++ b/regression-test/data/mtmv_p0/ivm/test_ivm_null_repair_anti_join.out
@@ -0,0 +1,13 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !small --
+1 1
+1 2
+2 3
+3 4
+4 \N
+
+-- !large --
+1 2
+2 \N
+3 4
+4 5
diff --git
a/regression-test/suites/mtmv_p0/ivm/test_ivm_null_repair_anti_join.groovy
b/regression-test/suites/mtmv_p0/ivm/test_ivm_null_repair_anti_join.groovy
new file mode 100644
index 00000000000..4b5a4c6549f
--- /dev/null
+++ b/regression-test/suites/mtmv_p0/ivm/test_ivm_null_repair_anti_join.groovy
@@ -0,0 +1,110 @@
+// 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.
+
+suite("test_ivm_null_repair_anti_join", "nonConcurrent") {
+ sql "SET enable_materialized_view_rewrite = false"
+ sql "SET enable_dml_materialized_view_rewrite = false"
+ sql "DROP MATERIALIZED VIEW IF EXISTS ivm_repair_anti_mv"
+ sql "DROP TABLE IF EXISTS ivm_repair_anti_retained"
+ sql "DROP TABLE IF EXISTS ivm_repair_anti_snapshot"
+
+ sql """
+ CREATE TABLE ivm_repair_anti_retained (id INT NOT NULL, k INT NOT NULL)
+ UNIQUE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_num"="1",
"enable_unique_key_merge_on_write"="true",
+ "changelog.enable"="true",
"changelog.need_historical_value"="true")
+ """
+ sql """
+ CREATE TABLE ivm_repair_anti_snapshot (id INT NOT NULL, k INT NOT NULL)
+ UNIQUE KEY(id)
+ PARTITION BY RANGE(id) (
+ PARTITION p_changed VALUES LESS THAN (100),
+ PARTITION p_stable VALUES LESS THAN (MAXVALUE)
+ )
+ DISTRIBUTED BY HASH(id) BUCKETS 4
+ PROPERTIES ("replication_num"="1",
"enable_unique_key_merge_on_write"="true",
+ "changelog.enable"="true",
"changelog.need_historical_value"="true")
+ """
+ sql "INSERT INTO ivm_repair_anti_retained VALUES (1, 10), (2, 20), (3,
30), (4, 40)"
+ sql "INSERT INTO ivm_repair_anti_snapshot VALUES (1, 10), (2, 10), (3, 20)"
+ // Simulate an old NDV on one column after the table row count shrinks.
Each column statistic is
+ // valid on its own, and the final scan validation detects the mismatch
against the new table count.
+ sql """
+ ALTER TABLE ivm_repair_anti_retained MODIFY COLUMN id SET STATS
+ ('row_count'='1000', 'ndv'='1000', 'min_value'='1', 'max_value'='1000')
+ """
+ sql """
+ ALTER TABLE ivm_repair_anti_retained MODIFY COLUMN k SET STATS
+ ('row_count'='4', 'ndv'='4', 'min_value'='10', 'max_value'='40')
+ """
+ sql """
+ CREATE MATERIALIZED VIEW ivm_repair_anti_mv
+ BUILD DEFERRED REFRESH INCREMENTAL ON MANUAL
+ DISTRIBUTED BY RANDOM BUCKETS 1
+ PROPERTIES ("replication_num"="1")
+ AS SELECT a.id AS retained_id, b.id AS matching_id
+ FROM ivm_repair_anti_retained a LEFT OUTER JOIN
ivm_repair_anti_snapshot b ON a.k = b.k
+ """
+
+ def refresh = { String mode ->
+ sql "REFRESH MATERIALIZED VIEW ivm_repair_anti_mv ${mode}"
+ waitingMTMVTaskFinishedByMvName("ivm_repair_anti_mv")
+ }
+ def explainAntiJoin = { String type, boolean broadcast ->
+ explain {
+ sql "SHAPE PLAN REFRESH MATERIALIZED VIEW ivm_repair_anti_mv
INCREMENTAL"
+ check { plan ->
+ def antiJoins = plan.readLines().findAll {
it.contains("ANTI_JOIN") }
+ !antiJoins.isEmpty() && antiJoins.every {
+ it.contains("hashJoin[${type} ") && (!broadcast ||
it.contains(" broadcast]"))
+ }
+ }
+ }
+ }
+
+ // REFRESH uses an admin planning context. A small global row cap
exercises both sides of the
+ // broadcast threshold with a modest fixture.
+ def cap = sql_return_maparray("SHOW GLOBAL VARIABLES LIKE
'broadcast_row_count_limit'")[0].Value
+ def reorderDisabled = sql_return_maparray("SHOW GLOBAL VARIABLES LIKE
'disable_join_reorder'")[0].Value
+ try {
+ sql "SET GLOBAL broadcast_row_count_limit = 128"
+ sql "SET GLOBAL disable_join_reorder = false"
+ refresh("COMPLETE")
+ sql "INSERT INTO ivm_repair_anti_snapshot VALUES (4, 30)"
+ explainAntiJoin("LEFT_ANTI_JOIN", true)
+ refresh("INCREMENTAL")
+ order_qt_small "SELECT retained_id, matching_id FROM
ivm_repair_anti_mv"
+
+ sql """
+ INSERT INTO ivm_repair_anti_snapshot
+ SELECT number + 100, number + 100 FROM numbers("number"="4096")
+ """
+ refresh("COMPLETE")
+ sql "INSERT INTO ivm_repair_anti_snapshot VALUES (5, 40)"
+ sql "DELETE FROM ivm_repair_anti_snapshot WHERE id IN (1, 3)"
+ explainAntiJoin("RIGHT_ANTI_JOIN", false)
+
+ sql "SET GLOBAL disable_join_reorder = true"
+ explainAntiJoin("LEFT_ANTI_JOIN", false)
+ sql "SET GLOBAL disable_join_reorder = false"
+ refresh("INCREMENTAL")
+ order_qt_large "SELECT retained_id, matching_id FROM
ivm_repair_anti_mv"
+ } finally {
+ sql "SET GLOBAL broadcast_row_count_limit = ${cap}"
+ sql "SET GLOBAL disable_join_reorder = ${reorderDisabled}"
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]