Stamatis Zampetakis created IMPALA-15808:
--------------------------------------------

             Summary: Disable union rewrite for CTEs
                 Key: IMPALA-15808
                 URL: https://issues.apache.org/jira/browse/IMPALA-15808
             Project: IMPALA
          Issue Type: Sub-task
          Components: Frontend
            Reporter: Stamatis Zampetakis
            Assignee: Stamatis Zampetakis
         Attachments: tpcds-q09-b-union-rewrites.txt, tpcds-q09-b.sql

The CTE rewrite algorithm uses [Calcite rules originally designed for 
materialized 
views|https://github.com/apache/impala/blob/9316cbeb7504d3c3e02c2c19549dbbd36acc508d/java/calcite-planner/src/main/java/org/apache/impala/calcite/service/CalciteOptimizer.java#L97].
 In the default configuration the rules have a feature known as union rewrite 
(firstly introduced by CALCITE-1795):
[https://github.com/apache/calcite/blob/7d72586c79c2288ee6ddb09f94e11ca8124d6bac/core/src/main/java/org/apache/calcite/rel/rules/materialize/MaterializedViewRule.java#L1437]

The union rewrite is rarely useful for CTEs. Picking a union rewrite on top of 
a CTE makes the query more complex and essentially more expensive than before. 
To better illustrate let's use the following reduced and simplified variant of 
TPC-DS Q9.
{code:sql}
select
 (select min(ss_net_profit) from store_sales where ss_quantity > 20) as minq20,
 (select max(ss_net_profit) from store_sales where ss_quantity > 20) as maxq20,
 (select min(ss_net_profit) from store_sales where ss_quantity = 40) as minq40,
 (select max(ss_net_profit) from store_sales where ss_quantity = 40) as maxq40
{code}
The current plan when CTEs are enabled is outlined below.
{noformat}
ImpalaSequence
  ImpalaProjectRel(MINQ20=[$1], MAXQ20=[$2], MINQ40=[$3], MAXQ40=[$4])
    ImpalaJoinRel(condition=[true], joinType=[left])
      ImpalaJoinRel(condition=[true], joinType=[left])
        ImpalaJoinRel(condition=[true], joinType=[left])
          ImpalaJoinRel(condition=[true], joinType=[left])
            ImpalaValuesRel(tuples=[[{ 0 }]])
            ImpalaAggRel(group=[{}], EXPR$0=[MIN($0)])
              ImpalaCTEConsumer(cteName=[cte_suggestion_1])
          ImpalaAggRel(group=[{}], EXPR$0=[MAX($0)])
            ImpalaCTEConsumer(cteName=[cte_suggestion_1])
        ImpalaAggRel(group=[{}], EXPR$0=[MIN($0)])
          ImpalaCTEConsumer(cteName=[cte_suggestion_0])
      ImpalaAggRel(group=[{}], EXPR$0=[MAX($0)])
        ImpalaCTEConsumer(cteName=[cte_suggestion_0])
  ImpalaCTEProducer(readType=[EAGER], writeType=[EAGER], 
cteName=[cte_suggestion_0])
    ImpalaProjectRel(ss_net_profit=[$1])
      ImpalaFilterRel(condition=[=($0, 40)])
        ImpalaProjectRel(ss_quantity=[$9], ss_net_profit=[$21])
          ImpalaHdfsScanRel(table=[[tpcds_partitioned_parquet_snap, 
store_sales]])
  ImpalaCTEProducer(readType=[EAGER], writeType=[EAGER], 
cteName=[cte_suggestion_1])
    ImpalaProjectRel(ss_net_profit=[$1])
      ImpalaFilterRel(condition=[>($0, 20)])
        ImpalaProjectRel(ss_quantity=[$9], ss_net_profit=[$21])
          ImpalaHdfsScanRel(table=[[tpcds_partitioned_parquet_snap, 
store_sales]])
{noformat}
The two CTE suggestions that were picked are expected.

Although not visible at the final plan internally the algorithm explored and 
considered some union rewrites. Concretely for the following part of the query
{code:sql}
from store_sales where ss_quantity > 20
{code}
the following transformation was generated:
{noformat}
LogicalUnion(all=[true])
  LogicalProject(ss_net_profit=[$1])
    LogicalFilter(condition=[<>(40, $0)])
      LogicalFilter(condition=[>($0, 20)])
        LogicalProject(ss_quantity=[$9], ss_net_profit=[$21])
          LogicalTableScan(table=[[tpcds_partitioned_parquet_snap, 
store_sales]])
  ImpalaCTEConsumer(cteName=[cte_suggestion_0])
{noformat}
It basically says that I have the results for {{ss_quantity = 40}} in {{cte0}} 
so will take the rows from there and then scan {{store_sales}} skipping those 
rows I already have. However, this transformation does not save a scan but 
instead adds an extra one.

The current cost model rejects the proposed transformation so the union rewrite 
never makes it to the final plan. However, the optimizer spends time generating 
this kind of rewrites that also increase the search space and lead to more rule 
matching attempts and transformations.

Another variant of Q9 ([^tpcds-q09-b.sql]) generated 64 union rewrites 
([^tpcds-q09-b-union-rewrites.txt]) that luckily were never selected. However, 
the impact on optimization time was noticeable and be seen in the logs after 
enabling the "rule_execution_summary".
{code:java}
log4j.logger.org.apache.calcite.plan.AbstractRelOptPlanner.rule_execution_summary=DEBUG
{code}
+Union Rewrite Enabled+
{noformat}
$ cat ~/impala/logs/fe_tests/FeSupport.INFO | grep "MaterializedView.*Rule" -B 1
Rules                                                                   
Attempts           Time (us)
MaterializedViewJoinRule(Filter)                                              
69             214,136
MaterializedViewJoinRule(Project-Filter)                                      
69             165,600
MaterializedViewJoinRule(Join)                                                
15                 494
MaterializedViewAggregateRule(Aggregate)                                      
15                 480
MaterializedViewJoinRule(Project-Join)                                         
1                  10
{noformat}
+Union Rewrite Disabled+
{noformat}
$ cat ~/impala/logs/fe_tests/FeSupport.INFO | grep "MaterializedView.*Rule" -B 1
Rules                                                                   
Attempts           Time (us)
MaterializedViewJoinRule(Join)                                                
15                 559
MaterializedViewAggregateRule(Aggregate)                                      
15                 466
MaterializedViewJoinRule(Filter)                                               
5              59,036
MaterializedViewJoinRule(Project-Filter)                                       
5               8,607
MaterializedViewJoinRule(Project-Join)                                         
1                   8
{noformat}
||UnionRewrite||Total Attempts|Total time (us)|
|FALSE|41|68676|
|TRUE|169|380,720|

All in all, the CTE rewrite for this query is 5.5 times slower when union 
rewrite is enabled adding an overhead of 312ms. The query is specially crafted 
to highlight the downsides of union rewrite but remains pretty close to Q9s 
original shape.

Apart from optimization overhead and plan quality another core motivation for 
disabling the rewrite is correctness and stability. Some of the rewrites 
captured in [^tpcds-q09-b-union-rewrites.txt] appear to be incorrect.
{noformat}
LogicalUnion(all=[true])
  LogicalProject(ss_net_profit=[$1])
    LogicalFilter(condition=[<>(100, $0)])
      LogicalFilter(condition=[<>(40, $0)])
        LogicalFilter(subset=[rel#2838:RelSubset#78.NONE], condition=[<>(60, 
$0)])
          LogicalFilter(subset=[rel#2729:RelSubset#53.NONE], condition=[<>(80, 
$0)])
            LogicalFilter(subset=[rel#2579:RelSubset#3.NONE], condition=[>($0, 
20)])
              LogicalProject(subset=[rel#2577:RelSubset#2.NONE], 
ss_quantity=[$9], ss_net_profit=[$21])
                LogicalTableScan(subset=[rel#2575:RelSubset#1.NONE], 
table=[[tpcds_partitioned_parquet_snap, store_sales]])
  ImpalaCTEConsumer(cteName=[cte_suggestion_0])
{noformat}
The {{cte0}} contains rows where quantity equals 100 but the union part has 
multiple filters seemingly unrelated to the {{{}cte0{}}}.

Additionally, in some cases the union rewrite transformations lead to crashes 
such as the "Type mismatch" error reported under IMPALA-15651.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to