dianfu commented on code in PR #28638:
URL: https://github.com/apache/flink/pull/28638#discussion_r3827001839
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecPythonCalc.java:
##########
@@ -144,51 +278,65 @@ private OneInputTransformation<RowData, RowData>
createPythonOneInputTransformat
.map(x -> ((RexInputRef) x).getIndex())
.collect(Collectors.toList());
+ LogicalType[] inputLogicalTypes =
+ ((InternalTypeInfo<RowData>)
inputTransform.getOutputType()).toRowFieldTypes();
+ RowType inputType =
Review Comment:
unused
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcConditionProjectionCseRule.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc;
+
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelRule;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+import org.apache.calcite.rex.RexShuttle;
+import org.immutables.value.Value;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Rule that eliminates common Python UDF sub-expressions between the
condition and projection of a
+ * Calc node.
+ *
+ * <p>After {@link RemoteCalcSplitConditionRule} splits a Calc with Python
UDFs in its condition,
+ * the result is a two-level Calc structure:
+ *
+ * <pre>
+ * TopCalc(projection=[pyFunc(a, b) + 1, pyFunc(a, b) + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ *
+ * <p>The TopCalc's projection still contains {@code pyFunc(a, b)} which is
structurally identical
+ * to the already-computed {@code f0} in the BottomCalc. This rule detects
such duplicates and
+ * rewrites the TopCalc's projection to reference the BottomCalc's output
directly:
+ *
+ * <pre>
+ * TopCalc(projection=[$2 + 1, $2 + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ */
[email protected]
+public class RemoteCalcConditionProjectionCseRule
+ extends RelRule<RemoteCalcConditionProjectionCseRule.Config> {
+
+ protected RemoteCalcConditionProjectionCseRule(Config config) {
+ super(config);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ FlinkLogicalCalc topCalc = call.rel(0);
+ FlinkLogicalCalc bottomCalc = call.rel(1);
+ RemoteCallFinder callFinder = config.remoteCallFinder();
+
+ // Only applies when the top calc has a condition.
+ if (topCalc.getProgram().getCondition() == null) {
+ return false;
+ }
+
+ List<RexNode> topProjects = RemoteCalcCseUtil.expandProjects(topCalc);
+ Map<RexNode, Integer> bottomPythonCalls =
buildBottomPythonCallMap(bottomCalc, callFinder);
+
+ if (bottomPythonCalls.isEmpty()) {
+ return false;
+ }
+
+ // Check if any top projection contains a call matching the bottom
calc's output.
+ return topProjects.stream()
+ .anyMatch(node -> containsCallMatchingBottom(node,
bottomPythonCalls, callFinder));
+ }
+
+ @Override
+ public void onMatch(RelOptRuleCall call) {
+ FlinkLogicalCalc topCalc = call.rel(0);
+ FlinkLogicalCalc bottomCalc = call.rel(1);
+ RemoteCallFinder callFinder = config.remoteCallFinder();
+ RexBuilder rexBuilder = call.builder().getRexBuilder();
+
+ List<RexNode> topProjects = RemoteCalcCseUtil.expandProjects(topCalc);
+ RexNode topCondition =
+ topCalc.getProgram().getCondition() != null
+ ?
topCalc.getProgram().expandLocalRef(topCalc.getProgram().getCondition())
+ : null;
+
+ Map<RexNode, Integer> bottomPythonCalls =
buildBottomPythonCallMap(bottomCalc, callFinder);
+ RelDataType bottomRowType = bottomCalc.getRowType();
+
+ // Rewrite top projections: replace matching calls with RexInputRef.
+ CseRewriteShuttle rewriter = new CseRewriteShuttle(bottomPythonCalls,
bottomRowType);
+ List<RexNode> newTopProjects =
+ topProjects.stream().map(p ->
p.accept(rewriter)).collect(Collectors.toList());
+
+ if (!rewriter.hasRewritten()) {
+ return;
+ }
+
+ // Build the new top calc with rewritten projections.
+ call.transformTo(
+ topCalc.copy(
+ topCalc.getTraitSet(),
+ bottomCalc,
+ RexProgram.create(
+ bottomRowType,
+ newTopProjects,
+ topCondition,
+ topCalc.getRowType(),
+ rexBuilder)));
+ }
+
+ /**
+ * Builds a map from deterministic Python UDF calls in the bottom calc's
projection to their
+ * output index.
+ */
+ private Map<RexNode, Integer> buildBottomPythonCallMap(
+ FlinkLogicalCalc bottomCalc, RemoteCallFinder callFinder) {
+ List<RexNode> bottomProjects =
RemoteCalcCseUtil.expandProjects(bottomCalc);
+
+ Map<RexNode, Integer> result = new HashMap<>();
+ IntStream.range(0, bottomProjects.size())
+ .filter(
+ i ->
+ RemoteCalcCseUtil.containsReusableRemoteCall(
+ bottomProjects.get(i), callFinder))
+ .forEach(i -> result.put(bottomProjects.get(i), i));
+ return result;
+ }
+
+ private boolean containsCallMatchingBottom(
Review Comment:
Could declared as a static method
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcConditionProjectionCseRule.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc;
+
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelRule;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+import org.apache.calcite.rex.RexShuttle;
+import org.immutables.value.Value;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Rule that eliminates common Python UDF sub-expressions between the
condition and projection of a
+ * Calc node.
+ *
+ * <p>After {@link RemoteCalcSplitConditionRule} splits a Calc with Python
UDFs in its condition,
+ * the result is a two-level Calc structure:
+ *
+ * <pre>
+ * TopCalc(projection=[pyFunc(a, b) + 1, pyFunc(a, b) + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ *
+ * <p>The TopCalc's projection still contains {@code pyFunc(a, b)} which is
structurally identical
+ * to the already-computed {@code f0} in the BottomCalc. This rule detects
such duplicates and
+ * rewrites the TopCalc's projection to reference the BottomCalc's output
directly:
+ *
+ * <pre>
+ * TopCalc(projection=[$2 + 1, $2 + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ */
[email protected]
+public class RemoteCalcConditionProjectionCseRule
Review Comment:
This rule applies for both Python operator and async function operator.
Could you update the implementation to reflect this?
##########
flink-python/pyflink/table/tests/test_udf.py:
##########
@@ -926,6 +926,85 @@ def test_create_and_drop_function(self):
self.assertTrue('add_one_func' not in
t_env.list_user_defined_functions())
self.assertTrue('subtract_one_func' not in
t_env.list_user_defined_functions())
+ def test_python_local_ref_reuse(self):
Review Comment:
I think planner test is enough?
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcConditionProjectionCseRule.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc;
+
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelRule;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+import org.apache.calcite.rex.RexShuttle;
+import org.immutables.value.Value;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Rule that eliminates common Python UDF sub-expressions between the
condition and projection of a
+ * Calc node.
+ *
+ * <p>After {@link RemoteCalcSplitConditionRule} splits a Calc with Python
UDFs in its condition,
+ * the result is a two-level Calc structure:
+ *
+ * <pre>
+ * TopCalc(projection=[pyFunc(a, b) + 1, pyFunc(a, b) + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ *
+ * <p>The TopCalc's projection still contains {@code pyFunc(a, b)} which is
structurally identical
+ * to the already-computed {@code f0} in the BottomCalc. This rule detects
such duplicates and
+ * rewrites the TopCalc's projection to reference the BottomCalc's output
directly:
+ *
+ * <pre>
+ * TopCalc(projection=[$2 + 1, $2 + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ */
[email protected]
+public class RemoteCalcConditionProjectionCseRule
+ extends RelRule<RemoteCalcConditionProjectionCseRule.Config> {
+
+ protected RemoteCalcConditionProjectionCseRule(Config config) {
+ super(config);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ FlinkLogicalCalc topCalc = call.rel(0);
+ FlinkLogicalCalc bottomCalc = call.rel(1);
+ RemoteCallFinder callFinder = config.remoteCallFinder();
+
+ // Only applies when the top calc has a condition.
+ if (topCalc.getProgram().getCondition() == null) {
+ return false;
+ }
+
+ List<RexNode> topProjects = RemoteCalcCseUtil.expandProjects(topCalc);
+ Map<RexNode, Integer> bottomPythonCalls =
buildBottomPythonCallMap(bottomCalc, callFinder);
+
+ if (bottomPythonCalls.isEmpty()) {
+ return false;
+ }
+
+ // Check if any top projection contains a call matching the bottom
calc's output.
+ return topProjects.stream()
+ .anyMatch(node -> containsCallMatchingBottom(node,
bottomPythonCalls, callFinder));
+ }
+
+ @Override
+ public void onMatch(RelOptRuleCall call) {
+ FlinkLogicalCalc topCalc = call.rel(0);
+ FlinkLogicalCalc bottomCalc = call.rel(1);
+ RemoteCallFinder callFinder = config.remoteCallFinder();
+ RexBuilder rexBuilder = call.builder().getRexBuilder();
+
+ List<RexNode> topProjects = RemoteCalcCseUtil.expandProjects(topCalc);
+ RexNode topCondition =
+ topCalc.getProgram().getCondition() != null
+ ?
topCalc.getProgram().expandLocalRef(topCalc.getProgram().getCondition())
+ : null;
+
+ Map<RexNode, Integer> bottomPythonCalls =
buildBottomPythonCallMap(bottomCalc, callFinder);
+ RelDataType bottomRowType = bottomCalc.getRowType();
+
+ // Rewrite top projections: replace matching calls with RexInputRef.
+ CseRewriteShuttle rewriter = new CseRewriteShuttle(bottomPythonCalls,
bottomRowType);
+ List<RexNode> newTopProjects =
+ topProjects.stream().map(p ->
p.accept(rewriter)).collect(Collectors.toList());
+
+ if (!rewriter.hasRewritten()) {
+ return;
+ }
+
+ // Build the new top calc with rewritten projections.
+ call.transformTo(
+ topCalc.copy(
+ topCalc.getTraitSet(),
+ bottomCalc,
+ RexProgram.create(
+ bottomRowType,
+ newTopProjects,
+ topCondition,
+ topCalc.getRowType(),
+ rexBuilder)));
+ }
+
+ /**
+ * Builds a map from deterministic Python UDF calls in the bottom calc's
projection to their
+ * output index.
+ */
+ private Map<RexNode, Integer> buildBottomPythonCallMap(
+ FlinkLogicalCalc bottomCalc, RemoteCallFinder callFinder) {
+ List<RexNode> bottomProjects =
RemoteCalcCseUtil.expandProjects(bottomCalc);
+
+ Map<RexNode, Integer> result = new HashMap<>();
+ IntStream.range(0, bottomProjects.size())
+ .filter(
+ i ->
+ RemoteCalcCseUtil.containsReusableRemoteCall(
+ bottomProjects.get(i), callFinder))
+ .forEach(i -> result.put(bottomProjects.get(i), i));
+ return result;
+ }
+
+ private boolean containsCallMatchingBottom(
+ RexNode node, Map<RexNode, Integer> bottomPythonCalls,
RemoteCallFinder callFinder) {
+ if (node instanceof RexCall) {
+ RexCall rexCall = (RexCall) node;
+ if (callFinder.isRemoteCall(rexCall) &&
bottomPythonCalls.containsKey(rexCall)) {
Review Comment:
For the following SQL:
```
SELECT pyFunc1(b, c) FROM MyTable WHERE pyFunc1(a, b) > 0
```
After splitting, both calls can appear as `pyFunc1($0, $1)`, so this rule
incorrectly replaces the projection result with the condition result and
changes the query output.
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcConditionProjectionCseRule.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc;
+
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelRule;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+import org.apache.calcite.rex.RexShuttle;
+import org.immutables.value.Value;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Rule that eliminates common Python UDF sub-expressions between the
condition and projection of a
+ * Calc node.
+ *
+ * <p>After {@link RemoteCalcSplitConditionRule} splits a Calc with Python
UDFs in its condition,
+ * the result is a two-level Calc structure:
+ *
+ * <pre>
+ * TopCalc(projection=[pyFunc(a, b) + 1, pyFunc(a, b) + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ *
+ * <p>The TopCalc's projection still contains {@code pyFunc(a, b)} which is
structurally identical
+ * to the already-computed {@code f0} in the BottomCalc. This rule detects
such duplicates and
+ * rewrites the TopCalc's projection to reference the BottomCalc's output
directly:
+ *
+ * <pre>
+ * TopCalc(projection=[$2 + 1, $2 + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ */
[email protected]
+public class RemoteCalcConditionProjectionCseRule
+ extends RelRule<RemoteCalcConditionProjectionCseRule.Config> {
+
+ protected RemoteCalcConditionProjectionCseRule(Config config) {
+ super(config);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ FlinkLogicalCalc topCalc = call.rel(0);
+ FlinkLogicalCalc bottomCalc = call.rel(1);
+ RemoteCallFinder callFinder = config.remoteCallFinder();
+
+ // Only applies when the top calc has a condition.
+ if (topCalc.getProgram().getCondition() == null) {
+ return false;
+ }
+
+ List<RexNode> topProjects = RemoteCalcCseUtil.expandProjects(topCalc);
+ Map<RexNode, Integer> bottomPythonCalls =
buildBottomPythonCallMap(bottomCalc, callFinder);
+
+ if (bottomPythonCalls.isEmpty()) {
+ return false;
+ }
+
+ // Check if any top projection contains a call matching the bottom
calc's output.
+ return topProjects.stream()
+ .anyMatch(node -> containsCallMatchingBottom(node,
bottomPythonCalls, callFinder));
+ }
+
+ @Override
+ public void onMatch(RelOptRuleCall call) {
+ FlinkLogicalCalc topCalc = call.rel(0);
+ FlinkLogicalCalc bottomCalc = call.rel(1);
+ RemoteCallFinder callFinder = config.remoteCallFinder();
+ RexBuilder rexBuilder = call.builder().getRexBuilder();
+
+ List<RexNode> topProjects = RemoteCalcCseUtil.expandProjects(topCalc);
+ RexNode topCondition =
+ topCalc.getProgram().getCondition() != null
+ ?
topCalc.getProgram().expandLocalRef(topCalc.getProgram().getCondition())
+ : null;
+
+ Map<RexNode, Integer> bottomPythonCalls =
buildBottomPythonCallMap(bottomCalc, callFinder);
+ RelDataType bottomRowType = bottomCalc.getRowType();
+
+ // Rewrite top projections: replace matching calls with RexInputRef.
+ CseRewriteShuttle rewriter = new CseRewriteShuttle(bottomPythonCalls,
bottomRowType);
+ List<RexNode> newTopProjects =
+ topProjects.stream().map(p ->
p.accept(rewriter)).collect(Collectors.toList());
+
+ if (!rewriter.hasRewritten()) {
+ return;
+ }
+
+ // Build the new top calc with rewritten projections.
+ call.transformTo(
+ topCalc.copy(
+ topCalc.getTraitSet(),
+ bottomCalc,
+ RexProgram.create(
+ bottomRowType,
+ newTopProjects,
+ topCondition,
+ topCalc.getRowType(),
+ rexBuilder)));
+ }
+
+ /**
+ * Builds a map from deterministic Python UDF calls in the bottom calc's
projection to their
+ * output index.
+ */
+ private Map<RexNode, Integer> buildBottomPythonCallMap(
Review Comment:
Could declared as a static method
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcConditionProjectionCseRule.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc;
+
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelRule;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+import org.apache.calcite.rex.RexShuttle;
+import org.immutables.value.Value;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Rule that eliminates common Python UDF sub-expressions between the
condition and projection of a
+ * Calc node.
+ *
+ * <p>After {@link RemoteCalcSplitConditionRule} splits a Calc with Python
UDFs in its condition,
+ * the result is a two-level Calc structure:
+ *
+ * <pre>
+ * TopCalc(projection=[pyFunc(a, b) + 1, pyFunc(a, b) + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ *
+ * <p>The TopCalc's projection still contains {@code pyFunc(a, b)} which is
structurally identical
+ * to the already-computed {@code f0} in the BottomCalc. This rule detects
such duplicates and
+ * rewrites the TopCalc's projection to reference the BottomCalc's output
directly:
+ *
+ * <pre>
+ * TopCalc(projection=[$2 + 1, $2 + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ */
[email protected]
+public class RemoteCalcConditionProjectionCseRule
+ extends RelRule<RemoteCalcConditionProjectionCseRule.Config> {
+
+ protected RemoteCalcConditionProjectionCseRule(Config config) {
+ super(config);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ FlinkLogicalCalc topCalc = call.rel(0);
+ FlinkLogicalCalc bottomCalc = call.rel(1);
+ RemoteCallFinder callFinder = config.remoteCallFinder();
+
+ // Only applies when the top calc has a condition.
+ if (topCalc.getProgram().getCondition() == null) {
+ return false;
+ }
+
+ List<RexNode> topProjects = RemoteCalcCseUtil.expandProjects(topCalc);
Review Comment:
This line could be moved before it's used. It could avoid unnecessary
computation if `bottomPythonCalls.isEmpty()` is true.
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcConditionProjectionCseRule.java:
##########
@@ -0,0 +1,241 @@
+/*
+ * 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.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc;
+
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelRule;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+import org.apache.calcite.rex.RexShuttle;
+import org.immutables.value.Value;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Rule that eliminates common Python UDF sub-expressions between the
condition and projection of a
+ * Calc node.
+ *
+ * <p>After {@link RemoteCalcSplitConditionRule} splits a Calc with Python
UDFs in its condition,
+ * the result is a two-level Calc structure:
+ *
+ * <pre>
+ * TopCalc(projection=[pyFunc(a, b) + 1, pyFunc(a, b) + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ *
+ * <p>The TopCalc's projection still contains {@code pyFunc(a, b)} which is
structurally identical
+ * to the already-computed {@code f0} in the BottomCalc. This rule detects
such duplicates and
+ * rewrites the TopCalc's projection to reference the BottomCalc's output
directly:
+ *
+ * <pre>
+ * TopCalc(projection=[$2 + 1, $2 + 2], condition=[$2 > 0])
+ * BottomCalc(projection=[a, b, pyFunc(a, b) AS f0])
+ * </pre>
+ */
[email protected]
+public class RemoteCalcConditionProjectionCseRule
+ extends RelRule<RemoteCalcConditionProjectionCseRule.Config> {
+
+ protected RemoteCalcConditionProjectionCseRule(Config config) {
+ super(config);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ FlinkLogicalCalc topCalc = call.rel(0);
+ FlinkLogicalCalc bottomCalc = call.rel(1);
+ RemoteCallFinder callFinder = config.remoteCallFinder();
+
+ // Only applies when the top calc has a condition.
+ if (topCalc.getProgram().getCondition() == null) {
+ return false;
+ }
+
+ List<RexNode> topProjects = RemoteCalcCseUtil.expandProjects(topCalc);
+ Map<RexNode, Integer> bottomPythonCalls =
buildBottomPythonCallMap(bottomCalc, callFinder);
+
+ if (bottomPythonCalls.isEmpty()) {
+ return false;
+ }
+
+ // Check if any top projection contains a call matching the bottom
calc's output.
+ return topProjects.stream()
+ .anyMatch(node -> containsCallMatchingBottom(node,
bottomPythonCalls, callFinder));
+ }
+
+ @Override
+ public void onMatch(RelOptRuleCall call) {
+ FlinkLogicalCalc topCalc = call.rel(0);
+ FlinkLogicalCalc bottomCalc = call.rel(1);
+ RemoteCallFinder callFinder = config.remoteCallFinder();
+ RexBuilder rexBuilder = call.builder().getRexBuilder();
+
+ List<RexNode> topProjects = RemoteCalcCseUtil.expandProjects(topCalc);
+ RexNode topCondition =
+ topCalc.getProgram().getCondition() != null
+ ?
topCalc.getProgram().expandLocalRef(topCalc.getProgram().getCondition())
+ : null;
+
+ Map<RexNode, Integer> bottomPythonCalls =
buildBottomPythonCallMap(bottomCalc, callFinder);
+ RelDataType bottomRowType = bottomCalc.getRowType();
+
+ // Rewrite top projections: replace matching calls with RexInputRef.
+ CseRewriteShuttle rewriter = new CseRewriteShuttle(bottomPythonCalls,
bottomRowType);
+ List<RexNode> newTopProjects =
+ topProjects.stream().map(p ->
p.accept(rewriter)).collect(Collectors.toList());
+
+ if (!rewriter.hasRewritten()) {
+ return;
+ }
+
+ // Build the new top calc with rewritten projections.
+ call.transformTo(
+ topCalc.copy(
+ topCalc.getTraitSet(),
+ bottomCalc,
+ RexProgram.create(
+ bottomRowType,
+ newTopProjects,
+ topCondition,
+ topCalc.getRowType(),
+ rexBuilder)));
+ }
+
+ /**
+ * Builds a map from deterministic Python UDF calls in the bottom calc's
projection to their
+ * output index.
+ */
+ private Map<RexNode, Integer> buildBottomPythonCallMap(
Review Comment:
buildBottomPythonCallMap -> buildBottomRemoteCallMap.
--
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]