github-actions[bot] commented on code in PR #62628: URL: https://github.com/apache/doris/pull/62628#discussion_r3121399331
########## regression-test/suites/nereids_p0/hash_shuffle_key_prune/join_parent.groovy: ########## @@ -0,0 +1,300 @@ +// 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), Review Comment: `orderedShuffledColumns` is order-sensitive here, so this assertion is weaker than the parent-key contract it is trying to verify. `RequestPropertyDeriver` preserves the parent hash order when it builds `intersectIdList`, and `ChildrenPropertiesRegulator.bothSideShuffleKeysAreSameOrder()` treats a reordered list as a different distribution. With `(actualIds as Set) == (expectedIds as Set)`, `[c,d,e]` and `[e,d,c]` both pass, so a real regression in `agg_shuffle_use_parent_key` can slip through. Please compare the ordered lists directly instead of sets. ########## regression-test/suites/nereids_p0/hash_shuffle_key_prune/join_parent.groovy: ########## @@ -0,0 +1,300 @@ +// 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 findAllGlobalAggChildShuffleIds = { String e -> + def lines = e.readLines() + def allIds = [] + 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=")) { + allIds << parseOrderedIds(childLine) + break + } + } + } + allIds + } + 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 -> + 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 offAggIds=findAllGlobalAggChildShuffleIds(eOff) + sql "set enable_shuffle_key_prune=true;" + def eOn=explainText(q); def nS=extractSigns(eOn); def onAggIds=findAllGlobalAggChildShuffleIds(eOn) + def chg=(expChg==null?single:expChg) + if(chg){ + assertTrue(oS.toString()!=nS.toString(),"${id}: signs should change") + if(single){ + assertTrue(onAggIds.any{it.size()==1}, "${id}: expect at least one single-key agg-side shuffle, got ${onAggIds}") Review Comment: This helper only checks `onAggIds.any { it.size() == 1 }`. That is enough for single-agg cases, but not for the symmetric join cases with multiple global aggs. In `J04`, the suite still passes if only one agg side prunes to a single key and the other side regresses, because the plan text changes and `any(...)` stays true. Since these cases are meant to prove both agg sides honor the optimization, please assert the full `onAggIds` shape/count here instead of just the existence of one single-key shuffle. ########## regression-test/suites/nereids_p0/hash_shuffle_key_prune/window_distinct_regression.groovy: ########## @@ -0,0 +1,233 @@ +// 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 assertDistinctShufflePrunedToSingle = { String id, String eOff, String eOn, String c -> + def offIds = extractIdLists(eOff) + def onIds = extractIdLists(eOn) + assertTrue(!offIds.isEmpty() && !onIds.isEmpty(), "${id}: missing shuffle ids, off=${offIds}, on=${onIds}") + def offTarget = offIds.last() Review Comment: This helper is not scoped to the DISTINCT/GLOBAL aggregate subtree; it just grabs the last `orderedShuffledColumns` in the whole plan. These queries also have a window-level distribution request on `t.a` from `RequestPropertyDeriver.visitPhysicalWindow()`, so if the plan shape shifts, WD02/WD03 can start validating the window exchange instead of the distinct-global exchange we actually want to protect. `distinct_mixed.groovy` already uses a subtree-scoped helper for this case; please reuse that pattern here. -- 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]
