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


##########
regression-test/suites/nereids_p0/hash_shuffle_key_prune/join_parent.groovy:
##########
@@ -0,0 +1,196 @@
+// 
===========================================================================================
+// 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 containsCols = { String e, List<String> cols ->

Review Comment:
   J11/J12 are supposed to verify that the parent join request rewrites the agg 
child's shuffle key, but `containsCols()` scans the entire plan. Because the 
query already has an explicit `[shuffle]` join on `(c,d,e)`, `containsCols(eOn, 
["c","d","e"])` can be satisfied by the join exchange itself even if the agg 
child never switches away from `(b,c,d,e,f,g)`. This makes the parent-request 
assertion false-positive prone; the helper needs to identify the specific 
aggregate-side `PhysicalDistribute` instead of any matching hash list in the 
plan.



##########
regression-test/suites/nereids_p0/hash_shuffle_key_prune/window_distinct_regression.groovy:
##########
@@ -0,0 +1,197 @@
+// 
===========================================================================================
+// 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;"""
+
+    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 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 assertSelected = { String id, String e, String c ->

Review Comment:
   WD02/WD03 are intended to prove that the inner DISTINCT agg is pruned under 
a window wrapper, but `assertSelected()` searches every single-column 
`orderedShuffledColumns` in the whole plan. In these queries the outer 
`row_number() over (partition by t.a ...)` can itself require a one-column 
shuffle on `a`, so this helper can pass even when the DISTINCT agg keeps its 
original shuffle key. Please target the distribute directly under the agg (or 
otherwise assert the exact node) instead of matching any `[a]` in the plan.



##########
regression-test/suites/nereids_p0/hash_shuffle_key_prune/distinct_mixed.groovy:
##########
@@ -0,0 +1,157 @@
+// 
===========================================================================================
+// 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 norm = { rows -> 
rows.collect{r->r.collect{v->v==null?"NULL":v.toString()}.join("||")}.sort() }
+
+    // DA-group test helper

Review Comment:
   The DA-group description says these cases validate pruning of *both* the 
DISTINCT partition exchange and the agg shuffle exchange, but `runDA()` only 
checks `eOff != eOn`. For `count(distinct ...)` plans there are multiple 
`orderedShuffledColumns` occurrences, so pruning only one exchange (or any 
other plan diff) still makes the case pass. I think this helper needs to 
inspect the actual hash-key lists and assert the targeted DISTINCT-related 
distributes changed as expected.



##########
regression-test/suites/nereids_p0/hash_shuffle_key_prune/degrade_fallback.groovy:
##########
@@ -0,0 +1,176 @@
+// 
===========================================================================================
+// Category 04: Fallback and Conservative Logic — R01-R02, SK01, N01-N02, 
E01-E02
+// 
===========================================================================================
+//
+// Purpose
+//   Validate fallback (no optimization) behavior of Shuffle Key Pruning in 
special scenarios:
+//   1. ROLLUP/GROUPING SETS -> the Repeat operator produces multiple group-by 
key sets -> no pruning
+//   2. All candidate columns are skewed -> no safe column can be chosen -> no 
pruning
+//   3. Missing/partial statistics -> conservative fallback -> no pruning
+//   4. String fallback: when step 1 cannot pick a single key, step 2 removes 
string-typed columns
+//
+// Case List
+//   R01: GROUP BY ROLLUP(b,c,d,e,f) -> Repeat operator -> no pruning 
(negative)
+//   R02: GROUP BY GROUPING SETS -> same behavior -> no pruning (negative)
+//   SK01: k1~k5 all have hot_values=0.8 -> all skewed -> no pruning (negative)
+//   N01: Some partitions of a partitioned table have no stats -> conservative 
-> no pruning (negative)
+//   N02: Only column b is analyzed -> other columns miss stats -> no pruning 
(negative)
+//   E01: All non-string columns are skewed / low-NDV -> step 2 removes 
strings and keeps a 3-column composite key (positive)
+//   E02: Only string columns remain -> no usable key after removing strings 
-> no pruning (negative)
+//
+// Validation
+//   Check whether the plan changes and verify result consistency.
+// 
===========================================================================================
+suite("degrade_fallback", "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 R = "480000"
+    def nullSkew = "48000"
+    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(); 
if(r.length()==0){ids<<[];continue}
+            
ids<<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 norm = { rows -> 
rows.collect{r->r.collect{v->v==null?"NULL":v.toString()}.join("||")}.sort() }
+
+    def runEx = { String id,String q,int ap,boolean single,boolean 
reqShuffle,Boolean expChg,String sel,def exc ->
+        sql "set agg_phase=${ap};"; sql "set disable_nereids_rules='';"
+        sql "set enable_shuffle_key_prune=false;"
+        def eOff=(sql "explain physical plan "+q).toString(); def 
oS=extractSigns(eOff)
+        sql "set enable_shuffle_key_prune=true;"
+        def eOn=(sql "explain physical plan "+q).toString(); def 
nS=extractSigns(eOn)
+        def si=[]; extractIdLists(eOn).findAll{it.size()==1}.each{si<<it[0]}
+        def shouldChg = (expChg==null ? single : expChg)
+        if(shouldChg){assertTrue(oS.toString()!=nS.toString(),"${id}: signs 
should change"); if(single)assertTrue(si.size()>0,"${id}: expect single")}
+        else{assertTrue(oS.toString()==nS.toString(),"${id}: should stay 
unchanged"); if(reqShuffle)assertTrue(nS.size()>0,"${id}: need shuffle")}
+        sql "set enable_shuffle_key_prune=false;"; def rOff=sql q
+        sql "set enable_shuffle_key_prune=true;"; def rOn=sql q
+        assertTrue(norm(rOff)==norm(rOn),"${id}: results differ")
+        logger.info("${id}: oS=${oS}, nS=${nS}")
+    }
+
+    def runAdvanced = { String id,String q,boolean chg,List<String> 
selCols,List<String> exc,Integer keyCount ->

Review Comment:
   `runAdvanced()` never uses `selCols` or `exc`; it only checks that *some* 
`orderedShuffledColumns` entry has `keyCount`. For `E01`, that means any 3-key 
shuffle in the plan will satisfy the test, even if the string-removal fallback 
keeps `vc16_hot`/`s_hot` or picks a different 3-column set. Since this PR's 
value is the regression coverage itself, I think this helper needs to assert 
the actual selected/excluded exprIds, not just the count.



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