github-actions[bot] commented on code in PR #62628:
URL: https://github.com/apache/doris/pull/62628#discussion_r3122091477


##########
regression-test/suites/nereids_p0/hash_shuffle_key_prune/distinct_mixed.groovy:
##########
@@ -0,0 +1,258 @@
+// 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.
+
+// 
===========================================================================================
+// Category 08: Distinct Partition and Mixed Join — DA01-DA05, M01-M03
+// 
===========================================================================================
+//
+// Purpose
+//   Validate two kinds of special scenarios:
+//   A. COUNT(DISTINCT) cases: DISTINCT introduces an extra partition 
operator, so pruning must optimize
+//      both the partition and agg shuffle keys
+//   B. Mixed Join: pruning behavior when Agg hot_values and Join probe-side 
hot_values=null are mixed
+//
+// DA Group Case List
+//   DA01: High NDV + COUNT(DISTINCT g) + agg_phase=2 -> pruning works 
(positive)
+//   DA02: Low NDV + COUNT(DISTINCT g) -> NDV is insufficient -> no pruning 
(negative)
+//   DA03: Mixed COUNT(DISTINCT g) + AVG(v) aggregation -> pruning still works 
(positive)
+//   DA04: agg_phase=4 (2+2 mode) -> pruning still works (positive)
+//   DA05: count(distinct [skew] g) -> explicit skew-distinct guard -> no 
pruning (negative)
+//
+// M Group Case List
+//   M01: t_08_m_agg (hot_values='') JOIN t_08_m_probe (hot_values=null)
+//        join on 6 columns = group by 6 columns -> conservative -> plan 
unchanged (negative)
+//   M02: join on 3 columns < group by 6 columns, but probe-side 
hot_values=null -> conservative -> plan unchanged (negative)
+//   M03: Probe side uses an agg table with hot_values=null -> conservative -> 
plan unchanged (negative)
+//
+// Validation
+//   Both DA and M groups use hard assertions.
+//   Every case verifies that OFF/ON results are identical.
+// 
===========================================================================================
+suite("distinct_mixed", "agg_shuffle_prune_func") {
+    sql """set enable_nereids_planner=true;"""
+    sql """set enable_fallback_to_original_planner=false;"""
+    sql """set enable_sql_cache=false;"""
+    sql """set enable_query_cache=false;"""
+    sql """set agg_phase=0;"""
+
+    def dbName = context.config.getDbNameByFile(context.file)
+    sql "create database if not exists ${dbName};"
+    sql "use ${dbName};"
+
+    def tptn = 8
+    sql "set parallel_fragment_exec_instance_num=1;"
+    sql "set parallel_pipeline_task_num=${tptn};"
+    sql "set be_number_for_test=1;"
+
+    def qn = (tptn*512 + tptn*64).toString()
+    def R = "480000"
+    def lowNdv = "4"
+    def daQn = "60000"
+    def esc = { Object v -> 
v==null?"null":v.toString().replace("\\","\\\\").replace("'","\\'") }
+    def ss = { String t,String c,String n,String nn,String ds,String mi,String 
ma,String hv ->
+        def hvc = hv==null ? "" : ", 'hot_values'='${esc(hv)}'"
+        sql "alter table ${t} modify column ${c} set stats 
('row_count'='${R}','ndv'='${esc(n)}','num_nulls'='${esc(nn)}','data_size'='${esc(ds)}','min_value'='${esc(mi)}','max_value'='${esc(ma)}'${hvc});"
+    }
+    def extractSigns = { String e ->
+        def s=[]; def m=(e=~/orderedShuffledColumns=\[([0-9,\s-]*)\]/); 
while(m.find()){s<<"["+m.group(1).replaceAll("\\s+","")+"]"}; s
+    }
+    def extractIdLists = { String e ->
+        def ids=[]; def m=(e=~/orderedShuffledColumns=\[([0-9,\s-]*)\]/)
+        while(m.find()){
+            def r=m.group(1).trim()
+            ids << (r.length()==0 ? [] : 
r.split(",").collect{it.trim()}.findAll{it.length()>0}.collect{Integer.parseInt(it)})
+        }
+        ids
+    }
+    def parseOrderedIds = { String line ->
+        def m=(line=~/orderedShuffledColumns=\[([0-9,\s-]*)\]/)
+        if (!m.find()) {
+            return null
+        }
+        def r=m.group(1).trim()
+        return (r.length()==0 ? [] : 
r.split(",").collect{it.trim()}.findAll{it.length()>0}.collect{Integer.parseInt(it)})
+    }
+    def subtreeText = { List<String> lines, int rootIndex ->
+        int rootIndent = lines[rootIndex].indexOf("Physical")
+        def collected = []
+        for (int i = rootIndex; i < lines.size(); i++) {
+            def line = lines[i]
+            int indent = line.indexOf("Physical")
+            if (i > rootIndex && indent >= 0 && indent <= rootIndent) {
+                break
+            }
+            collected << line
+        }
+        collected.join("\n")
+    }
+    def exprId = { String e,String c -> def 
m=(e=~("\\b"+java.util.regex.Pattern.quote(c)+"#(\\d+)\\b")); 
m.find()?Integer.parseInt(m.group(1)):null }
+    def findScopedExprId = { String e,String c -> def 
m=(e=~("\\b"+java.util.regex.Pattern.quote(c)+"#(\\d+)\\b")); 
m.find()?Integer.parseInt(m.group(1)):null }
+    def norm = { rows -> 
rows.collect{r->r.collect{v->v==null?"NULL":v.toString()}.join("||")}.sort() }
+    def explainText = { String q -> (sql "explain physical plan " + q).collect 
{ it[0].toString() }.join("\n") }
+    def findDistinctAggShuffleCtx = { String e ->
+        def lines = e.readLines()
+        int rootIndex = -1
+        for (int i = 0; i < lines.size(); i++) {
+            if (lines[i].contains("PhysicalHashAggregate") && 
lines[i].contains("aggPhase=DISTINCT_GLOBAL")) {
+                rootIndex = i
+                break
+            }
+        }
+        if (rootIndex < 0) {
+            for (int i = 0; i < lines.size(); i++) {
+                if (lines[i].contains("PhysicalHashAggregate") && 
lines[i].contains("aggPhase=GLOBAL")) {
+                    rootIndex = i
+                    break
+                }
+            }
+        }
+        if (rootIndex < 0) {
+            return null
+        }
+        int rootIndent = lines[rootIndex].indexOf("PhysicalHashAggregate")
+        def ctxs = []
+        for (int i = rootIndex + 1; i < lines.size(); i++) {
+            def line = lines[i]
+            int indent = line.indexOf("Physical")
+            if (indent < 0) {
+                continue
+            }
+            if (indent <= rootIndent) {
+                break
+            }
+            if (line.contains("PhysicalDistribute") && 
line.contains("orderedShuffledColumns=")) {
+                ctxs << [ids: parseOrderedIds(line), subtree: 
subtreeText(lines, i)]
+            }
+        }
+        [subtree: subtreeText(lines, rootIndex), ctxs: ctxs]
+    }
+
+    // DA-group test helper
+    def runDA = { String id,String q,boolean expChg,int ap ->
+        sql "set agg_phase=${ap};"; sql "set disable_nereids_rules='';"
+        sql "set enable_shuffle_key_prune=false;"
+        def eOff=explainText(q); def oS=extractSigns(eOff); def 
offCtx=findDistinctAggShuffleCtx(eOff)
+        sql "set enable_shuffle_key_prune=true;"
+        def eOn=explainText(q); def nS=extractSigns(eOn); def 
onCtx=findDistinctAggShuffleCtx(eOn)
+        def chg=(eOff!=eOn)
+        logger.info("${id}: oS=${oS}, nS=${nS}, offCtx=${offCtx}, 
onCtx=${onCtx}, changed=${chg}")
+        if(expChg){
+            assertTrue(chg,"${id}: signs should change")
+            assertTrue(offCtx!=null && onCtx!=null, "${id}: missing 
DISTINCT/global agg subtree")
+            assertTrue(!offCtx.ctxs.isEmpty() && 
offCtx.ctxs.size()==onCtx.ctxs.size(),
+                "${id}: expected matching DISTINCT/global distribute lists, 
got off=${offCtx}, on=${onCtx}")
+            def target = findScopedExprId(onCtx.subtree, "a")
+            assertTrue(target!=null, "${id}: missing exprId for a")
+            assertTrue(offCtx.ctxs.any{it.ids.size()>1 && 
it.ids.contains(target)},
+                "${id}: expected at least one multi-key DISTINCT/global 
shuffle containing a/${target} before pruning, got ${offCtx.ctxs}")
+            assertTrue(onCtx.ctxs.every{it.ids.size()==1 && it.ids[0]==target},

Review Comment:
   This assertion is stronger than the implementation contract. 
`ShuffleKeyPruner.tryPruneGlobalAgg()` only rewrites the **direct child** 
`PhysicalDistribute` of the target `GLOBAL` / `DISTINCT_GLOBAL` aggregate, but 
this helper walks the whole subtree and requires **every** `PhysicalDistribute` 
under it to collapse to `[a]`. A valid extra exchange inside the subtree would 
make DA01/DA03/DA04 fail even though the pruned child is correct. Please scope 
the check to the aggregate's direct child distribute, like the FE unit test 
does.



##########
regression-test/suites/nereids_p0/hash_shuffle_key_prune/join_key_prune.groovy:
##########
@@ -0,0 +1,281 @@
+// 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.
+
+// 
===========================================================================================
+// Category 07: Pure Join Shuffle Key Optimization — JK01-JK08
+// 
===========================================================================================
+//
+// Purpose
+//   Validate pure Join shuffle-key optimization outside Agg scenarios.
+//   When two tables use Shuffle Hash Join and the join key contains multiple 
columns,
+//   pruning can reduce the number of columns participating in hash 
computation and lower shuffle cost.
+//
+// Note
+//   Join shuffle-key pruning is cost-based, but we keep the environment 
deterministic with fixed statistics
+//   and be_number_for_test=1, then use hard assertions for validation.
+//
+// Case List
+//   JK01: All join keys on both sides have high NDV + no skew -> can be 
pruned (positive)
+//   JK02: All join keys are skewed, but step 2 still removes the string key 
when numeric combined NDV is high -> pruning works (positive)
+//   JK03: Numeric columns are skewed while varchar is balanced -> single-key 
selection can still prune on varchar (positive)
+//   JK04: Left table lacks statistics -> conservative -> no pruning (negative)
+//   JK05: Left table has hot_values=null -> not sampled -> conservative -> no 
pruning (negative)
+//   JK06: Verify the switch works -> OFF keeps the full join shuffle key, ON 
can prune
+//   JK07: join [shuffle[skew(...)] ] hint -> explicit skew guard -> no 
pruning (negative)
+//   JK08: All keys are skewed and numeric combined NDV is too low for step 2 
-> no pruning (negative)
+//
+// Validation
+//   Fix join reorder and turn off runtime filters to keep the plan stable.
+//   Compare OFF/ON plan changes and result consistency.
+// 
===========================================================================================
+suite("join_key_prune", "agg_shuffle_prune_func") {
+    sql """set enable_nereids_planner=true;"""
+    sql """set enable_fallback_to_original_planner=false;"""
+    sql """set enable_sql_cache=false;"""
+    sql """set enable_query_cache=false;"""
+    sql """set agg_phase=0;"""
+
+    def dbName = context.config.getDbNameByFile(context.file)
+    sql "create database if not exists ${dbName};"
+    sql "use ${dbName};"
+
+    def tptn = 8
+    sql "set parallel_fragment_exec_instance_num=1;"
+    sql "set parallel_pipeline_task_num=${tptn};"
+    sql "set be_number_for_test=1;"
+
+    def qn = (tptn*512 + tptn*64).toString()
+    def R = "480000"
+    def esc = { Object v -> 
v==null?"null":v.toString().replace("\\","\\\\").replace("'","\\'") }
+    def ss = { String t,String c,String n,String nn,String ds,String mi,String 
ma,String hv ->
+        def hvc = hv==null ? "" : ", 'hot_values'='${esc(hv)}'"
+        sql "alter table ${t} modify column ${c} set stats 
('row_count'='${R}','ndv'='${esc(n)}','num_nulls'='${esc(nn)}','data_size'='${esc(ds)}','min_value'='${esc(mi)}','max_value'='${esc(ma)}'${hvc});"
+    }
+    def extractSigns = { String e ->
+        def s=[]; def m=(e=~/orderedShuffledColumns=\[([0-9,\s-]*)\]/); 
while(m.find()){s<<"["+m.group(1).replaceAll("\\s+","")+"]"}; s
+    }
+    def extractKeyCounts = { String e ->
+        def c=[]; def m=(e=~/orderedShuffledColumns=\[([0-9,\s-]*)\]/)
+        while(m.find()){
+            def r=m.group(1).trim()
+            def p=r.length()==0 ? [] : 
r.split(",").collect{it.trim()}.findAll{it.length()>0}
+            c<<p.size()
+        }
+        c
+    }
+    def parseOrderedIds = { String line ->
+        def m = (line =~ /orderedShuffledColumns=\[([0-9,\s-]*)\]/)
+        if (!m.find()) {
+            return null
+        }
+        def r = m.group(1).trim()
+        return (r.length()==0 ? [] : 
r.split(",").collect{it.trim()}.findAll{it.length()>0}.collect{Integer.parseInt(it)})
+    }
+    def subtreeText = { List<String> lines, int rootIndex, int stopIndent ->
+        int rootIndent = lines[rootIndex].indexOf("Physical")
+        def collected = []
+        for (int i = rootIndex; i < lines.size(); i++) {
+            def line = lines[i]
+            int indent = line.indexOf("Physical")
+            if (i > rootIndex && indent >= 0 && indent <= stopIndent) {
+                break
+            }
+            collected << line
+        }
+        collected.join("\n")
+    }
+    def findScopedExprId = { String e,String c ->
+        def m=(e=~("\\b"+java.util.regex.Pattern.quote(c)+"#(\\d+)\\b"))
+        m.find()?Integer.parseInt(m.group(1)):null
+    }
+    def findFirstJoinChildShuffleCtxs = { String e ->
+        def lines = e.readLines()
+        int joinIndex = -1
+        for (int i = 0; i < lines.size(); i++) {
+            if (lines[i].contains("PhysicalHashJoin")) {
+                joinIndex = i
+                break
+            }
+        }
+        if (joinIndex < 0) {
+            return null
+        }
+        int joinIndent = lines[joinIndex].indexOf("PhysicalHashJoin")
+        def childRootIndices = []
+        Integer childRootIndent = null
+        for (int i = joinIndex + 1; i < lines.size(); i++) {
+            def line = lines[i]
+            int indent = line.indexOf("Physical")
+            if (indent < 0) {
+                continue
+            }
+            if (indent <= joinIndent) {
+                break
+            }
+            if (childRootIndent == null) {
+                childRootIndent = indent
+            }
+            if (indent == childRootIndent) {
+                childRootIndices << i
+            }
+        }
+        assertTrue(childRootIndices.size() >= 2, "missing join child roots in 
plan:\n${e}")
+        def childCtxs = childRootIndices.take(2).collect { idx ->

Review Comment:
   This helper is very sensitive to explain-text layout: it grabs the first 
textual `PhysicalHashJoin`, then assumes the first two textual child roots 
under it are the join children we want to validate. `ShuffleKeyPruner` works on 
the optimized plan tree, not on this textual ordering, so a harmless wrapper 
node / extra hash join / subtree reorder can break JKxx without any regression 
in the actual pruning logic. Please make the assertion less dependent on 'first 
join / first two child roots' ordering.



##########
regression-test/suites/nereids_p0/hash_shuffle_key_prune/join_parent.groovy:
##########
@@ -0,0 +1,316 @@
+// 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.
+
+// 
===========================================================================================
+// Category 06: Join Paths and Parent Requests — J01-J12, P01-P02
+// 
===========================================================================================
+//
+// Purpose
+//   Validate the interaction between Shuffle Key Pruning and Join operators, 
and verify the correctness of
+//   Parent Requests (where the parent asks the child to adjust its shuffle 
key to remove extra exchanges).
+//
+// Core Background
+//   - When Agg output is consumed by Join, the Agg shuffle key can be 
adjusted to a subset of the Join keys,
+//     avoiding the re-shuffle exchange before the Join.
+//   - tByB = distributed by hash(b) -> if group by includes b, distribution 
may already be satisfied -> no pruning
+//   - tByX = distributed by hash(x) -> x is not in group by -> shuffle is 
required -> pruning is possible
+//
+// J Group Case List
+//   J01: scan JOIN agg(tByB) -> distribution already satisfied -> no pruning 
(negative)
+//   J02: scan JOIN agg(tByX) -> shuffle required -> pruning works (positive)
+//   J03: agg(tByB) JOIN agg(tByB) -> both sides already satisfied -> no 
pruning (negative)
+//   J04: agg(tByX) JOIN agg(tByX) -> both sides require shuffle -> pruning 
works (positive)
+//   J05: LEFT JOIN + agg(tByX) -> same as J02 -> pruning works (positive)
+//   J06: LEFT SEMI JOIN -> pruning works (positive)
+//   J07: LEFT ANTI JOIN -> pruning works (positive)
+//   J08: agg(tByB) JOIN scan on a non-group-by column -> requirement not 
satisfied -> no pruning (negative)
+//   J09: scan JOIN scan -> no agg -> no pruning (negative)
+//   J10: agg on join output + all skewed columns -> no safe key -> no pruning 
(negative)
+//   J11: parent-key-subset positive case -> agg shuffle key is adjusted to a 
subset of join keys
+//   J12: parent-key-subset negative case -> low-NDV columns do not qualify -> 
no adjustment
+//
+// P Group Case List
+//   P01: subquery agg -> parent agg -> inner distribution already satisfied 
-> no pruning (negative)
+//   P02: subquery agg -> window(partition by) -> inner distribution already 
satisfied -> no pruning (negative)
+//
+// Validation
+//   Use run() to check orderedShuffledColumns changes;
+//   use runParent() to check how agg_shuffle_use_parent_key adjusts shuffle 
keys.
+// 
===========================================================================================
+suite("join_parent", "agg_shuffle_prune_func") {
+    sql """set enable_nereids_planner=true;"""
+    sql """set enable_fallback_to_original_planner=false;"""
+    sql """set enable_sql_cache=false;"""
+    sql """set enable_query_cache=false;"""
+    sql """set agg_phase=0;"""
+
+    def dbName = context.config.getDbNameByFile(context.file)
+    sql "create database if not exists ${dbName};"
+    sql "use ${dbName};"
+
+    def tptn = 8
+    sql "set parallel_fragment_exec_instance_num=1;"
+    sql "set parallel_pipeline_task_num=${tptn};"
+    sql "set be_number_for_test=1;"
+
+    def qn = (tptn*512 + tptn*64).toString()
+    def ln = "4"
+    def R = "480000"
+    def esc = { Object v -> 
v==null?"null":v.toString().replace("\\","\\\\").replace("'","\\'") }
+    def ss = { String t,String c,String n,String nn,String ds,String mi,String 
ma,String hv ->
+        def hvc = hv==null ? "" : ", 'hot_values'='${esc(hv)}'"
+        sql "alter table ${t} modify column ${c} set stats 
('row_count'='${R}','ndv'='${esc(n)}','num_nulls'='${esc(nn)}','data_size'='${esc(ds)}','min_value'='${esc(mi)}','max_value'='${esc(ma)}'${hvc});"
+    }
+    def extractSigns = { String e ->
+        def s=[]; def m=(e=~/orderedShuffledColumns=\[([0-9,\s-]*)\]/); 
while(m.find()){s<<"["+m.group(1).replaceAll("\\s+","")+"]"}; s
+    }
+    def extractSingle = { String e ->
+        def ids=[]; def m=(e=~/orderedShuffledColumns=\[([0-9,\s-]*)\]/)
+        while(m.find()){def r=m.group(1).trim(); if(r.length()==0)continue; 
def p=r.split(",").collect{it.trim()}.findAll{it.length()>0}; 
if(p.size()==1)ids<<Integer.parseInt(p[0])}; ids
+    }
+    def exprId = { String e,String c -> def 
m=(e=~("\\b"+java.util.regex.Pattern.quote(c)+"#(\\d+)\\b")); 
m.find()?Integer.parseInt(m.group(1)):null }
+    def norm = { rows -> 
rows.collect{r->r.collect{v->v==null?"NULL":v.toString()}.join("||")}.sort() }
+    def parseOrderedIds = { String line ->
+        def m = (line =~ /orderedShuffledColumns=\[([0-9,\s-]*)\]/)
+        if (!m.find()) {
+            return null
+        }
+        def r = m.group(1).trim()
+        return (r.length() == 0) ? Collections.emptyList()
+                : r.split(",").collect { it.trim() }.findAll { it.length() > 0 
}.collect { Integer.parseInt(it) }
+    }
+    def subtreeText = { List<String> lines, int rootIndex ->
+        int rootIndent = lines[rootIndex].indexOf("Physical")
+        def collected = []
+        for (int i = rootIndex; i < lines.size(); i++) {
+            def line = lines[i]
+            int indent = line.indexOf("Physical")
+            if (i > rootIndex && indent >= 0 && indent <= rootIndent) {
+                break
+            }
+            collected << line
+        }
+        collected.join("\n")
+    }
+    def findScopedExprId = { String e, String c ->
+        def m = (e =~ ("\\b" + java.util.regex.Pattern.quote(c) + 
"#(\\d+)\\b"))
+        m.find() ? Integer.parseInt(m.group(1)) : null
+    }
+    def findGlobalAggChildShuffleCtx = { String e ->
+        def lines = e.readLines()
+        for (int i = 0; i < lines.size(); i++) {
+            def line = lines[i]
+            if (!(line.contains("PhysicalHashAggregate") && 
line.contains("aggPhase=GLOBAL"))) {
+                continue
+            }
+            int aggIndent = line.indexOf("PhysicalHashAggregate")
+            for (int j = i + 1; j < lines.size(); j++) {
+                def childLine = lines[j]
+                int childIndent = childLine.indexOf("Physical")
+                if (childIndent < 0) {
+                    continue
+                }
+                if (childIndent <= aggIndent) {
+                    break
+                }
+                if (childLine.contains("PhysicalDistribute") && 
childLine.contains("orderedShuffledColumns=")) {
+                    return [ids: parseOrderedIds(childLine), subtree: 
subtreeText(lines, j)]
+                }
+            }
+        }
+        return null
+    }
+    def assertGlobalAggChildCols = { String id, String e, List<String> cols ->
+        def ctx = findGlobalAggChildShuffleCtx(e)
+        assertTrue(ctx != null, "${id}: missing agg-side PhysicalDistribute")
+        def expectedIds = cols.collect { c ->
+            def eid = findScopedExprId(ctx.subtree, c)
+            assertTrue(eid != null, "${id}: missing exprId for ${c}")
+            eid
+        }
+        def actualIds = ctx.ids
+        assertTrue(actualIds == expectedIds,
+            "${id}: expected agg-side shuffle cols ${cols}/${expectedIds}, got 
${actualIds}")
+    }
+    def findAllGlobalAggChildShuffleCtxs = { String e ->
+        def lines = e.readLines()
+        def allCtxs = []
+        for (int i = 0; i < lines.size(); i++) {
+            def line = lines[i]
+            if (!(line.contains("PhysicalHashAggregate") && 
line.contains("aggPhase=GLOBAL"))) {
+                continue
+            }
+            int aggIndent = line.indexOf("PhysicalHashAggregate")
+            for (int j = i + 1; j < lines.size(); j++) {
+                def childLine = lines[j]
+                int childIndent = childLine.indexOf("Physical")
+                if (childIndent < 0) {
+                    continue
+                }
+                if (childIndent <= aggIndent) {
+                    break
+                }
+                if (childLine.contains("PhysicalDistribute") && 
childLine.contains("orderedShuffledColumns=")) {
+                    allCtxs << [ids: parseOrderedIds(childLine), subtree: 
subtreeText(lines, j)]
+                    break
+                }
+            }
+        }
+        allCtxs
+    }
+    def assertGlobalAggShapes = { String id, List<Map> ctxs, 
List<List<String>> expectedColsByAgg ->
+        assertTrue(ctxs.size() == expectedColsByAgg.size(),

Review Comment:
   `assertGlobalAggShapes()` binds the expectation to the textual order of 
**all** `GLOBAL` aggregates in the explain output. The pruning code rewrites 
each global aggregate's direct child distribute independently and does not 
guarantee that DFS/text order will stay stable. Queries like J04 can therefore 
false-fail on a valid branch reorder. Please key this to the specific aggregate 
under test instead of enumerating all global aggs by explain order.



##########
regression-test/suites/nereids_p0/hash_shuffle_key_prune/window_distinct_regression.groovy:
##########
@@ -0,0 +1,296 @@
+// 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.
+
+// 
===========================================================================================
+// Category 09: Window / Distinct Regression — WD01-WD04
+// 
===========================================================================================
+//
+// Purpose
+//   Add a more focused regression set for window / distinct patterns:
+//   - Window guard: ensure pruning is not triggered incorrectly under window 
wrappers
+//   - Distinct + Window: ensure DISTINCT aggregation keeps the correct prune 
/ no-prune behavior when wrapped by a window
+//
+// Case List
+//   WD01: window over inner agg, child distribution already satisfied -> no 
pruning (negative)
+//   WD02: count(distinct) + window, high NDV -> pruning works (positive)
+//   WD03: count(distinct) + avg + window, high NDV -> pruning still works 
(positive)
+//   WD04: count(distinct) + window, low NDV -> no pruning (negative)
+// 
===========================================================================================
+suite("window_distinct_regression", "agg_shuffle_prune_func") {
+    sql """set enable_nereids_planner=true;"""
+    sql """set enable_fallback_to_original_planner=false;"""
+    sql """set enable_sql_cache=false;"""
+    sql """set enable_query_cache=false;"""
+    sql """set agg_phase=0;"""
+    sql """set agg_shuffle_use_parent_key=false;"""
+    sql """set 
detail_shape_nodes='PhysicalHashAggregate,PhysicalDistribute,PhysicalWindow';"""
+
+    def dbName = context.config.getDbNameByFile(context.file)
+    sql "create database if not exists ${dbName};"
+    sql "use ${dbName};"
+
+    def tptn = 8
+    sql "set parallel_fragment_exec_instance_num=1;"
+    sql "set parallel_pipeline_task_num=${tptn};"
+    sql "set be_number_for_test=1;"
+
+    def highNdv = (tptn * 512 + tptn * 64).toString()
+    def lowNdv = "4"
+    def rowCount = "480000"
+    def esc = { Object v -> v == null ? "null" : v.toString().replace("\\", 
"\\\\").replace("'", "\\'") }
+    def ss = { String t, String c, String n, String nn, String ds, String mi, 
String ma, String hv ->
+        def hvc = hv == null ? "" : ", 'hot_values'='${esc(hv)}'"
+        sql "alter table ${t} modify column ${c} set stats 
('row_count'='${rowCount}','ndv'='${esc(n)}','num_nulls'='${esc(nn)}','data_size'='${esc(ds)}','min_value'='${esc(mi)}','max_value'='${esc(ma)}'${hvc});"
+    }
+    def extractSigns = { String e ->
+        def s = []
+        def m = (e =~ /orderedShuffledColumns=\[([0-9,\s-]*)\]/)
+        while (m.find()) {
+            s << "[" + m.group(1).replaceAll("\\s+", "") + "]"
+        }
+        s
+    }
+    def extractSingle = { String e ->
+        def ids = []
+        def m = (e =~ /orderedShuffledColumns=\[([0-9,\s-]*)\]/)
+        while (m.find()) {
+            def r = m.group(1).trim()
+            if (r.length() == 0) continue
+            def p = r.split(",").collect { it.trim() }.findAll { it.length() > 
0 }
+            if (p.size() == 1) ids << Integer.parseInt(p[0])
+        }
+        ids
+    }
+    def extractIdLists = { String e ->
+        def ids = []
+        def m = (e =~ /orderedShuffledColumns=\[([0-9,\s-]*)\]/)
+        while (m.find()) {
+            def r = m.group(1).trim()
+            ids << (r.length() == 0 ? [] : r.split(",").collect { it.trim() 
}.findAll { it.length() > 0 }.collect { Integer.parseInt(it) })
+        }
+        ids
+    }
+    def exprId = { String e, String c ->
+        def m = (e =~ ("\\b" + java.util.regex.Pattern.quote(c) + 
"#(\\d+)\\b"))
+        m.find() ? Integer.parseInt(m.group(1)) : null
+    }
+    def subtreeText = { List<String> lines, int rootIndex ->
+        int rootIndent = lines[rootIndex].indexOf("Physical")
+        def collected = []
+        for (int i = rootIndex; i < lines.size(); i++) {
+            def line = lines[i]
+            int indent = line.indexOf("Physical")
+            if (i > rootIndex && indent >= 0 && indent <= rootIndent) {
+                break
+            }
+            collected << line
+        }
+        collected.join("\n")
+    }
+    def parseOrderedIds = { String line ->
+        def m = (line =~ /orderedShuffledColumns=\[([0-9,\s-]*)\]/)
+        if (!m.find()) {
+            return null
+        }
+        def r = m.group(1).trim()
+        return (r.length() == 0 ? [] : r.split(",").collect { it.trim() 
}.findAll { it.length() > 0 }.collect { Integer.parseInt(it) })
+    }
+    def findDistinctAggShuffleCtx = { String e ->
+        def lines = e.readLines()
+        int rootIndex = -1
+        for (int i = 0; i < lines.size(); i++) {
+            if (lines[i].contains("PhysicalHashAggregate") && 
lines[i].contains("aggPhase=DISTINCT_GLOBAL")) {
+                rootIndex = i
+                break
+            }
+        }
+        if (rootIndex < 0) {
+            for (int i = 0; i < lines.size(); i++) {
+                if (lines[i].contains("PhysicalHashAggregate") && 
lines[i].contains("aggPhase=GLOBAL")) {
+                    rootIndex = i
+                    break
+                }
+            }
+        }
+        if (rootIndex < 0) {
+            return null
+        }
+        int rootIndent = lines[rootIndex].indexOf("PhysicalHashAggregate")
+        def ctxs = []
+        for (int i = rootIndex + 1; i < lines.size(); i++) {
+            def line = lines[i]
+            int indent = line.indexOf("Physical")
+            if (indent < 0) {
+                continue
+            }
+            if (indent <= rootIndent) {
+                break
+            }
+            if (line.contains("PhysicalDistribute") && 
line.contains("orderedShuffledColumns=")) {
+                ctxs << [ids: parseOrderedIds(line), subtree: 
subtreeText(lines, i)]
+            }
+        }
+        [subtree: subtreeText(lines, rootIndex), ctxs: ctxs]
+    }
+    def findScopedExprId = { String e, String c ->
+        def m = (e =~ ("\\b" + java.util.regex.Pattern.quote(c) + 
"#(\\d+)\\b"))
+        m.find() ? Integer.parseInt(m.group(1)) : null
+    }
+    def assertDistinctShufflePrunedToSingle = { String id, String eOff, String 
eOn, String c ->
+        def offCtx = findDistinctAggShuffleCtx(eOff)
+        def onCtx = findDistinctAggShuffleCtx(eOn)
+        assertTrue(offCtx != null && onCtx != null, "${id}: missing 
DISTINCT/global agg subtree")
+        assertTrue(!offCtx.ctxs.isEmpty() && !onCtx.ctxs.isEmpty(), "${id}: 
missing DISTINCT/global distribute ids, off=${offCtx}, on=${onCtx}")
+        def target = findScopedExprId(onCtx.subtree, c)
+        assertTrue(target != null, "${id}: missing exprId for ${c}")
+        assertTrue(offCtx.ctxs.size() == onCtx.ctxs.size(),
+            "${id}: expected matching DISTINCT/global distribute counts, 
off=${offCtx.ctxs}, on=${onCtx.ctxs}")
+        assertTrue(offCtx.ctxs.any { it.ids.size() > 1 && 
it.ids.contains(target) },
+            "${id}: expected at least one multi-key DISTINCT/global shuffle 
containing ${c}/${target} before pruning, got off=${offCtx.ctxs}")
+        assertTrue(onCtx.ctxs.every { it.ids.size() == 1 && it.ids[0] == 
target },

Review Comment:
   Same issue here: the pruning pass only rewrites the direct child 
`PhysicalDistribute` of the target global aggregate, but this helper requires 
all `PhysicalDistribute` nodes inside the subtree to become the same single-key 
shuffle. That over-constrains the planner and can false-fail on valid plans 
with an extra exchange under the window/distinct subtree.



-- 
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