hello-stephen commented on code in PR #71440:
URL: https://github.com/apache/doris/pull/71440#discussion_r4802417658


##########
fe/fe-core/src/test/java/org/apache/doris/mtmv/ivm/IvmAggDeltaHandlerTest.java:
##########
@@ -916,6 +921,131 @@ void 
testGroupedAggFullKeysWithSameNamedGroupKeysKeepsDistinctDeltaSlots() {
         
Assertions.assertTrue(deltaSides.contains(deltaKeySlots.get(1).getExprId()));
     }
 
+    private void markMvKeyColumns(MTMV mtmv, String... keyColNames) {
+        Set<String> keySet = new HashSet<>(Arrays.asList(keyColNames));
+        for (Column col : mtmv.getBaseSchema(true)) {
+            if (keySet.contains(col.getName())) {
+                col.setIsKey(true);
+            }
+        }
+    }
+
+    private AggRewriteResult rewriteAggPlanWithMvKeys(Plan plan, List<Slot> 
identityKeys, String... mvKeyCols) {
+        ConnectContext connectContext = newConnectContext();
+        JobContext jobContext = newJobContextForRoot(plan, connectContext);
+        Plan normalizedPlan = new IvmNormalizeUniqKeysMTMV().normalize(plan, 
jobContext);
+        IvmRewriteResult rewriteResult = publishNormalizeResult(jobContext, 
normalizedPlan);
+        PlanBundle bundle = new PlanBundle(connectContext, normalizedPlan, 
rewriteResult);
+        if (identityKeys != null) {
+            bundle.rewriteResult.setIdentityKeySlots(identityKeys);
+        }
+        MTMV mtmv = buildMtmvFromPlan(bundle.normalizedPlan.getOutput());
+        markMvKeyColumns(mtmv, mvKeyCols);
+        mtmv.getIvmInfo().advanceSequencePrefix();
+        mtmv.getIvmInfo().advanceSequencePrefix();
+        Plan rewritten = new IvmDeltaRewriter().generateIncrRefreshPlan(
+                bundle.normalizedPlan, bundle.rewriteResult,
+                IvmRewriteContext.incremental(mtmv), bundle.connectContext);
+        Assertions.assertNotNull(rewritten);
+        InsertIntoTableCommand command = new IvmIncrRefreshManager()
+                .buildInsertCommand((LogicalPlan) rewritten, mtmv);
+        UnboundTableSink<?> sink = getSink(command);
+        return new AggRewriteResult(bundle, mtmv, sink, (LogicalProject<?>) 
sink.child());
+    }
+
+    @Test
+    void testApplyJoinAddsVisibleMvKeyConjunctsWithoutFullKeys() {
+        LogicalOlapScan scan = buildScan();
+        LogicalAggregate<LogicalOlapScan> agg = buildGroupedAgg(scan);
+        AggRewriteResult result = rewriteAggPlanWithMvKeys(agg, null, "id");
+        LogicalJoin<?, ?> join = getJoin(result);
+
+        Assertions.assertEquals(2, join.getHashJoinConjuncts().size(),
+                "expected visible MV key conjunct plus row_id conjunct, got: " 
+ join.getHashJoinConjuncts());
+        Assertions.assertTrue(join.getHashJoinConjuncts().stream()
+                .anyMatch(c -> c instanceof NullSafeEqual && 
c.toSql().contains("id")
+                        && !c.toSql().contains(Column.IVM_ROW_ID_COL)));
+        Assertions.assertTrue(join.getHashJoinConjuncts().stream()
+                .anyMatch(c -> c instanceof NullSafeEqual && 
c.toSql().contains(Column.IVM_ROW_ID_COL)));
+    }
+
+    @Test
+    void testApplyJoinDeduplicatesVisibleMvKeyWithFullKeys() {
+        LogicalOlapScan scan = buildScan();
+        Slot idSlot = scan.getOutput().get(0);
+        LogicalAggregate<LogicalOlapScan> agg = buildGroupedAgg(scan);
+        AggRewriteResult result = rewriteAggPlanWithMvKeys(agg, 
ImmutableList.of(idSlot), "id");
+        LogicalJoin<?, ?> join = getJoin(result);
+
+        Assertions.assertEquals(2, join.getHashJoinConjuncts().size(),
+                "visible MV key already covered by identityKeys must not 
duplicate conjuncts: "
+                        + join.getHashJoinConjuncts());
+    }
+
+    @Test
+    void testApplyJoinMapsAliasedSameNamedGroupKeysBySlotIdentity() {
+        LogicalOlapScan leftScan = buildScanForTable(1L, "l");
+        LogicalOlapScan rightScan = buildScanForTable(2L, "r");
+        Slot leftId = leftScan.getOutput().get(0);
+        Slot rightId = rightScan.getOutput().get(0);
+        LogicalJoin<LogicalOlapScan, LogicalOlapScan> joinInput = new 
LogicalJoin<>(
+                JoinType.INNER_JOIN, ImmutableList.of(new EqualTo(leftId, 
rightId)),
+                leftScan, rightScan, JoinReorderContext.EMPTY);
+        Alias countAlias = new Alias(new Count(), "cnt");
+        LogicalAggregate<LogicalJoin<LogicalOlapScan, LogicalOlapScan>> agg = 
new LogicalAggregate<>(
+                ImmutableList.of(leftId, rightId),
+                ImmutableList.of(leftId, rightId, countAlias),
+                true, Optional.empty(), joinInput);
+        LogicalProject<LogicalAggregate<LogicalJoin<LogicalOlapScan, 
LogicalOlapScan>>> topProject =
+                new LogicalProject<>(ImmutableList.of(
+                        new Alias(leftId, "left_id"),
+                        new Alias(rightId, "right_id"),
+                        countAlias.toSlot()), agg);
+
+        AggRewriteResult result = rewriteAggPlanWithMvKeys(topProject, null, 
"left_id", "right_id");
+        LogicalJoin<?, ?> join = getJoin(result);
+        LogicalProject<?> deltaTop = getDeltaTopProject(result);
+        Slot deltaLeftId = deltaTop.getOutput().get(1);
+        Slot deltaRightId = deltaTop.getOutput().get(2);
+
+        List<Expression> keyConjuncts = join.getHashJoinConjuncts().stream()
+                .filter(c -> c instanceof NullSafeEqual && 
!c.toSql().contains(Column.IVM_ROW_ID_COL))
+                .collect(Collectors.toList());
+        Assertions.assertEquals(2, keyConjuncts.size(),
+                "expected aliased visible MV keys to produce distinct 
conjuncts: " + keyConjuncts);
+        Set<ExprId> deltaSides = keyConjuncts.stream()

Review Comment:
   [P3] Assert each MV alias maps to its own delta key
   
   The unordered set of right-hand `ExprId`s also passes for `mv.left_id <=> 
delta.r.id` and `mv.right_id <=> delta.l.id`. The input joins on `l.id = r.id`, 
so row values also hide the swap. Assert the delta `ExprId` for each named MV 
column, and join on another column so the two grouped IDs can differ.



##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmAggDeltaHandler.java:
##########
@@ -436,15 +443,134 @@ private ImmutableList<Expression> 
buildApplyJoinConjuncts(IvmIncrRefreshContext
                 if (deltaKey == null) {
                     continue;
                 }
+                addedMvSlots.add(mvKey.getExprId());
+                conjuncts.add(new NullSafeEqual(mvKey, deltaKey));
+            }
+        }
+        // When an aggregate MV defines explicit KEY, PARTITION BY, or HASH 
distribution columns,
+        // those visible columns precede __DORIS_IVM_ROW_ID_COL__ in the 
physical schema. Adding
+        // redundant equality conjuncts on any visible key column that 
directly passes through a
+        // group key unlocks Bucket Shuffle Join, dynamic partition pruning, 
and prefix/ZoneMap
+        // pruning even without ivm_use_full_keys.
+        Map<String, Integer> directGroupKeyByMvColName = 
resolveDirectGroupKeyMapping(

Review Comment:
   [P3] Skip lineage tracing when the MV has no visible physical key
   
   A grouped MV with the default layout is keyed and distributed on the hidden 
row ID. This call still traces every visible output, scanning each ancestor 
project and the group-key list for each output. That adds quadratic planning 
work to wide grouped refreshes with no eligible visible predicate. Discover 
visible catalog keys before walking the plan and trace only those outputs. Use 
catalog visibility or original-case names for this check, because 
`getDistributionColumnNames()` lowercases the hidden row ID before the 
case-sensitive `isIvmHiddenColumn()` test.



##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmAggDeltaHandler.java:
##########
@@ -436,15 +443,134 @@ private ImmutableList<Expression> 
buildApplyJoinConjuncts(IvmIncrRefreshContext
                 if (deltaKey == null) {
                     continue;
                 }
+                addedMvSlots.add(mvKey.getExprId());
+                conjuncts.add(new NullSafeEqual(mvKey, deltaKey));
+            }
+        }
+        // When an aggregate MV defines explicit KEY, PARTITION BY, or HASH 
distribution columns,
+        // those visible columns precede __DORIS_IVM_ROW_ID_COL__ in the 
physical schema. Adding
+        // redundant equality conjuncts on any visible key column that 
directly passes through a
+        // group key unlocks Bucket Shuffle Join, dynamic partition pruning, 
and prefix/ZoneMap

Review Comment:
   [P2] The nullable apply key cannot drive runtime-filter pruning
   
   For a partitioned aggregate MV grouped by a nullable `dt`, the apply join 
retains `mv.dt <=> delta.dt`. `RuntimeFilterGenerator` starts pushdown at the 
builder join itself, and `RuntimeFilterPushDownVisitor.visitPhysicalHashJoin` 
stops at a right outer join for `<=>` before reaching the MV scan. If the join 
commutes to a left outer join, `RuntimeFilterGenerator` skips it. The extra 
hash key therefore supplies no runtime filter for dynamic partition or storage 
pruning in this case. If scan pruning is part of the intended change, please 
cover it with a physical refresh plan test. Otherwise, scope the pruning claim 
to the supported cases.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to