1919
2020import org .apache .doris .common .Pair ;
2121import org .apache .doris .nereids .CascadesContext ;
22+ import org .apache .doris .nereids .StatementContext ;
2223import org .apache .doris .nereids .cost .Cost ;
2324import org .apache .doris .nereids .hint .Hint ;
2425import org .apache .doris .nereids .hint .UseCboRuleHint ;
2829import org .apache .doris .nereids .memo .GroupExpression ;
2930import org .apache .doris .nereids .rules .Rule ;
3031import org .apache .doris .nereids .rules .RuleType ;
32+ import org .apache .doris .nereids .trees .expressions .CTEId ;
3133import org .apache .doris .nereids .trees .plans .logical .LogicalCTEAnchor ;
3234import org .apache .doris .nereids .trees .plans .logical .LogicalPlan ;
3335import org .apache .doris .qe .ConnectContext ;
3436
3537import com .google .common .collect .ImmutableList ;
38+ import com .google .common .collect .Maps ;
3639import org .apache .logging .log4j .LogManager ;
3740import org .apache .logging .log4j .Logger ;
3841
3942import java .util .ArrayList ;
4043import java .util .Arrays ;
4144import java .util .List ;
45+ import java .util .Map ;
4246import java .util .Optional ;
4347
4448/**
@@ -56,6 +60,11 @@ public CostBasedRewriteJob(List<RewriteJob> rewriteJobs) {
5660 // need to generate real rewrite job list
5761 }
5862
63+ private void restoreCteProducerMap (StatementContext context , Map <CTEId , LogicalPlan > currentCteProducers ) {
64+ context .getRewrittenCteProducer ().clear ();
65+ currentCteProducers .forEach (context .getRewrittenCteProducer ()::put );
66+ }
67+
5968 @ Override
6069 public void execute (JobContext jobContext ) {
6170 // checkHint.first means whether it use hint and checkHint.second means what kind of hint it used
@@ -74,9 +83,15 @@ public void execute(JobContext jobContext) {
7483 return ;
7584 }
7685
86+ Map <CTEId , LogicalPlan > currentCteProducers = Maps .newHashMap ();
87+ // cost based rewrite job may contaminate StatementContext.rewrittenCteProducer
88+ // clone current rewrittenCteProducer, and restore it after getCost(.).
89+ currentCtx .getStatementContext ().getRewrittenCteProducer ().forEach (currentCteProducers ::put );
7790 // compare two candidates
7891 Optional <Pair <Cost , GroupExpression >> skipCboRuleCost = getCost (currentCtx , skipCboRuleCtx , jobContext );
92+ restoreCteProducerMap (currentCtx .getStatementContext (), currentCteProducers );
7993 Optional <Pair <Cost , GroupExpression >> appliedCboRuleCost = getCost (currentCtx , applyCboRuleCtx , jobContext );
94+ restoreCteProducerMap (currentCtx .getStatementContext (), currentCteProducers );
8095 // If one of them optimize failed, just return
8196 if (!skipCboRuleCost .isPresent () || !appliedCboRuleCost .isPresent ()) {
8297 LOG .warn ("Cbo rewrite execute failed on sql: {}, jobs are {}, plan is {}." ,
0 commit comments