dianfu commented on code in PR #28998:
URL: https://github.com/apache/flink/pull/28998#discussion_r3921731195


##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/utils/PythonCallCseResult.java:
##########
@@ -0,0 +1,89 @@
+/*
+ * 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.nodes.exec.utils;
+
+import org.apache.flink.annotation.Internal;
+
+import org.apache.calcite.rex.RexCall;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/** Encapsulates the result of Python UDF call Common Sub-expression 
Elimination (CSE). */
+@Internal
+public class PythonCallCseResult {
+
+    /**
+     * The deduplicated Python UDF calls to be evaluated, in execution order.
+     *
+     * <p>Nested call trees are flattened so that a sub-expression shared 
between calls appears
+     * exactly once. For example {@code SELECT udf1(x), udf2(udf1(x))} yields 
{@code [udf1(x),
+     * udf2(<ref to udf1(x)>)]}.
+     */
+    private final List<RexCall> deduplicatedCalls;
+
+    /**
+     * For each projection entry, the position in {@link #deduplicatedCalls} 
holding its result.
+     *
+     * <p>Flattening appends intermediate sub-expressions that must not be 
emitted, and post-order
+     * can leave a projected result before the end of the list, so this is not 
necessarily the
+     * identity.
+     */
+    private final int[] outputIndices;
+
+    /**
+     * Maps a call to the position in {@link #deduplicatedCalls} where its 
result is computed.
+     *
+     * <p>Derived from {@link #deduplicatedCalls}: since the list is already 
deduplicated, the first
+     * occurrence of a structurally equal call is the one that computes it.
+     */
+    private final Map<RexCall, Integer> refMap;
+
+    public PythonCallCseResult(List<RexCall> deduplicatedCalls, int[] 
outputIndices) {
+        this.deduplicatedCalls = deduplicatedCalls;
+        this.outputIndices = outputIndices;
+        this.refMap = buildRefMap(deduplicatedCalls);
+    }
+
+    public List<RexCall> getDeduplicatedCalls() {
+        return deduplicatedCalls;
+    }
+
+    public int[] getOutputIndices() {
+        return outputIndices;
+    }
+
+    public Map<RexCall, Integer> getRefMap() {
+        return refMap;
+    }
+
+    /**
+     * Indexes the deduplicated calls by structural equality, keeping the 
first occurrence so that a
+     * parent references its own child rather than a later structurally equal 
duplicate.
+     */
+    private static Map<RexCall, Integer> buildRefMap(List<RexCall> 
deduplicatedCalls) {

Review Comment:
   Not every entry in this list is safe to reference, e.g. non-deterministic 
calls. It makes `SELECT Nondet(s), Det(Nondet(s))` incorrectly reuse the first 
result.



##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/utils/PythonCallDeduplicator.java:
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.nodes.exec.utils;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.planner.plan.utils.PythonUtil;
+import org.apache.flink.table.planner.utils.ShortcutUtils;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+
+/**
+ * Utility for Python UDF Common Sub-expression Elimination (CSE) of nested 
calls.
+ *
+ * <p>Nested Python UDF call trees are flattened in post-order and 
deduplicated by structural
+ * equivalence, so that a sub-expression shared between calls is evaluated 
only once by the Python
+ * worker. Duplicates between whole projection entries are already removed in 
the planner by {@code
+ * RemoteCalcProjectionCseRule}, so this only concerns sub-expressions.
+ */
+@Internal
+public class PythonCallDeduplicator {
+
+    /**
+     * Flattens the given Python UDF call trees and deduplicates the resulting 
calls.
+     *
+     * <p>Flattening all trees into a single list enables cross-subtree reuse: 
e.g. in {@code SELECT
+     * udf1(x), udf2(udf1(x))}, the inner {@code udf1(x)} is evaluated only 
once and {@code udf2}
+     * receives its result by reference.
+     */
+    public static PythonCallCseResult deduplicate(List<RexCall> 
pythonRexCalls) {

Review Comment:
   This flattens every deterministic nested call, even when no sub-expression 
is shared. As a result, `SELECT f(g(a))` switches to sequential worker 
execution and allocates a results list per row without any CSE benefit. 



##########
flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/plan/nodes/exec/utils/PythonCalcNestedCseInvariantTest.scala:
##########
@@ -0,0 +1,170 @@
+/*
+ * 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.nodes.exec.utils
+
+import org.apache.flink.table.api._
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNode
+import 
org.apache.flink.table.planner.plan.nodes.exec.common.CommonExecPythonCalc
+import 
org.apache.flink.table.planner.plan.nodes.physical.stream.StreamPhysicalRel
+import 
org.apache.flink.table.planner.runtime.utils.JavaUserDefinedScalarFunctions.PythonScalarFunction
+import org.apache.flink.table.planner.utils.{TableTestBase, TableTestUtil}
+import org.apache.flink.table.types.logical.RowType
+
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rex.{RexCall, RexNode}
+import org.assertj.core.api.Assertions.assertThat
+import org.junit.jupiter.api.{BeforeEach, Test}
+
+import scala.collection.JavaConverters._
+
+/**
+ * Tests the invariants of nested Python UDF flattening, driven through the 
real SQL pipeline so
+ * that genuine Python [[RexCall]]s are used.
+ *
+ * <p>Flattening happens while translating the ExecNode into a transformation 
and is therefore not
+ * visible in the optimized plan, so these invariants are asserted here rather 
than in a plan test.
+ */
+class PythonCalcNestedCseInvariantTest extends TableTestBase {

Review Comment:
   Could we rewrite this test as a Java test?



-- 
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]

Reply via email to