private RelNode applyCteRewriting(RelOptPlanner planner,  RelNode basePlan, RelMetadataProvider mdProvider, RexExecutor executorProvider) {
      final int referenceThreshold = conf.getIntVar(ConfVars.HIVE_CTE_MATERIALIZE_THRESHOLD);
      if (referenceThreshold <= 0) {
        return basePlan;
      }
      CommonTableExpressionSuggester suggester = CommonTableExpressionSuggesterFactory.create(conf);
      List<RelNode> ctes = suggester.suggest(basePlan, conf);
      if (ctes.isEmpty()) {
        return basePlan;
      }
      HiveRelMetadataQuery mq = (HiveRelMetadataQuery) basePlan.getCluster().getMetadataQuery();
      List<RelOptMaterialization> cteMVs = new ArrayList<>();
      for (int i = 0; i < ctes.size(); i++) {
        final RelNode cte = ctes.get(i);
        if (isMaterializableCte(mq, cte)) {
          cteMVs.add(HiveMaterializedViewUtils.createCTEMaterialization("cte_suggestion_" + i, cte, conf));
        }
      }
      final RelNode ctePlan = rewriteUsingViews(planner, basePlan, mdProvider, executorProvider, cteMVs);
      Map<List<String>, Integer> tableOccurrences = RelOptUtil.findAllTables(ctePlan).stream()
          .map(RelOptTable::getQualifiedName)
          .collect(Collectors.toMap(Function.identity(), v -> 1, Integer::sum));
      CteRuleConfig cteConfig = CteRuleConfig.config()
          .withReferenceThreshold(referenceThreshold)
          .withTableOccurrences(tableOccurrences);
      HepProgram spoolProgram = HepProgram.builder()
          // Use some defined match order ensuring consistent introduction of spool operators; avoids plan flakiness
          .addMatchOrder(HepMatchOrder.DEPTH_FIRST)
          .addRuleInstance(new TableScanToSpoolRule(cteConfig))
          .addRuleInstance(new RemoveInfrequentCteRule(cteConfig))
          .build();
      final RelNode spoolPlan = executeProgram(ctePlan, spoolProgram, mdProvider, executorProvider, cteMVs, true);
      if (ctePlan.getRelDigest().equals(spoolPlan.getRelDigest())) {
        return basePlan;
      } else {
        return spoolPlan;
      }
    }
Returns true if MV is being loaded, constructed or being rebuilt.
ql/src/java/org/apache/hadoop/hive/ql/parse/CalcitePlanner.java