github-actions[bot] commented on code in PR #62628: URL: https://github.com/apache/doris/pull/62628#discussion_r3115973294
########## regression-test/suites/nereids_p0/hash_shuffle_key_prune/distinct_mixed.groovy: ########## @@ -0,0 +1,257 @@ +// 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}, + "${id}: expected all DISTINCT/global shuffles to prune to [a]/${target}, got ${onCtx.ctxs}") + } else { + assertTrue(oS.toString()==nS.toString(),"${id}: should stay unchanged") + assertTrue(offCtx?.ctxs?.collect{it.ids} == onCtx?.ctxs?.collect{it.ids}, + "${id}: DISTINCT/global shuffle lists should stay unchanged, off=${offCtx}, on=${onCtx}") + } + 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") + } + + // ===== DA group table setup ===== + sql "drop table if exists t_08_da;" + sql """create table t_08_da (id bigint,a bigint,b bigint,c bigint,d bigint,e bigint,f bigint,g bigint,v bigint) + duplicate key(id) distributed by hash(id) buckets 4 properties ("replication_num"="1");""" + sql """insert into t_08_da select number,number%5000,number%4800,number%4600, + number%4400,number%4200,number%4000,number%3800,number from numbers("number"="2000");""" + + def daBase = { String ndv -> + ss("t_08_da","id","60000","0","1600000","0","1999","") + ["a","b","c","d","e","f","g","v"].each{c-> ss("t_08_da",c,ndv,"0","1600000","0","9999","")} + } + + // DA01: high NDV -> prune + daBase(daQn) + runDA("DA01","select a,b,c,d,e,f,count(distinct g) from t_08_da group by a,b,c,d,e,f",true,2) + + // DA02: low NDV -> no pruning + daBase(lowNdv) + runDA("DA02","select a,b,c,d,e,f,count(distinct g) from t_08_da group by a,b,c,d,e,f",false,2) + + // DA03: distinct + avg mixed -> prune + daBase(daQn) + runDA("DA03","select a,b,c,d,e,f,count(distinct g),avg(v) from t_08_da group by a,b,c,d,e,f",true,2) + + // DA04: agg_phase=4 (2+2) + daBase(daQn) + runDA("DA04","select a,b,c,d,e,f,count(distinct g) from t_08_da group by a,b,c,d,e,f",true,4) + + // DA05: distinct [skew] hint → should skip shuffle key prune + daBase(daQn) + runDA("DA05","select a,count(distinct [skew] g) from t_08_da group by a",false,2) + + // ===== M group table setup ===== Review Comment: `runDA()` mutates the session `agg_phase`, and DA05 leaves it at `2`. Because the M group never resets it, M01-M03 run under forced two-phase aggregation instead of the suite's default `agg_phase=0`. For non-distinct agg this disables the auto/one-phase/bucketed alternatives in `SplitAggWithoutDistinct`, so these cases are no longer validating the default mixed-join path described above. Please reset `agg_phase` before the M group, or inside each M case. ########## regression-test/suites/nereids_p0/hash_shuffle_key_prune/degrade_fallback.groovy: ########## @@ -0,0 +1,246 @@ +// 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 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 -> + sql "set agg_phase=0;"; 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 idLists=extractIdLists(eOn) + if(chg){assertTrue(oS.toString()!=nS.toString(),"${id}: signs should change")} + else{assertTrue(oS.toString()==nS.toString(),"${id}: should stay unchanged")} + def matchedIds = null + if(selCols!=null && !selCols.isEmpty()){ + def selectedIds = selCols.collect { c -> + def eid = exprId(eOn, c) + assertTrue(eid!=null, "${id}: missing exprId for ${c}") + eid + } + matchedIds = idLists.find { it.size()==selectedIds.size() && (it as Set)==(selectedIds as Set) } + assertTrue(matchedIds!=null, "${id}: expected selected cols ${selCols}, got ${idLists}") + } + if(keyCount!=null){ + def counts=idLists.collect{it.size()} + assertTrue(counts.any{it==keyCount},"${id}: expect keyCount ${keyCount}") + if(matchedIds!=null){assertTrue(matchedIds.size()==keyCount,"${id}: selected cols size should be ${keyCount}, got ${matchedIds}")} + } + if(exc!=null && !exc.isEmpty()){ + def excludedPairs = exc.collect { c -> + def eid = exprId(eOn, c) + assertTrue(eid!=null, "${id}: missing exprId for ${c}") + [c, eid] + } + if(matchedIds!=null){ + excludedPairs.each { p -> + assertTrue(!matchedIds.contains(p[1]), "${id}: excluded ${p[0]} was selected in ${matchedIds}") + } + } else if(keyCount!=null){ + def candidateLists = idLists.findAll { it.size()==keyCount } + assertTrue(candidateLists.any { ids -> excludedPairs.every { p -> !ids.contains(p[1]) } }, + "${id}: expected a ${keyCount}-key shuffle without excluded cols ${exc}, got ${candidateLists}") + } + } + 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 promoteKnownStats = { String t, Map<String, String> ndvMap -> + ss(t, "x", ndvMap.getOrDefault("x", "12000"), "0", "1600000", "1", "199900001", "") + ndvMap.each { c, ndv -> + if (c != "x") { + ss(t, c, ndv, "0", "1600000", "1", ndv, "") + } + } + if (ndvMap.containsKey("v")) { + ss(t, "v", ndvMap.get("v"), "0", "1600000", "0", "1999", "") + } + } + + // ===== R group: repeat -> no optimization ===== + sql "drop table if exists t_04_repeat;" + sql """create table t_04_repeat (x bigint, b bigint, c bigint, d bigint, e bigint, f bigint, g bigint, v bigint) + duplicate key(x) distributed by hash(x) buckets 4 properties ("replication_num"="1");""" + sql """insert into t_04_repeat select + (bitand(murmur_hash3_32(concat(cast(number as string),'_x')),2147483647)%4500)*100000+1, + (bitand(murmur_hash3_32(concat(cast(number as string),'_b')),2147483647)%220)*100000+2, + (bitand(murmur_hash3_32(concat(cast(number as string),'_c')),2147483647)%3900)*100000+3, + (bitand(murmur_hash3_32(concat(cast(number as string),'_d')),2147483647)%3600)*100000+4, + (bitand(murmur_hash3_32(concat(cast(number as string),'_e')),2147483647)%4000)*100000+5, + (bitand(murmur_hash3_32(concat(cast(number as string),'_f')),2147483647)%3400)*100000+6, + (bitand(murmur_hash3_32(concat(cast(number as string),'_g')),2147483647)%120)*100000+7, + number from numbers("number"="2000");""" + sql "analyze table t_04_repeat with sync;" + // Promote stats above the prune threshold so Repeat is the only blocker. + promoteKnownStats("t_04_repeat", ["b":"5200","c":"5600","d":"6000","e":"6400","f":"6800","g":"7200","v":"60000"]) + runEx("R01","select b,c,d,e,f,sum(v) from t_04_repeat group by rollup(b,c,d,e,f)",0,false,true,false,null,[]) + runEx("R02","select b,c,d,e,f,sum(v) from t_04_repeat group by grouping sets ((b,c,d,e,f),(b,c,d,e),(b,c,d),(b,c),(b))",0,false,true,false,null,[]) + + // ===== SK group: all skewed -> no optimization ===== + sql "drop table if exists t_04_allskew;" + sql """create table t_04_allskew (x bigint, k1 bigint, k2 bigint, k3 bigint, k4 bigint, k5 bigint, v bigint) + duplicate key(x) distributed by hash(x) buckets 4 properties ("replication_num"="1");""" + sql """insert into t_04_allskew select number*100000+1, + if(number%10<8,1,number%3600+2), if(number%10<8,2,number%3400+2), + if(number%10<8,3,number%3200+2), if(number%10<8,4,number%3000+2), + if(number%10<8,5,number%2800+2), number from numbers("number"="2000");""" + ["k1","k2","k3","k4","k5"].each{c-> ss("t_04_allskew",c,"9000","0","1600000","1","9000","${c=='k1'?1:c=='k2'?2:c=='k3'?3:c=='k4'?4:5} :0.8")} + ss("t_04_allskew","x","60000","0","1600000","1","199900001","") + ss("t_04_allskew","v","60000","0","1600000","0","1999","") + runEx("SK01","select k1,k2,k3,k4,k5,sum(v) from t_04_allskew group by k1,k2,k3,k4,k5",0,false,true,false,null,[]) + + // ===== N group: stale/partial stats -> conservative ===== + sql "drop table if exists t_04_stale;" + sql "drop table if exists t_04_partial;" + sql """create table t_04_stale (part_key int, x bigint, b bigint, c bigint, d bigint, e bigint, f bigint, v bigint) + duplicate key(part_key, x, b, c) partition by range(part_key) ( + partition p1 values [("0"),("100")), partition p2 values [("100"),("200")), partition p3 values [("200"),("300")) + ) distributed by hash(x) buckets 4 properties ("replication_num"="1");""" + sql """create table t_04_partial (x bigint, b bigint, c bigint, d bigint, e bigint, f bigint, v bigint) + duplicate key(x) distributed by hash(x) buckets 4 properties ("replication_num"="1");""" + sql """insert into t_04_stale select 10, number*100000+1, + (bitand(murmur_hash3_32(concat(cast(number as string),'_b')),2147483647)%180)*100000+2, + (bitand(murmur_hash3_32(concat(cast(number as string),'_c')),2147483647)%2600)*100000+3, + (bitand(murmur_hash3_32(concat(cast(number as string),'_d')),2147483647)%2400)*100000+4, + (bitand(murmur_hash3_32(concat(cast(number as string),'_e')),2147483647)%2200)*100000+5, + (bitand(murmur_hash3_32(concat(cast(number as string),'_f')),2147483647)%2000)*100000+6, + number from numbers("number"="6000");""" + sql """insert into t_04_partial select number*100000+1, + (bitand(murmur_hash3_32(concat(cast(number as string),'_b')),2147483647)%180)*100000+2, + (bitand(murmur_hash3_32(concat(cast(number as string),'_c')),2147483647)%2600)*100000+3, + (bitand(murmur_hash3_32(concat(cast(number as string),'_d')),2147483647)%2400)*100000+4, + (bitand(murmur_hash3_32(concat(cast(number as string),'_e')),2147483647)%2200)*100000+5, + (bitand(murmur_hash3_32(concat(cast(number as string),'_f')),2147483647)%2000)*100000+6, + number from numbers("number"="6000");""" + // Analyze only p1 so p2 remains without partition stats; this isolates the "partial partition stats" guard. Review Comment: This suite is relying on deliberately missing/partial statistics for `N01`/`N02`, but unlike the existing `hash_shuffle_key_prune.groovy` baseline it never disables `enable_auto_analyze`. That makes these negatives timing-dependent: if the background collector fills the table or partition stats after the inserts, the optimizer can start pruning and the cases will fail for the wrong reason. Please freeze auto analyze before these suites, or at least before the missing-stats cases. ########## regression-test/suites/nereids_p0/hash_shuffle_key_prune/join_parent.groovy: ########## @@ -0,0 +1,265 @@ +// 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.size() == expectedIds.size() && (actualIds as Set) == (expectedIds as Set), + "${id}: expected agg-side shuffle cols ${cols}/${expectedIds}, got ${actualIds}") + } + def explainText = { String q -> (sql "explain physical plan " + q).collect { it[0].toString() }.join("\n") } + def run = { String id,String q,int ap,boolean single,boolean reqSh,Boolean expChg,String sel,def exc -> Review Comment: `run()` takes `sel` / `exc`, but the helper never uses them. That means J02/J04/J05/J06/J07 only prove that some `orderedShuffledColumns` text changed, not that the agg-side shuffle key was pruned to the intended join-key subset. If the optimizer starts choosing the wrong key, these cases will still pass because the query result is unchanged. Please either scope the assertion to the target `PhysicalDistribute` (like `runParent()` does) or remove the misleading parameters and add explicit key checks. -- 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]
