You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "AlanConfluent (via GitHub)" <gi...@apache.org> on 2024/01/09 00:40:28 UTC
Re: [PR] [FLINK-34027] Introduces AsyncScalarFunction as a new UDF type [flink]
AlanConfluent commented on code in PR #23975:
URL: https://github.com/apache/flink/pull/23975#discussion_r1443523374
##########
docs/layouts/shortcodes/generated/execution_config_configuration.html:
##########
@@ -26,6 +26,36 @@
<td>Duration</td>
<td>The async timeout for the asynchronous operation to complete.</td>
</tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.buffer-capacity</h5><br> <span class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">10</td>
+ <td>Integer</td>
+ <td>The max number of async i/o operation that the async lookup join can trigger.</td>
+ </tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.max-attempts</h5><br> <span class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">3</td>
+ <td>Integer</td>
+ <td>The max number of async retry attempts to make when </td>
Review Comment:
Completed sentence.
##########
docs/layouts/shortcodes/generated/execution_config_configuration.html:
##########
@@ -26,6 +26,36 @@
<td>Duration</td>
<td>The async timeout for the asynchronous operation to complete.</td>
</tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.buffer-capacity</h5><br> <span class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">10</td>
+ <td>Integer</td>
+ <td>The max number of async i/o operation that the async lookup join can trigger.</td>
+ </tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.max-attempts</h5><br> <span class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">3</td>
+ <td>Integer</td>
+ <td>The max number of async retry attempts to make when </td>
+ </tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.retry-delay</h5><br> <span class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">100 ms</td>
+ <td>Duration</td>
+ <td>The delay to wait before trying again.</td>
+ </tr>
+ <tr>
+ <td><h5>table.exec.async-scalar.retry-strategy</h5><br> <span class="label label-primary">Streaming</span></td>
+ <td style="word-wrap: break-word;">FIXED_DELAY</td>
+ <td><p>Enum</p></td>
+ <td>Restart strategy which will be used, FIXED_DELAY by default.<br /><br />Possible values:<ul><li>"FIXED_DELAY"</li></ul></td>
Review Comment:
I added `NO_RETRY`. That's a good call.
There could be other strategies, like exponential backoff or other schemes, but I didn't implement that yet.
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/ExecutionConfigOptions.java:
##########
@@ -692,6 +734,14 @@ public enum AsyncOutputMode {
ALLOW_UNORDERED
}
+ /** Retry strategy in the case of failure. */
+ @Experimental
Review Comment:
Done
##########
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/endpoint/hive/util/OperationExecutorFactory.java:
##########
@@ -579,6 +579,7 @@ private static List<Type> getSupportedHiveType() {
private static int toFunctionResult(FunctionKind kind) {
switch (kind) {
case SCALAR:
+ case ASYNC_SCALAR:
Review Comment:
Dropped
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.functions;
+
+import org.apache.flink.annotation.Experimental;
+import org.apache.flink.table.catalog.DataTypeFactory;
+import org.apache.flink.table.types.extraction.TypeInferenceExtractor;
+import org.apache.flink.table.types.inference.TypeInference;
+
+/**
+ * Base class for a user-defined scalar function which returns results asynchronously. A
+ * user-defined scalar function maps zero, one, or multiple scalar values to a new scalar value.
+ *
+ * <p>The behavior of a {@link AsyncScalarFunction} can be defined by implementing a custom
+ * evaluation method. An evaluation method must be declared publicly and named <code>eval</code>.
+ * Evaluation methods can also be overloaded by implementing multiple methods named <code>eval
+ * </code>. The first argument of the method must be a {@link
+ * java.util.concurrent.CompletableFuture} of the return type. The method body must complete the
+ * future either if there is a result or if it completes exceptionally.
+ *
+ * <p>By default, input and output data types are automatically extracted using reflection. If the
+ * reflective information is not sufficient, it can be supported and enriched with {@link
+ * org.apache.flink.table.annotation.DataTypeHint} and {@link
+ * org.apache.flink.table.annotation.FunctionHint} annotations.
+ *
+ * <p>The following examples show how to specify an async scalar function:
+ *
+ * <pre>{@code
+ * // a function that accepts two INT arguments and computes a sum
+ * class SumFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<Integer> future, Integer a, Integer b) {
+ * return future.complete(a + b);
+ * }
+ * }
+ *
+ * // a function that accepts either INT NOT NULL or BOOLEAN NOT NULL and computes a STRING
+ * class StringifyFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<String> future, int i) {
+ * return future.complete(String.valueOf(i));
+ * }
+ * public void eval(CompletableFuture<String> future, boolean b) {
+ * return future.complete(String.valueOf(b));
+ * }
+ * }
+ *
+ * // a function that accepts either INT or BOOLEAN and computes a STRING using function hints
+ * @FunctionHint(input = [@DataTypeHint("INT")])
+ * @FunctionHint(input = [@DataTypeHint("BOOLEAN")])
+ * class StringifyFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<String> future, Object o) {
+ * return future.complete(o.toString());
+ * }
+ * }
+ *
+ * // a function that accepts any data type as argument and computes a STRING
+ * class StringifyFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<String> future,
+ * @DataTypeHint(inputGroup = InputGroup.ANY) Object o) {
+ * return future.complete(o.toString());
+ * }
+ * }
+ *
+ * // a function that accepts an arbitrary number of BIGINT values and computes a DECIMAL(10, 4)
+ * class SumFunction extends AsyncScalarFunction {
+ * public void eval(@DataTypeHint("DECIMAL(10, 4)") CompletableFuture<BigDecimal> future,
+ * Long... values) {
+ * // ...
+ * }
+ * }
+ * }</pre>
+ *
+ * <p>For storing a user-defined function in a catalog, the class must have a default constructor
+ * and must be instantiable during runtime. Anonymous functions in Table API can only be persisted
+ * if the function is not stateful (i.e. containing only transient and static fields).
+ */
+@Experimental
+public class AsyncScalarFunction extends UserDefinedFunction {
+ @Override
+ public final FunctionKind getKind() {
+ return FunctionKind.ASYNC_SCALAR;
+ }
+
+ @Override
+ public TypeInference getTypeInference(DataTypeFactory typeFactory) {
+ TypeInference val = TypeInferenceExtractor.forAsyncScalarFunction(typeFactory, getClass());
Review Comment:
Done
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.functions;
+
+import org.apache.flink.annotation.Experimental;
+import org.apache.flink.table.catalog.DataTypeFactory;
+import org.apache.flink.table.types.extraction.TypeInferenceExtractor;
+import org.apache.flink.table.types.inference.TypeInference;
+
+/**
+ * Base class for a user-defined scalar function which returns results asynchronously. A
+ * user-defined scalar function maps zero, one, or multiple scalar values to a new scalar value.
+ *
+ * <p>The behavior of a {@link AsyncScalarFunction} can be defined by implementing a custom
+ * evaluation method. An evaluation method must be declared publicly and named <code>eval</code>.
+ * Evaluation methods can also be overloaded by implementing multiple methods named <code>eval
+ * </code>. The first argument of the method must be a {@link
+ * java.util.concurrent.CompletableFuture} of the return type. The method body must complete the
+ * future either if there is a result or if it completes exceptionally.
+ *
+ * <p>By default, input and output data types are automatically extracted using reflection. If the
+ * reflective information is not sufficient, it can be supported and enriched with {@link
+ * org.apache.flink.table.annotation.DataTypeHint} and {@link
+ * org.apache.flink.table.annotation.FunctionHint} annotations.
+ *
+ * <p>The following examples show how to specify an async scalar function:
+ *
+ * <pre>{@code
+ * // a function that accepts two INT arguments and computes a sum
+ * class SumFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<Integer> future, Integer a, Integer b) {
+ * return future.complete(a + b);
+ * }
+ * }
+ *
+ * // a function that accepts either INT NOT NULL or BOOLEAN NOT NULL and computes a STRING
+ * class StringifyFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<String> future, int i) {
+ * return future.complete(String.valueOf(i));
+ * }
+ * public void eval(CompletableFuture<String> future, boolean b) {
+ * return future.complete(String.valueOf(b));
+ * }
+ * }
+ *
+ * // a function that accepts either INT or BOOLEAN and computes a STRING using function hints
+ * @FunctionHint(input = [@DataTypeHint("INT")])
+ * @FunctionHint(input = [@DataTypeHint("BOOLEAN")])
+ * class StringifyFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<String> future, Object o) {
+ * return future.complete(o.toString());
+ * }
+ * }
+ *
+ * // a function that accepts any data type as argument and computes a STRING
+ * class StringifyFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<String> future,
+ * @DataTypeHint(inputGroup = InputGroup.ANY) Object o) {
+ * return future.complete(o.toString());
+ * }
+ * }
+ *
+ * // a function that accepts an arbitrary number of BIGINT values and computes a DECIMAL(10, 4)
+ * class SumFunction extends AsyncScalarFunction {
+ * public void eval(@DataTypeHint("DECIMAL(10, 4)") CompletableFuture<BigDecimal> future,
+ * Long... values) {
+ * // ...
+ * }
+ * }
+ * }</pre>
+ *
+ * <p>For storing a user-defined function in a catalog, the class must have a default constructor
+ * and must be instantiable during runtime. Anonymous functions in Table API can only be persisted
+ * if the function is not stateful (i.e. containing only transient and static fields).
+ */
+@Experimental
+public class AsyncScalarFunction extends UserDefinedFunction {
Review Comment:
Done
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/DataTypeExtractor.java:
##########
@@ -155,6 +157,48 @@ public static DataType extractFromMethodParameter(
paramPos, method.getName(), baseClass.getName()));
}
+ /**
+ * Extracts a data type from a method parameter by considering surrounding classes and parameter
+ * annotation. This version assumes that the parameter is a generic type, and uses the generic
+ * position type as the extracted data type. For example, if the parameter is a
+ * CompletableFuture<Long> and genericPos is 0, it will extract Long.
+ */
+ public static DataType extractFromGenericMethodParameter(
+ DataTypeFactory typeFactory,
+ Class<?> baseClass,
+ Method method,
+ int paramPos,
+ int genericPos) {
+
+ Type parameterType = method.getGenericParameterTypes()[paramPos];
+ // Trusty library allows to resolve generic types where the type resolves to a type with
+ // generic parameters...
+ parameterType = TypeToken.of(baseClass).resolveType(parameterType).getType();
Review Comment:
I have an IT case in `AsyncCalcITCase.testMultiLayerGeneric()` that exercises this case that motivated this. I commented out the line here, and low and behold it works. I didn't realize Flink can resolve variables climbing the class hierarchy as well. I think the original motivation was in `FunctionMappingExtractor` where this wasn't as easily available, and I wasn't aware that `extractDataTypeWithClassContext` existed and effectively does the same thing.
I made a simplified method `ExtractionUtils.resolveVariableWithClassContext`, so this resolution logic can be utilized by `FunctionMappingExtractor` when creating a `MethodVerification`.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunctionHelper.java:
##########
@@ -67,6 +67,8 @@ public final class UserDefinedFunctionHelper {
public static final String SCALAR_EVAL = "eval";
+ public static final String ASYNC_SCALAR_EVAL = "eval";
+
public static final String TABLE_EVAL = "eval";
Review Comment:
Done. Added `validateAsyncImplementationMethod`. I check for a lot of these in a couple places. The error before was decent, but this is probably better.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunctionHelper.java:
##########
@@ -67,6 +67,8 @@ public final class UserDefinedFunctionHelper {
public static final String SCALAR_EVAL = "eval";
+ public static final String ASYNC_SCALAR_EVAL = "eval";
Review Comment:
Missed that. Done
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/FunctionMappingExtractor.java:
##########
@@ -208,6 +249,32 @@ static MethodVerification createParameterWithArgumentVerification(
};
}
+ /** Verification that checks a method by parameters including an additional first parameter. */
+ static MethodVerification createGenericParameterWithArgumentAndReturnTypeVerification(
+ Class<?> baseClass, Class<?> argumentClass, int paramPos, int genericPos) {
+ return (method, signature, result) -> {
+ final Class<?>[] parameters =
+ Stream.concat(Stream.of(argumentClass), signature.stream())
+ .toArray(Class<?>[]::new);
+
+ Type genericType = method.getGenericParameterTypes()[paramPos];
+ // Trusty library allows to resolve generic types where the type resolves to a type with
+ // generic parameters...
+ genericType = TypeToken.of(baseClass).resolveType(genericType).getType();
Review Comment:
The purpose here was to have `returnType` resolved below so that the real types can be compared. I changed to using the flink resolution mechanism and it all works fine, as described above. Is that reasonable?
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.codegen;
+
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.functions.FunctionKind;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitorImpl;
+import org.apache.commons.text.StringSubstitutor;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * Generates an {@link AsyncFunction} which can be used to evaluate calc projections from an async
+ * scalar function.
+ */
+public class AsyncCodeGenerator {
+
+ public static final String DEFAULT_EXCEPTION_TERM = "e";
+ public static final String DEFAULT_DELEGATING_FUTURE_TERM = "f";
+
+ /**
+ * Creates a generated function which produces an {@link AsyncFunction} which executes the calc
+ * projections.
+ *
+ * @param name The name used to generate the underlying function name
+ * @param inputType The RowType of the input RowData
+ * @param returnType The RowType of the resulting RowData
+ * @param outRowClass The class used to generate the output RowData
+ * @param retainHeader If the header of the row should be retained
+ * @param calcProjection The list of projections to be executed by this function
+ * @param tableConfig The table configuration
+ * @param classLoader The classloader to use while resolving classes
+ * @return A {@link GeneratedFunction} returning an {@link AsyncFunction} executing the given
+ * list of projections
+ */
+ public static GeneratedFunction<AsyncFunction<RowData, RowData>> generateFunction(
+ String name,
+ RowType inputType,
+ RowType returnType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> calcProjection,
+ boolean retainHeader,
+ ReadableConfig tableConfig,
+ ClassLoader classLoader) {
+ CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig, classLoader);
+ String processCode =
+ generateProcessCode(
+ ctx,
+ inputType,
+ returnType,
+ outRowClass,
+ calcProjection,
+ retainHeader,
+ CodeGenUtils.DEFAULT_INPUT1_TERM(),
+ CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
+ DEFAULT_EXCEPTION_TERM,
+ CodeGenUtils.DEFAULT_OUT_RECORD_TERM(),
+ DEFAULT_DELEGATING_FUTURE_TERM);
+ return FunctionCodeGenerator.generateFunction(
+ ctx,
+ name,
+ getFunctionClass(),
+ processCode,
+ returnType,
+ inputType,
+ CodeGenUtils.DEFAULT_INPUT1_TERM(),
+ JavaScalaConversionUtil.toScala(Optional.empty()),
+ JavaScalaConversionUtil.toScala(Optional.empty()),
+ CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
+ CodeGenUtils.DEFAULT_CONTEXT_TERM());
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Class<AsyncFunction<RowData, RowData>> getFunctionClass() {
+ return (Class<AsyncFunction<RowData, RowData>>) (Object) AsyncFunction.class;
+ }
+
+ private static String generateProcessCode(
+ CodeGeneratorContext ctx,
+ RowType inputType,
+ RowType outRowType,
+ Class<? extends RowData> outRowClass,
Review Comment:
Removed.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.common;
+
+import org.apache.flink.api.dag.Transformation;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperatorFactory;
+import org.apache.flink.streaming.api.operators.async.AsyncWaitOperatorFactory;
+import org.apache.flink.streaming.api.transformations.OneInputTransformation;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
+import org.apache.flink.table.planner.codegen.AsyncCodeGenerator;
+import org.apache.flink.table.planner.delegation.PlannerBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.SingleTransformationTranslator;
+import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
+import org.apache.flink.table.planner.plan.utils.AsyncUtil;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.runtime.operators.calc.async.AsyncFunctionRunner;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/** Base class for exec Async Calc. */
+public abstract class CommonExecAsyncCalc extends ExecNodeBase<RowData>
+ implements SingleTransformationTranslator<RowData> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(CommonExecAsyncCalc.class);
+
+ public static final String ASYNC_CALC_TRANSFORMATION = "async-calc";
+
+ public static final String FIELD_NAME_PROJECTION = "projection";
+
+ public static final String FIELD_NAME_SYNC_MODE = "syncMode";
+
+ @JsonProperty(FIELD_NAME_PROJECTION)
+ private final List<RexNode> projection;
+
+ public CommonExecAsyncCalc(
+ int id,
+ ExecNodeContext context,
+ ReadableConfig persistedConfig,
+ List<RexNode> projection,
+ List<InputProperty> inputProperties,
+ RowType outputType,
+ String description) {
+ super(id, context, persistedConfig, inputProperties, outputType, description);
+ checkArgument(inputProperties.size() == 1);
+ this.projection = checkNotNull(projection);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ protected Transformation<RowData> translateToPlanInternal(
+ PlannerBase planner, ExecNodeConfig config) {
+ final ExecEdge inputEdge = getInputEdges().get(0);
+ final Transformation<RowData> inputTransform =
+ (Transformation<RowData>) inputEdge.translateToPlan(planner);
+ return createAsyncOneInputTransformation(
+ inputTransform, config, planner.getFlinkContext().getClassLoader());
+ }
+
+ private OneInputTransformation<RowData, RowData> createAsyncOneInputTransformation(
+ Transformation<RowData> inputTransform,
+ ExecNodeConfig config,
+ ClassLoader classLoader) {
+ List<RexCall> asyncRexCalls =
+ projection.stream()
+ .filter(x -> x instanceof RexCall)
+ .map(x -> (RexCall) x)
+ .collect(Collectors.toList());
+
+ List<Integer> forwardedFields =
+ projection.stream()
+ .filter(x -> x instanceof RexInputRef)
+ .map(x -> ((RexInputRef) x).getIndex())
+ .collect(Collectors.toList());
+ InternalTypeInfo<RowData> asyncOperatorInputTypeInfo =
+ (InternalTypeInfo<RowData>) inputTransform.getOutputType();
+ LogicalType[] inputLogicalTypes =
+ ((InternalTypeInfo<RowData>) inputTransform.getOutputType()).toRowFieldTypes();
+
+ List<LogicalType> forwardedFieldsLogicalTypes =
+ forwardedFields.stream()
+ .map(i -> inputLogicalTypes[i])
+ .collect(Collectors.toList());
+ List<LogicalType> asyncCallLogicalTypes =
+ asyncRexCalls.stream()
+ .map(node -> FlinkTypeFactory.toLogicalType(node.getType()))
+ .collect(Collectors.toList());
+ List<LogicalType> fieldsLogicalTypes = new ArrayList<>();
+ fieldsLogicalTypes.addAll(forwardedFieldsLogicalTypes);
+ fieldsLogicalTypes.addAll(asyncCallLogicalTypes);
+ InternalTypeInfo<RowData> asyncOperatorResultTypeInfo =
+ InternalTypeInfo.ofFields(fieldsLogicalTypes.toArray(new LogicalType[0]));
+ OneInputStreamOperatorFactory<RowData, RowData> factory =
+ getAsyncFunctionOperator(config, classLoader, asyncOperatorInputTypeInfo);
+ return ExecNodeUtil.createOneInputTransformation(
+ inputTransform,
+ createTransformationMeta(ASYNC_CALC_TRANSFORMATION, config),
+ factory,
+ asyncOperatorResultTypeInfo,
+ inputTransform.getParallelism(),
+ false);
+ }
+
+ private OneInputStreamOperatorFactory<RowData, RowData> getAsyncFunctionOperator(
+ ExecNodeConfig config,
+ ClassLoader classLoader,
+ InternalTypeInfo<RowData> inputRowTypeInfo) {
+
+ List<LogicalType> resultTypes =
+ projection.stream()
+ .map(node -> FlinkTypeFactory.toLogicalType(node.getType()))
+ .collect(Collectors.toList());
Review Comment:
Ok, I tried to create RowType first and do everything from that.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.common;
+
+import org.apache.flink.api.dag.Transformation;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperatorFactory;
+import org.apache.flink.streaming.api.operators.async.AsyncWaitOperatorFactory;
+import org.apache.flink.streaming.api.transformations.OneInputTransformation;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
+import org.apache.flink.table.planner.codegen.AsyncCodeGenerator;
+import org.apache.flink.table.planner.delegation.PlannerBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.SingleTransformationTranslator;
+import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
+import org.apache.flink.table.planner.plan.utils.AsyncUtil;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.runtime.operators.calc.async.AsyncFunctionRunner;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/** Base class for exec Async Calc. */
+public abstract class CommonExecAsyncCalc extends ExecNodeBase<RowData>
+ implements SingleTransformationTranslator<RowData> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(CommonExecAsyncCalc.class);
+
+ public static final String ASYNC_CALC_TRANSFORMATION = "async-calc";
+
+ public static final String FIELD_NAME_PROJECTION = "projection";
+
+ public static final String FIELD_NAME_SYNC_MODE = "syncMode";
Review Comment:
Done
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.codegen;
+
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.functions.FunctionKind;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitorImpl;
+import org.apache.commons.text.StringSubstitutor;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * Generates an {@link AsyncFunction} which can be used to evaluate calc projections from an async
+ * scalar function.
+ */
+public class AsyncCodeGenerator {
+
+ public static final String DEFAULT_EXCEPTION_TERM = "e";
+ public static final String DEFAULT_DELEGATING_FUTURE_TERM = "f";
+
+ /**
+ * Creates a generated function which produces an {@link AsyncFunction} which executes the calc
+ * projections.
+ *
+ * @param name The name used to generate the underlying function name
+ * @param inputType The RowType of the input RowData
+ * @param returnType The RowType of the resulting RowData
+ * @param outRowClass The class used to generate the output RowData
+ * @param retainHeader If the header of the row should be retained
+ * @param calcProjection The list of projections to be executed by this function
+ * @param tableConfig The table configuration
+ * @param classLoader The classloader to use while resolving classes
+ * @return A {@link GeneratedFunction} returning an {@link AsyncFunction} executing the given
+ * list of projections
+ */
+ public static GeneratedFunction<AsyncFunction<RowData, RowData>> generateFunction(
+ String name,
+ RowType inputType,
+ RowType returnType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> calcProjection,
+ boolean retainHeader,
+ ReadableConfig tableConfig,
+ ClassLoader classLoader) {
+ CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig, classLoader);
+ String processCode =
+ generateProcessCode(
+ ctx,
+ inputType,
+ returnType,
+ outRowClass,
+ calcProjection,
+ retainHeader,
+ CodeGenUtils.DEFAULT_INPUT1_TERM(),
+ CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
+ DEFAULT_EXCEPTION_TERM,
+ CodeGenUtils.DEFAULT_OUT_RECORD_TERM(),
+ DEFAULT_DELEGATING_FUTURE_TERM);
+ return FunctionCodeGenerator.generateFunction(
+ ctx,
+ name,
+ getFunctionClass(),
+ processCode,
+ returnType,
+ inputType,
+ CodeGenUtils.DEFAULT_INPUT1_TERM(),
+ JavaScalaConversionUtil.toScala(Optional.empty()),
+ JavaScalaConversionUtil.toScala(Optional.empty()),
+ CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
+ CodeGenUtils.DEFAULT_CONTEXT_TERM());
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Class<AsyncFunction<RowData, RowData>> getFunctionClass() {
+ return (Class<AsyncFunction<RowData, RowData>>) (Object) AsyncFunction.class;
+ }
+
+ private static String generateProcessCode(
+ CodeGeneratorContext ctx,
+ RowType inputType,
+ RowType outRowType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> projection,
+ boolean retainHeader,
+ String inputTerm,
+ String collectorTerm,
+ String errorTerm,
+ String recordTerm,
+ String delegatingFutureTerm) {
+
+ projection.forEach(n -> n.accept(new AsyncScalarFunctionsValidator()));
+
+ ExprCodeGenerator exprGenerator =
+ new ExprCodeGenerator(ctx, false)
+ .bindInput(
+ inputType,
+ inputTerm,
+ JavaScalaConversionUtil.toScala(Optional.empty()));
+
+ List<GeneratedExpression> projectionExprs =
+ projection.stream()
+ .map(exprGenerator::generateExpression)
+ .collect(Collectors.toList());
+ int syncIndex = 0;
+ int index = 0;
+ StringBuilder outputs = new StringBuilder();
+ StringBuilder syncInvocations = new StringBuilder();
+ StringBuilder asyncInvocation = new StringBuilder();
+ if (retainHeader) {
+ outputs.append(String.format("%s.setRowKind(rowKind);\n", recordTerm, inputTerm));
+ }
+ for (GeneratedExpression fieldExpr : projectionExprs) {
+ if (fieldExpr.resultTerm().isEmpty()) {
+ outputs.append(
+ String.format("%s.setField(%d, resultObject);\n", recordTerm, index));
+ asyncInvocation.append(fieldExpr.code());
+ } else {
+ outputs.append(
+ String.format(
+ "%s.setField(%d, %s.getSynchronousResult(%d));\n",
+ recordTerm, index, delegatingFutureTerm, syncIndex));
+ syncInvocations.append(fieldExpr.code());
+ syncInvocations.append(
+ String.format(
+ "%s.addSynchronousResult(%s);\n",
+ delegatingFutureTerm, fieldExpr.resultTerm()));
+ syncIndex++;
+ }
+ index++;
+ }
+
+ Map<String, String> values = new HashMap<>();
+ values.put("delegatingFuture", delegatingFutureTerm);
+ values.put("collectorTerm", collectorTerm);
+ values.put("typeTerm", outRowClass.getCanonicalName());
+ values.put("recordTerm", recordTerm);
+ values.put("inputTerm", inputTerm);
+ values.put("fieldCount", Integer.toString(LogicalTypeChecks.getFieldCount(outRowType)));
+ values.put("outputs", outputs.toString());
+ values.put("syncInvocations", syncInvocations.toString());
+ values.put("asyncInvocation", asyncInvocation.toString());
+ values.put("errorTerm", errorTerm);
+
+ return StringSubstitutor.replace(
Review Comment:
I just took a stab at it, and it wasn't too bad, so long as you don't mind using `StringSubstitutor` for templating. Open to other java libraries as well, but didn't see anything that really stood out.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecAsyncCalc.java:
##########
@@ -0,0 +1,75 @@
+/*
+ * 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.stream;
+
+import org.apache.flink.FlinkVersion;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeMetadata;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.common.CommonExecAsyncCalc;
+import org.apache.flink.table.types.logical.RowType;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
+
+import org.apache.calcite.rex.RexNode;
+
+import java.util.Collections;
+import java.util.List;
+
+/** Stream {@link ExecNode} for AsyncScalarFunctions. */
+@ExecNodeMetadata(
+ name = "stream-exec-async-calc",
+ version = 1,
+ producedTransformations = CommonExecAsyncCalc.ASYNC_CALC_TRANSFORMATION,
+ minPlanVersion = FlinkVersion.v1_17,
+ minStateVersion = FlinkVersion.v1_17)
Review Comment:
Added.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.common;
+
+import org.apache.flink.api.dag.Transformation;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperatorFactory;
+import org.apache.flink.streaming.api.operators.async.AsyncWaitOperatorFactory;
+import org.apache.flink.streaming.api.transformations.OneInputTransformation;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
+import org.apache.flink.table.planner.codegen.AsyncCodeGenerator;
+import org.apache.flink.table.planner.delegation.PlannerBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.SingleTransformationTranslator;
+import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
+import org.apache.flink.table.planner.plan.utils.AsyncUtil;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.runtime.operators.calc.async.AsyncFunctionRunner;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/** Base class for exec Async Calc. */
+public abstract class CommonExecAsyncCalc extends ExecNodeBase<RowData>
+ implements SingleTransformationTranslator<RowData> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(CommonExecAsyncCalc.class);
+
+ public static final String ASYNC_CALC_TRANSFORMATION = "async-calc";
+
+ public static final String FIELD_NAME_PROJECTION = "projection";
+
+ public static final String FIELD_NAME_SYNC_MODE = "syncMode";
+
+ @JsonProperty(FIELD_NAME_PROJECTION)
+ private final List<RexNode> projection;
+
+ public CommonExecAsyncCalc(
+ int id,
+ ExecNodeContext context,
+ ReadableConfig persistedConfig,
+ List<RexNode> projection,
+ List<InputProperty> inputProperties,
+ RowType outputType,
+ String description) {
+ super(id, context, persistedConfig, inputProperties, outputType, description);
+ checkArgument(inputProperties.size() == 1);
+ this.projection = checkNotNull(projection);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ protected Transformation<RowData> translateToPlanInternal(
+ PlannerBase planner, ExecNodeConfig config) {
+ final ExecEdge inputEdge = getInputEdges().get(0);
+ final Transformation<RowData> inputTransform =
+ (Transformation<RowData>) inputEdge.translateToPlan(planner);
+ return createAsyncOneInputTransformation(
+ inputTransform, config, planner.getFlinkContext().getClassLoader());
+ }
+
+ private OneInputTransformation<RowData, RowData> createAsyncOneInputTransformation(
+ Transformation<RowData> inputTransform,
+ ExecNodeConfig config,
+ ClassLoader classLoader) {
+ List<RexCall> asyncRexCalls =
+ projection.stream()
+ .filter(x -> x instanceof RexCall)
+ .map(x -> (RexCall) x)
+ .collect(Collectors.toList());
+
+ List<Integer> forwardedFields =
+ projection.stream()
+ .filter(x -> x instanceof RexInputRef)
+ .map(x -> ((RexInputRef) x).getIndex())
+ .collect(Collectors.toList());
+ InternalTypeInfo<RowData> asyncOperatorInputTypeInfo =
+ (InternalTypeInfo<RowData>) inputTransform.getOutputType();
+ LogicalType[] inputLogicalTypes =
+ ((InternalTypeInfo<RowData>) inputTransform.getOutputType()).toRowFieldTypes();
Review Comment:
Done
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalAsyncCalc.java:
##########
@@ -0,0 +1,85 @@
+/*
+ * 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.physical.stream;
+
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecAsyncCalc;
+import org.apache.flink.table.planner.plan.utils.AsyncUtil;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Calc;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.table.planner.utils.ShortcutUtils.unwrapTableConfig;
+
+/** Stream physical RelNode for AsyncScalarFunctions. */
Review Comment:
Done
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalAsyncCalc.java:
##########
@@ -0,0 +1,85 @@
+/*
+ * 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.physical.stream;
+
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecAsyncCalc;
+import org.apache.flink.table.planner.plan.utils.AsyncUtil;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Calc;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.table.planner.utils.ShortcutUtils.unwrapTableConfig;
+
+/** Stream physical RelNode for AsyncScalarFunctions. */
+public class StreamPhysicalAsyncCalc extends StreamPhysicalCalcBase {
+ private final RelOptCluster cluster;
+ private final RexProgram calcProgram;
+ private final RelDataType outputRowType;
+
+ public StreamPhysicalAsyncCalc(
+ RelOptCluster cluster,
+ RelTraitSet traitSet,
+ RelNode inputRel,
+ RexProgram calcProgram,
+ RelDataType outputRowType) {
+ super(cluster, traitSet, inputRel, calcProgram, outputRowType);
+ this.cluster = cluster;
+ this.calcProgram = calcProgram;
+ this.outputRowType = outputRowType;
+ }
+
+ @Override
+ public Calc copy(RelTraitSet traitSet, RelNode child, RexProgram program) {
+ return new StreamPhysicalAsyncCalc(cluster, traitSet, child, program, outputRowType);
+ }
+
+ @Override
+ public ExecNode<?> translateToExecNode() {
+ List<RexNode> projection =
+ calcProgram.getProjectList().stream()
+ .map(calcProgram::expandLocalRef)
+ .collect(Collectors.toList());
+ if (calcProgram.getCondition() != null) {
+ throw new TableException("The condition of StreamPhysicalAsyncCalc should be null.");
+ }
+ if (projection.stream().filter(AsyncUtil::containsAsyncCall).count() > 1) {
+ throw new TableException(
+ "Only a single async projection is allowed in " + "StreamPhysicalAsyncCalc.");
Review Comment:
I explained this in a bit more detail previously, but more complex calcs are split up so that an async call is alone as a projection with no other async calls (though possibly other projections) and no conditions. These are all accomplished with the rules. So obviously conditions and multiple async call are allowed, they are all split up. You can check out the IT Cases to see the various tests done.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRule.java:
##########
@@ -0,0 +1,194 @@
+/*
+ * 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.flink.table.planner.plan.utils.AsyncUtil;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+import scala.Option;
+import scala.Tuple3;
+import scala.collection.Seq;
+
+/**
+ * Defines split rules for async calc nodes. These largely exist to isolate and simplify the calls
+ * to the async function from other calc operations, so that the operator can handle just that
+ * functionality.
+ */
+public class AsyncCalcSplitRule {
+
+ private static final RemoteCalcCallFinder ASYNC_CALL_FINDER = new AsyncRemoteCalcCallFinder();
+ public static final RelOptRule SPLIT_CONDITION =
+ new RemoteCalcSplitConditionRule(ASYNC_CALL_FINDER);
+ public static final RelOptRule SPLIT_PROJECT =
+ new RemoteCalcSplitProjectionRule(ASYNC_CALL_FINDER);
+ public static final RelOptRule SPLIT_PROJECTION_REX_FIELD =
+ new RemoteCalcSplitProjectionRexFieldRule(ASYNC_CALL_FINDER);
+ public static final RelOptRule SPLIT_CONDITION_REX_FIELD =
+ new RemoteCalcSplitConditionRexFieldRule(ASYNC_CALL_FINDER);
+ public static final RelOptRule EXPAND_PROJECT =
+ new RemoteCalcExpandProjectRule(ASYNC_CALL_FINDER);
+ public static final RelOptRule PUSH_CONDITION =
+ new RemoteCalcPushConditionRule(ASYNC_CALL_FINDER);
+ public static final RelOptRule REWRITE_PROJECT =
+ new RemoteCalcRewriteProjectionRule(ASYNC_CALL_FINDER);
+ public static final RelOptRule NESTED_SPLIT = new AsyncCalcSplitNestedRule(ASYNC_CALL_FINDER);
+ public static final RelOptRule ONE_PER_CALC_SPLIT =
+ new AsyncCalcSplitOnePerCalcRule(ASYNC_CALL_FINDER);
+
+ /**
+ * An Async implementation of {@link RemoteCalcCallFinder} which finds uses of
+ * AsyncScalarFunction.
+ */
+ public static class AsyncRemoteCalcCallFinder implements RemoteCalcCallFinder {
+ @Override
+ public boolean containsRemoteCall(RexNode node) {
+ return AsyncUtil.containsAsyncCall(node);
+ }
+
+ @Override
+ public boolean containsNonRemoteCall(RexNode node) {
+ return AsyncUtil.containsNonAsyncCall(node);
+ }
+
+ @Override
+ public boolean isRemoteCall(RexNode node) {
+ return AsyncUtil.isAsyncCall(node);
+ }
+
+ @Override
+ public boolean isNonRemoteCall(RexNode node) {
+ return AsyncUtil.isNonAsyncCall(node);
+ }
+ }
+
+ private static boolean hasNestedCalls(List<RexNode> projects) {
+ return projects.stream()
+ .filter(AsyncUtil::containsAsyncCall)
+ .filter(expr -> expr instanceof RexCall)
+ .map(expr -> (RexCall) expr)
+ .anyMatch(
+ rexCall ->
+ rexCall.getOperands().stream()
+ .anyMatch(AsyncUtil::containsAsyncCall));
+ }
+
+ /**
+ * Splits nested call <- asyncCall chains so that nothing is immediately waiting on an async
+ * call in a single calc.
+ */
+ public static class AsyncCalcSplitNestedRule extends RemoteCalcSplitRuleBase<Void> {
+
+ public AsyncCalcSplitNestedRule(RemoteCalcCallFinder callFinder) {
+ super("AsyncCalcSplitNestedRule", callFinder);
+ }
+
+ @Override
+ public boolean matches(RelOptRuleCall call) {
+ FlinkLogicalCalc calc = call.rel(0);
+
+ // Matches if we have nested remote calls
+ List<RexNode> projects =
+ calc.getProgram().getProjectList().stream()
+ .map(calc.getProgram()::expandLocalRef)
+ .collect(Collectors.toList());
+ return hasNestedCalls(projects);
+ }
+
+ // We convert not on the outermost call, but anything within it
+ @Override
+ public boolean needConvert(RexProgram program, RexNode node, Option<Void> matchState) {
+ return node instanceof RexCall
+ && !((RexCall) node)
+ .getOperands().stream().anyMatch(callFinder()::containsRemoteCall);
+ }
+
+ @Override
+ public Tuple3<Option<RexNode>, Option<RexNode>, Seq<RexNode>> split(
Review Comment:
I agree. This was just to be compatible with the base class written in Scala (this is a Scala tuple). Not sure if this is considered Scala style, but I agree it's still easier to understand, so made the change.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/AsyncUtil.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.utils;
+
+import org.apache.flink.streaming.api.datastream.AsyncDataStream;
+import org.apache.flink.streaming.api.functions.async.AsyncRetryStrategy;
+import org.apache.flink.streaming.util.retryable.AsyncRetryStrategies;
+import org.apache.flink.table.api.config.ExecutionConfigOptions;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionDefinition;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.Collection;
+import java.util.Objects;
+import java.util.function.Predicate;
+
+/** Contains utilities for AsyncScalarFunctions. */
+public class AsyncUtil {
+
+ private static final EmptyResponseResultStrategy EMPTY_RESPONSE =
+ new EmptyResponseResultStrategy();
+ private static final Predicate<Throwable> ANY_EXCEPTION = new AnyExceptionStrategy();
+
+ /**
+ * Checks whether it contains the specified kind of async function call in the specified node.
+ *
+ * @param node the RexNode to check
+ * @return true if it contains an async function call in the specified node.
+ */
+ public static boolean containsAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(true, true));
+ }
+
+ /**
+ * Checks whether it contains non-async function call in the specified node.
+ *
+ * @param node the RexNode to check
+ * @return true if it contains a non-async function call in the specified node.
+ */
+ public static boolean containsNonAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(false, true));
+ }
+
+ /**
+ * Checks whether the specified node is the specified kind of async function call.
+ *
+ * @param node the RexNode to check
+ * @return true if the specified node is an async function call.
+ */
+ public static boolean isAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(true, false));
+ }
+
+ /**
+ * Checks whether the specified node is a non-async function call.
+ *
+ * @param node the RexNode to check
+ * @return true if the specified node is a non-async function call.
+ */
+ public static boolean isNonAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(false, false));
+ }
+
+ /**
+ * Gets the options required to run the operator.
+ *
+ * @param config The config from which to fetch the options
+ * @return Extracted options
+ */
+ public static AsyncUtil.Options getAsyncOptions(ExecNodeConfig config) {
+ return new AsyncUtil.Options(
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY),
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_TIMEOUT).toMillis(),
+ AsyncDataStream.OutputMode.ORDERED,
+ getResultRetryStrategy(
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_RETRY_STRATEGY),
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_RETRY_DELAY),
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_MAX_ATTEMPTS)));
+ }
+
+ /** Options for configuring async behavior. */
+ public static class Options {
+
+ public final int asyncBufferCapacity;
+ public final long asyncTimeout;
+ public final AsyncDataStream.OutputMode asyncOutputMode;
+ public final AsyncRetryStrategy<RowData> asyncRetryStrategy;
+
+ @JsonCreator
Review Comment:
No, I don't think there is any json serialization required for this object. I think this was copied from somewhere. Will remove.
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/ExpressionReducer.scala:
##########
@@ -65,9 +66,9 @@ class ExpressionReducer(
constExprs: java.util.List[RexNode],
reducedValues: java.util.List[RexNode]): Unit = {
- val pythonUDFExprs = new ListBuffer[RexNode]()
+ val asyncUDFExprs = new ListBuffer[RexNode]()
Review Comment:
Correct. That has been my terminology, even though technically it's anything that takes time (and doesn't strictly have to be remote).
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/AsyncUtil.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.utils;
+
+import org.apache.flink.streaming.api.datastream.AsyncDataStream;
+import org.apache.flink.streaming.api.functions.async.AsyncRetryStrategy;
+import org.apache.flink.streaming.util.retryable.AsyncRetryStrategies;
+import org.apache.flink.table.api.config.ExecutionConfigOptions;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionDefinition;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.Collection;
+import java.util.Objects;
+import java.util.function.Predicate;
+
+/** Contains utilities for AsyncScalarFunctions. */
+public class AsyncUtil {
+
+ private static final EmptyResponseResultStrategy EMPTY_RESPONSE =
+ new EmptyResponseResultStrategy();
+ private static final Predicate<Throwable> ANY_EXCEPTION = new AnyExceptionStrategy();
+
+ /**
+ * Checks whether it contains the specified kind of async function call in the specified node.
+ *
+ * @param node the RexNode to check
+ * @return true if it contains an async function call in the specified node.
+ */
+ public static boolean containsAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(true, true));
+ }
+
+ /**
+ * Checks whether it contains non-async function call in the specified node.
+ *
+ * @param node the RexNode to check
+ * @return true if it contains a non-async function call in the specified node.
+ */
+ public static boolean containsNonAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(false, true));
+ }
+
+ /**
+ * Checks whether the specified node is the specified kind of async function call.
+ *
+ * @param node the RexNode to check
+ * @return true if the specified node is an async function call.
+ */
+ public static boolean isAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(true, false));
+ }
+
+ /**
+ * Checks whether the specified node is a non-async function call.
+ *
+ * @param node the RexNode to check
+ * @return true if the specified node is a non-async function call.
+ */
+ public static boolean isNonAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(false, false));
+ }
+
+ /**
+ * Gets the options required to run the operator.
+ *
+ * @param config The config from which to fetch the options
+ * @return Extracted options
+ */
+ public static AsyncUtil.Options getAsyncOptions(ExecNodeConfig config) {
+ return new AsyncUtil.Options(
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY),
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_TIMEOUT).toMillis(),
+ AsyncDataStream.OutputMode.ORDERED,
+ getResultRetryStrategy(
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_RETRY_STRATEGY),
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_RETRY_DELAY),
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_MAX_ATTEMPTS)));
+ }
+
+ /** Options for configuring async behavior. */
+ public static class Options {
+
+ public final int asyncBufferCapacity;
+ public final long asyncTimeout;
+ public final AsyncDataStream.OutputMode asyncOutputMode;
+ public final AsyncRetryStrategy<RowData> asyncRetryStrategy;
+
+ @JsonCreator
+ public Options(
+ int asyncBufferCapacity,
+ long asyncTimeout,
+ AsyncDataStream.OutputMode asyncOutputMode,
+ AsyncRetryStrategy<RowData> asyncRetryStrategy) {
+ this.asyncBufferCapacity = asyncBufferCapacity;
+ this.asyncTimeout = asyncTimeout;
+ this.asyncOutputMode = asyncOutputMode;
+ this.asyncRetryStrategy = asyncRetryStrategy;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Options that = (Options) o;
+ return asyncBufferCapacity == that.asyncBufferCapacity
+ && asyncTimeout == that.asyncTimeout
+ && asyncOutputMode == that.asyncOutputMode;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(asyncBufferCapacity, asyncTimeout, asyncOutputMode);
+ }
+
+ @Override
+ public String toString() {
+ return asyncOutputMode + ", " + asyncTimeout + "ms, " + asyncBufferCapacity;
+ }
+ }
+
+ private static AsyncRetryStrategy<RowData> getResultRetryStrategy(
+ ExecutionConfigOptions.RetryStrategy retryStrategy,
+ Duration retryDelay,
+ int retryMaxAttempts) {
+ // Only fixed delay is allowed at the moment, so just ignore the config.
+ return new AsyncRetryStrategies.FixedDelayRetryStrategyBuilder<RowData>(
+ retryMaxAttempts, retryDelay.toMillis())
+ .ifResult(EMPTY_RESPONSE)
+ .ifException(ANY_EXCEPTION)
+ .build();
+ // return NO_RETRY_STRATEGY;
+ }
+
+ private static class FunctionFinder extends RexDefaultVisitor<Boolean> {
+
+ private final boolean findAsyncCall;
+ private final boolean recursive;
+
+ public FunctionFinder(boolean findAsyncCall, boolean recursive) {
+ this.findAsyncCall = findAsyncCall;
+ this.recursive = recursive;
+ }
+
+ @Override
+ public Boolean visitNode(RexNode rexNode) {
+ return false;
+ }
+
+ private boolean isImmediateAsyncCall(RexCall call) {
+ if (!(call.getOperator() instanceof BridgingSqlFunction)) {
+ return false;
+ }
+ FunctionDefinition definition =
+ ((BridgingSqlFunction) call.getOperator()).getDefinition();
+ return AsyncScalarFunction.class.isAssignableFrom(definition.getClass());
Review Comment:
Ah, makes sense. So long as the `SpecializedFunction` says the implementation is an async_scalar, we don't need to actually have it available until specialized is called if the check is done this way.
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/codegen/AsyncCodeGeneratorTest.java:
##########
@@ -0,0 +1,228 @@
+/*
+ * 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.codegen;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.streaming.api.functions.async.ResultFuture;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.catalog.UnresolvedIdentifier;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.planner.calcite.FlinkContext;
+import org.apache.flink.table.planner.calcite.SqlToRexConverter;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+import org.apache.flink.table.planner.utils.PlannerMocks;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.types.logical.BigIntType;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.IntType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.TimestampType;
+import org.apache.flink.table.types.logical.VarCharType;
+import org.apache.flink.table.utils.CatalogManagerMocks;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Test for {@link AsyncCodeGenerator}. */
+public class AsyncCodeGeneratorTest {
+
+ private static final RowType INPUT_TYPE =
+ RowType.of(new IntType(), new BigIntType(), new VarCharType());
+
+ private PlannerMocks plannerMocks;
+ private SqlToRexConverter converter;
+
+ private RelDataType tableRowType;
+
+ @BeforeEach
+ public void before() {
+ plannerMocks = PlannerMocks.create();
+ tableRowType =
+ plannerMocks
+ .getPlannerContext()
+ .getTypeFactory()
+ .buildRelNodeRowType(
+ JavaScalaConversionUtil.toScala(ImmutableList.of("f1", "f2", "f3")),
+ JavaScalaConversionUtil.toScala(
+ ImmutableList.of(
+ new IntType(),
+ new BigIntType(),
+ new VarCharType())));
+ converter =
+ plannerMocks
Review Comment:
Heh, nice. Used that.
##########
flink-table/flink-table-planner/src/test/resources/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRuleTest.xml:
##########
@@ -0,0 +1,536 @@
+<?xml version="1.0" ?>
+<!--
+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.
+-->
+<Root>
+ <TestCase name="testSingleCall">
+ <Resource name="sql">
+ <![CDATA[SELECT func1(a) FROM MyTable]]>
+ </Resource>
+ <Resource name="ast">
+ <![CDATA[
+LogicalProject(EXPR$0=[func1($0)])
++- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]])
+]]>
+ </Resource>
+ <Resource name="optimized rel plan">
+ <![CDATA[
+AsyncCalc(select=[func1(a) AS EXPR$0])
++- LegacyTableSourceScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]], fields=[a, b, c, d])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLiteralPlusTableSelect">
+ <Resource name="sql">
+ <![CDATA[SELECT 'foo', func1(a) FROM MyTable]]>
+ </Resource>
+ <Resource name="ast">
+ <![CDATA[
+LogicalProject(EXPR$0=[_UTF-16LE'foo'], EXPR$1=[func1($0)])
++- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]])
+]]>
+ </Resource>
+ <Resource name="optimized rel plan">
+ <![CDATA[
+Calc(select=['foo' AS EXPR$0, f0 AS EXPR$1])
++- AsyncCalc(select=[func1(a) AS f0])
+ +- LegacyTableSourceScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]], fields=[a, b, c, d])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testFieldPlusTableSelect">
+ <Resource name="sql">
+ <![CDATA[SELECT a, func1(a) from MyTable]]>
+ </Resource>
+ <Resource name="ast">
+ <![CDATA[
+LogicalProject(a=[$0], EXPR$1=[func1($0)])
++- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]])
+]]>
+ </Resource>
+ <Resource name="optimized rel plan">
+ <![CDATA[
+AsyncCalc(select=[a, func1(a) AS EXPR$1])
++- LegacyTableSourceScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]], fields=[a, b, c, d])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testTwoCalls">
+ <Resource name="sql">
+ <![CDATA[SELECT func1(a), func1(a) from MyTable]]>
+ </Resource>
+ <Resource name="ast">
+ <![CDATA[
+LogicalProject(EXPR$0=[func1($0)], EXPR$1=[func1($0)])
++- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]])
+]]>
+ </Resource>
+ <Resource name="optimized rel plan">
+ <![CDATA[
+AsyncCalc(select=[f0 AS EXPR$0, func1(a) AS EXPR$1])
Review Comment:
Yeah, that's true. My original version actually did allow for parallel calls to exist alongside each other. It seems like there are tradeoffs because if you allow them in the same operator, then one call failing would fail the other and they would have to be retried together. Not a huge deal in the common case (of say two calls), but if you had a bunch of them, it could decrease overall throughput quite a lot.
To allow for them, I would just have to add support in `DelegatingAsyncResultFuture` for multiple futures, and wait for them all. Then I could remove the rule which prevents parallel calls. Will create a ticket to followup.
##########
flink-table/flink-table-planner/src/test/resources/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRuleTest.xml:
##########
@@ -0,0 +1,536 @@
+<?xml version="1.0" ?>
+<!--
+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.
+-->
+<Root>
+ <TestCase name="testSingleCall">
+ <Resource name="sql">
+ <![CDATA[SELECT func1(a) FROM MyTable]]>
+ </Resource>
+ <Resource name="ast">
+ <![CDATA[
+LogicalProject(EXPR$0=[func1($0)])
++- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]])
+]]>
+ </Resource>
+ <Resource name="optimized rel plan">
+ <![CDATA[
+AsyncCalc(select=[func1(a) AS EXPR$0])
++- LegacyTableSourceScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]], fields=[a, b, c, d])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLiteralPlusTableSelect">
+ <Resource name="sql">
+ <![CDATA[SELECT 'foo', func1(a) FROM MyTable]]>
+ </Resource>
+ <Resource name="ast">
+ <![CDATA[
+LogicalProject(EXPR$0=[_UTF-16LE'foo'], EXPR$1=[func1($0)])
++- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]])
+]]>
+ </Resource>
+ <Resource name="optimized rel plan">
+ <![CDATA[
+Calc(select=['foo' AS EXPR$0, f0 AS EXPR$1])
++- AsyncCalc(select=[func1(a) AS f0])
+ +- LegacyTableSourceScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]], fields=[a, b, c, d])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testFieldPlusTableSelect">
+ <Resource name="sql">
+ <![CDATA[SELECT a, func1(a) from MyTable]]>
+ </Resource>
+ <Resource name="ast">
+ <![CDATA[
+LogicalProject(a=[$0], EXPR$1=[func1($0)])
++- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]])
+]]>
+ </Resource>
+ <Resource name="optimized rel plan">
+ <![CDATA[
+AsyncCalc(select=[a, func1(a) AS EXPR$1])
++- LegacyTableSourceScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]], fields=[a, b, c, d])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testTwoCalls">
+ <Resource name="sql">
+ <![CDATA[SELECT func1(a), func1(a) from MyTable]]>
+ </Resource>
+ <Resource name="ast">
+ <![CDATA[
+LogicalProject(EXPR$0=[func1($0)], EXPR$1=[func1($0)])
++- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]])
+]]>
+ </Resource>
+ <Resource name="optimized rel plan">
+ <![CDATA[
+AsyncCalc(select=[f0 AS EXPR$0, func1(a) AS EXPR$1])
++- AsyncCalc(select=[a, func1(a) AS f0])
+ +- LegacyTableSourceScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]], fields=[a, b, c, d])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testNestedCalls">
+ <Resource name="sql">
+ <![CDATA[SELECT func1(func1(func1(a))) from MyTable]]>
+ </Resource>
+ <Resource name="ast">
+ <![CDATA[
+LogicalProject(EXPR$0=[func1(func1(func1($0)))])
++- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]])
+]]>
+ </Resource>
+ <Resource name="optimized rel plan">
+ <![CDATA[
+AsyncCalc(select=[func1(f0) AS EXPR$0])
++- AsyncCalc(select=[func1(f0) AS f0])
+ +- AsyncCalc(select=[func1(a) AS f0])
+ +- LegacyTableSourceScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c, d)]]], fields=[a, b, c, d])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testThreeNestedCalls">
+ <Resource name="sql">
+ <![CDATA[SELECT func1(func1(a)), func1(func1(func1(a))), func1(a) from MyTable]]>
Review Comment:
Added that test
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/RemoteCalcSplitRule.scala:
##########
@@ -0,0 +1,509 @@
+/*
+ * 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.functions.ScalarFunction
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc
+import org.apache.flink.table.planner.plan.utils.{InputRefVisitor, RexDefaultVisitor}
+
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
+import org.apache.calcite.plan.RelOptRule.{any, operand}
+import org.apache.calcite.rex.{RexBuilder, RexCall, RexCorrelVariable, RexFieldAccess, RexInputRef, RexLocalRef, RexNode, RexProgram}
+import org.apache.calcite.sql.validate.SqlValidatorUtil
+
+import java.util.function.Function
+
+import scala.collection.JavaConversions._
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+/**
+ * Base rule that splits [[FlinkLogicalCalc]] into multiple [[FlinkLogicalCalc]]s. It is mainly to
+ * ensure that each [[FlinkLogicalCalc]] only contains Java/Scala [[ScalarFunction]]s or Python
Review Comment:
Done
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.functions;
+
+import org.apache.flink.annotation.Experimental;
+import org.apache.flink.table.catalog.DataTypeFactory;
+import org.apache.flink.table.types.extraction.TypeInferenceExtractor;
+import org.apache.flink.table.types.inference.TypeInference;
+
+/**
+ * Base class for a user-defined scalar function which returns results asynchronously. A
+ * user-defined scalar function maps zero, one, or multiple scalar values to a new scalar value.
+ *
+ * <p>The behavior of a {@link AsyncScalarFunction} can be defined by implementing a custom
+ * evaluation method. An evaluation method must be declared publicly and named <code>eval</code>.
+ * Evaluation methods can also be overloaded by implementing multiple methods named <code>eval
+ * </code>. The first argument of the method must be a {@link
+ * java.util.concurrent.CompletableFuture} of the return type. The method body must complete the
+ * future either if there is a result or if it completes exceptionally.
+ *
+ * <p>By default, input and output data types are automatically extracted using reflection. If the
+ * reflective information is not sufficient, it can be supported and enriched with {@link
+ * org.apache.flink.table.annotation.DataTypeHint} and {@link
+ * org.apache.flink.table.annotation.FunctionHint} annotations.
+ *
+ * <p>The following examples show how to specify an async scalar function:
+ *
+ * <pre>{@code
+ * // a function that accepts two INT arguments and computes a sum
+ * class SumFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<Integer> future, Integer a, Integer b) {
+ * return future.complete(a + b);
+ * }
+ * }
+ *
+ * // a function that accepts either INT NOT NULL or BOOLEAN NOT NULL and computes a STRING
+ * class StringifyFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<String> future, int i) {
+ * return future.complete(String.valueOf(i));
+ * }
+ * public void eval(CompletableFuture<String> future, boolean b) {
+ * return future.complete(String.valueOf(b));
+ * }
+ * }
+ *
+ * // a function that accepts either INT or BOOLEAN and computes a STRING using function hints
+ * @FunctionHint(input = [@DataTypeHint("INT")])
+ * @FunctionHint(input = [@DataTypeHint("BOOLEAN")])
+ * class StringifyFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<String> future, Object o) {
+ * return future.complete(o.toString());
+ * }
+ * }
+ *
+ * // a function that accepts any data type as argument and computes a STRING
+ * class StringifyFunction extends AsyncScalarFunction {
+ * public void eval(CompletableFuture<String> future,
+ * @DataTypeHint(inputGroup = InputGroup.ANY) Object o) {
+ * return future.complete(o.toString());
+ * }
+ * }
+ *
+ * // a function that accepts an arbitrary number of BIGINT values and computes a DECIMAL(10, 4)
+ * class SumFunction extends AsyncScalarFunction {
+ * public void eval(@DataTypeHint("DECIMAL(10, 4)") CompletableFuture<BigDecimal> future,
+ * Long... values) {
+ * // ...
+ * }
+ * }
+ * }</pre>
+ *
+ * <p>For storing a user-defined function in a catalog, the class must have a default constructor
+ * and must be instantiable during runtime. Anonymous functions in Table API can only be persisted
+ * if the function is not stateful (i.e. containing only transient and static fields).
+ */
+@Experimental
Review Comment:
I trust! I was going to ask about when each annotation should be used. Happy to use @PublicEvolving
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/codegen/AsyncCodeGeneratorTest.java:
##########
@@ -0,0 +1,228 @@
+/*
+ * 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.codegen;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.streaming.api.functions.async.ResultFuture;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.catalog.UnresolvedIdentifier;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.planner.calcite.FlinkContext;
+import org.apache.flink.table.planner.calcite.SqlToRexConverter;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+import org.apache.flink.table.planner.utils.PlannerMocks;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.types.logical.BigIntType;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.IntType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.TimestampType;
+import org.apache.flink.table.types.logical.VarCharType;
+import org.apache.flink.table.utils.CatalogManagerMocks;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Test for {@link AsyncCodeGenerator}. */
+public class AsyncCodeGeneratorTest {
+
+ private static final RowType INPUT_TYPE =
+ RowType.of(new IntType(), new BigIntType(), new VarCharType());
+
+ private PlannerMocks plannerMocks;
+ private SqlToRexConverter converter;
+
+ private RelDataType tableRowType;
+
+ @BeforeEach
+ public void before() {
+ plannerMocks = PlannerMocks.create();
+ tableRowType =
+ plannerMocks
+ .getPlannerContext()
+ .getTypeFactory()
+ .buildRelNodeRowType(
+ JavaScalaConversionUtil.toScala(ImmutableList.of("f1", "f2", "f3")),
+ JavaScalaConversionUtil.toScala(
+ ImmutableList.of(
+ new IntType(),
+ new BigIntType(),
+ new VarCharType())));
+ converter =
+ plannerMocks
+ .getPlanner()
+ .createToRelContext()
+ .getCluster()
+ .getPlanner()
+ .getContext()
+ .unwrap(FlinkContext.class)
+ .getRexFactory()
+ .createSqlToRexConverter(tableRowType, null);
+
+ plannerMocks
+ .getFunctionCatalog()
+ .registerTemporaryCatalogFunction(
Review Comment:
Done
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/logical/PythonCalcSplitRule.scala:
##########
@@ -293,222 +65,39 @@ object PythonCalcSplitPandasInProjectionRule
}
}
-/**
- * Rule that expands the RexFieldAccess inputs of Python functions contained in the projection of
- * [[FlinkLogicalCalc]]s.
- */
-object PythonCalcExpandProjectRule extends PythonCalcSplitRuleBase("PythonCalcExpandProjectRule") {
-
- override def matches(call: RelOptRuleCall): Boolean = {
- val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc]
- val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef)
-
- projects.exists(containsPythonCall(_)) && projects.exists(containsFieldAccessInputs)
+class PythonRemoteCalcCallFinder extends RemoteCalcCallFinder {
+ override def containsRemoteCall(node: RexNode): Boolean = {
+ PythonUtil.containsPythonCall(node)
}
- override def needConvert(program: RexProgram, node: RexNode): Boolean =
- node.isInstanceOf[RexFieldAccess]
-
- override def split(
- program: RexProgram,
- splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) = {
- (
- Option(program.getCondition).map(program.expandLocalRef),
- None,
- program.getProjectList.map(program.expandLocalRef(_).accept(splitter)))
- }
-
- private def containsFieldAccessInputs(node: RexNode): Boolean = {
- node match {
- case call: RexCall => call.getOperands.exists(containsFieldAccessInputs)
- case _: RexFieldAccess => true
- case _ => false
- }
+ override def containsNonRemoteCall(node: RexNode): Boolean = {
+ PythonUtil.containsNonPythonCall(node)
}
-}
-
-/**
- * Rule that pushes the condition of [[FlinkLogicalCalc]]s before it for the [[FlinkLogicalCalc]]s
- * which contain Python functions in the projection.
- */
-object PythonCalcPushConditionRule extends PythonCalcSplitRuleBase("PythonCalcPushConditionRule") {
-
- override def matches(call: RelOptRuleCall): Boolean = {
- val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc]
- val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef)
- // matches if all the following conditions hold true:
- // 1) the condition is not null
- // 2) it contains Python functions in the projection
- calc.getProgram.getCondition != null && projects.exists(containsPythonCall(_))
+ override def isRemoteCall(node: RexNode): Boolean = {
+ PythonUtil.isPythonCall(node)
}
- override def needConvert(program: RexProgram, node: RexNode): Boolean = isNonPythonCall(node)
-
- override def split(
- program: RexProgram,
- splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) = {
- (
- Option(program.getCondition).map(program.expandLocalRef),
- None,
- program.getProjectList.map(program.expandLocalRef))
+ override def isNonRemoteCall(node: RexNode): Boolean = {
+ PythonUtil.isNonPythonCall(node)
}
}
-/**
- * Rule that ensures that it only contains [[RexInputRef]]s at the beginning of the project list and
- * [[RexCall]]s at the end of the project list for [[FlinkLogicalCalc]]s which contain Python
- * functions in the projection. This rule exists to keep DataStreamPythonCalc as simple as possible
- * and ensures that it only needs to handle the Python function execution.
- */
-object PythonCalcRewriteProjectionRule
- extends PythonCalcSplitRuleBase("PythonCalcRewriteProjectionRule") {
-
- override def matches(call: RelOptRuleCall): Boolean = {
- val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc]
- val projects = calc.getProgram.getProjectList.map(calc.getProgram.expandLocalRef)
-
- // matches if all the following conditions hold true:
- // 1) it contains Python functions in the projection
- // 2) it contains RexNodes besides RexInputRef and RexCall or
- // not all the RexCalls lying at the end of the project list
- projects.exists(containsPythonCall(_)) &&
- (projects.exists(expr => !expr.isInstanceOf[RexCall] && !expr.isInstanceOf[RexInputRef]) ||
- projects.indexWhere(_.isInstanceOf[RexCall]) <
- projects.lastIndexWhere(_.isInstanceOf[RexInputRef]))
- }
-
- override def needConvert(program: RexProgram, node: RexNode): Boolean = isPythonCall(node)
-
- override def split(
- program: RexProgram,
- splitter: ScalarFunctionSplitter): (Option[RexNode], Option[RexNode], Seq[RexNode]) = {
- (None, None, program.getProjectList.map(program.expandLocalRef(_).accept(splitter)))
- }
-}
-
-private class ScalarFunctionSplitter(
- program: RexProgram,
- rexBuilder: RexBuilder,
- extractedFunctionOffset: Int,
- extractedRexNodes: mutable.ArrayBuffer[RexNode],
- needConvert: Function[RexNode, Boolean])
- extends RexDefaultVisitor[RexNode] {
-
- private var fieldsRexCall: Map[Int, Int] = Map[Int, Int]()
-
- override def visitCall(call: RexCall): RexNode = {
- if (needConvert(call)) {
- getExtractedRexNode(call)
- } else {
- call.clone(call.getType, call.getOperands.asScala.map(_.accept(this)))
- }
- }
-
- override def visitFieldAccess(fieldAccess: RexFieldAccess): RexNode = {
- if (needConvert(fieldAccess)) {
- val expr = fieldAccess.getReferenceExpr
- expr match {
- case localRef: RexLocalRef if containsPythonCall(program.expandLocalRef(localRef)) =>
- getExtractedRexFieldAccess(fieldAccess, localRef.getIndex)
- case _: RexCorrelVariable =>
- val field = fieldAccess.getField
- new RexInputRef(field.getIndex, field.getType)
- case _ =>
- val newFieldAccess =
- rexBuilder.makeFieldAccess(expr.accept(this), fieldAccess.getField.getIndex)
- getExtractedRexNode(newFieldAccess)
- }
- } else {
- fieldAccess
- }
- }
-
- override def visitLocalRef(localRef: RexLocalRef): RexNode = {
- program.getExprList.get(localRef.getIndex).accept(this)
- }
-
- override def visitNode(rexNode: RexNode): RexNode = rexNode
-
- private def getExtractedRexNode(node: RexNode): RexNode = {
- val newNode = new RexInputRef(extractedFunctionOffset + extractedRexNodes.length, node.getType)
- extractedRexNodes.append(node)
- newNode
- }
-
- private def getExtractedRexFieldAccess(node: RexFieldAccess, rexCallIndex: Int): RexNode = {
- val pythonCall: RexCall =
- program.expandLocalRef(node.getReferenceExpr.asInstanceOf[RexLocalRef]).asInstanceOf[RexCall]
- if (!fieldsRexCall.contains(rexCallIndex)) {
- extractedRexNodes.append(pythonCall)
- fieldsRexCall += rexCallIndex -> (extractedFunctionOffset + extractedRexNodes.length - 1)
- }
- rexBuilder.makeFieldAccess(
- new RexInputRef(fieldsRexCall(rexCallIndex), pythonCall.getType),
- node.getField.getIndex)
- }
-}
-
-/**
- * Rewrite field accesses of a RexNode as not all the fields from the original input are forwarded:
- * 1) Fields of index greater than or equal to extractedFunctionOffset refer to the extracted
- * function. 2) Fields of index less than extractedFunctionOffset refer to the original input field.
- *
- * @param rexBuilder
- * the RexBuilder
- * @param extractedFunctionOffset
- * the original start offset of the extracted functions
- * @param accessedFields
- * the accessed fields which will be forwarded
- */
-private class ExtractedFunctionInputRewriter(
- rexBuilder: RexBuilder,
- extractedFunctionOffset: Int,
- accessedFields: Array[Int])
- extends RexDefaultVisitor[RexNode] {
-
- /** old input fields ref index -> new input fields ref index mappings */
- private val fieldMap: Map[Int, Int] = accessedFields.zipWithIndex.toMap
-
- override def visitInputRef(inputRef: RexInputRef): RexNode = {
- if (inputRef.getIndex >= extractedFunctionOffset) {
- new RexInputRef(
- inputRef.getIndex - extractedFunctionOffset + accessedFields.length,
- inputRef.getType)
- } else {
- new RexInputRef(
- fieldMap.getOrElse(
- inputRef.getIndex,
- throw new IllegalArgumentException("input field contains invalid index")),
- inputRef.getType)
- }
- }
-
- override def visitCall(call: RexCall): RexNode = {
- call.clone(call.getType, call.getOperands.asScala.map(_.accept(this)))
- }
-
- override def visitFieldAccess(fieldAccess: RexFieldAccess): RexNode = {
- rexBuilder.makeFieldAccess(
- fieldAccess.getReferenceExpr.accept(this),
- fieldAccess.getField.getIndex)
- }
-
- override def visitNode(rexNode: RexNode): RexNode = rexNode
-}
-
object PythonCalcSplitRule {
/**
* These rules should be applied sequentially in the order of SPLIT_CONDITION, SPLIT_PROJECT,
* SPLIT_PANDAS_IN_PROJECT, EXPAND_PROJECT, PUSH_CONDITION and REWRITE_PROJECT.
*/
- val SPLIT_CONDITION: RelOptRule = PythonCalcSplitConditionRule
- val SPLIT_PROJECT: RelOptRule = PythonCalcSplitProjectionRule
- val SPLIT_PANDAS_IN_PROJECT: RelOptRule = PythonCalcSplitPandasInProjectionRule
- val SPLIT_PROJECTION_REX_FIELD: RelOptRule = PythonCalcSplitProjectionRexFieldRule
- val SPLIT_CONDITION_REX_FIELD: RelOptRule = PythonCalcSplitConditionRexFieldRule
- val EXPAND_PROJECT: RelOptRule = PythonCalcExpandProjectRule
- val PUSH_CONDITION: RelOptRule = PythonCalcPushConditionRule
- val REWRITE_PROJECT: RelOptRule = PythonCalcRewriteProjectionRule
+ private val callFinder = new PythonRemoteCalcCallFinder()
+ val SPLIT_CONDITION: RelOptRule = new RemoteCalcSplitConditionRule(callFinder) {}
Review Comment:
It appears that the rules are considered equal by their class type, not the instance. I hunted this down to be defined in `RelOptRule`. I had added the "{}" to make it an anonymous class definition, so it could exist alongside the async rules, but now that I found the source of the behavior, I overrode equals for `RemoteCalcSplitRuleBase` to also consider the class of the call finder.
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/table/AsyncCalcITCase.java:
##########
@@ -0,0 +1,561 @@
+/*
+ * 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.runtime.stream.table;
+
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.api.EnvironmentSettings;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.TableEnvironment;
+import org.apache.flink.table.api.TableResult;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.config.ExecutionConfigOptions;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionContext;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** IT Case tests for {@link AsyncScalarFunction}. */
+public class AsyncCalcITCase extends AbstractTestBase {
+
+ private StreamExecutionEnvironment env;
+
+ private TableEnvironment tEnv;
+
+ @BeforeEach
+ public void before() throws Exception {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.setParallelism(1);
+ env.setMaxParallelism(1);
+ tEnv = StreamTableEnvironment.create(env, EnvironmentSettings.inStreamingMode());
+ tEnv.getConfig().set(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_DEFAULT_PARALLELISM, 1);
+ tEnv.getConfig().set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY, 1);
+ tEnv.getConfig()
+ .set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_TIMEOUT, Duration.ofMinutes(1));
+ }
+
+ @Test
+ public void testSimpleTableSelect() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of("val 1"), Row.of("val 2"), Row.of("val 3"));
Review Comment:
Done
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/table/AsyncCalcITCase.java:
##########
@@ -0,0 +1,561 @@
+/*
+ * 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.runtime.stream.table;
+
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.api.EnvironmentSettings;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.TableEnvironment;
+import org.apache.flink.table.api.TableResult;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.config.ExecutionConfigOptions;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionContext;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** IT Case tests for {@link AsyncScalarFunction}. */
+public class AsyncCalcITCase extends AbstractTestBase {
+
+ private StreamExecutionEnvironment env;
+
+ private TableEnvironment tEnv;
+
+ @BeforeEach
+ public void before() throws Exception {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.setParallelism(1);
Review Comment:
Yes, I upped it to 2. I think I had originally added a test (left join?) which would be more likely to issue `+I` followed by `-D` rows if parallelism were higher, since I believe the way I was issuing them in streaming mode, there was a race about whether the right table would have materialized yet at processing time. Not sure what's the best way to write tests for these kinds of cases (is there a utility to wait until everything is materialized?).
Anyway, it's a moot point since I've deleted all of these non-deterministic cases.
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/codegen/AsyncCodeGeneratorTest.java:
##########
@@ -0,0 +1,228 @@
+/*
+ * 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.codegen;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.streaming.api.functions.async.ResultFuture;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.catalog.UnresolvedIdentifier;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.planner.calcite.FlinkContext;
+import org.apache.flink.table.planner.calcite.SqlToRexConverter;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+import org.apache.flink.table.planner.utils.PlannerMocks;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.types.logical.BigIntType;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.IntType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.TimestampType;
+import org.apache.flink.table.types.logical.VarCharType;
+import org.apache.flink.table.utils.CatalogManagerMocks;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Test for {@link AsyncCodeGenerator}. */
+public class AsyncCodeGeneratorTest {
+
+ private static final RowType INPUT_TYPE =
+ RowType.of(new IntType(), new BigIntType(), new VarCharType());
+
+ private PlannerMocks plannerMocks;
+ private SqlToRexConverter converter;
+
+ private RelDataType tableRowType;
+
+ @BeforeEach
+ public void before() {
+ plannerMocks = PlannerMocks.create();
+ tableRowType =
+ plannerMocks
+ .getPlannerContext()
+ .getTypeFactory()
+ .buildRelNodeRowType(
+ JavaScalaConversionUtil.toScala(ImmutableList.of("f1", "f2", "f3")),
+ JavaScalaConversionUtil.toScala(
+ ImmutableList.of(
+ new IntType(),
+ new BigIntType(),
+ new VarCharType())));
+ converter =
+ plannerMocks
+ .getPlanner()
+ .createToRelContext()
+ .getCluster()
+ .getPlanner()
+ .getContext()
+ .unwrap(FlinkContext.class)
+ .getRexFactory()
+ .createSqlToRexConverter(tableRowType, null);
+
+ plannerMocks
+ .getFunctionCatalog()
+ .registerTemporaryCatalogFunction(
+ UnresolvedIdentifier.of(
+ CatalogManagerMocks.DEFAULT_CATALOG,
+ CatalogManagerMocks.DEFAULT_DATABASE,
+ "myFunc"),
+ new AsyncFunc(),
+ false);
+ }
+
+ @Test
+ public void testStringReturnType() throws Exception {
+ RowData rowData =
+ execute(
+ "myFunc(f1, f2, f3)",
+ RowType.of(new VarCharType()),
+ GenericRowData.of(2, 3L, StringData.fromString("foo")));
+ assertThat(rowData).isEqualTo(GenericRowData.of(StringData.fromString("complete foo 4 6")));
+ }
+
+ @Test
+ public void testTimestampReturnType() throws Exception {
Review Comment:
Ok, removed extra tests.
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/DelegatingAsyncResultFuture.java:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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.runtime.operators.calc.async;
+
+import org.apache.flink.streaming.api.functions.async.ResultFuture;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.conversion.DataStructureConverter;
+import org.apache.flink.util.Preconditions;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+
+/**
+ * Inspired by {@link org.apache.flink.table.runtime.operators.join.lookup.DelegatingResultFuture}
+ * for {@link org.apache.flink.table.functions.AsyncScalarFunction}.
+ */
+public class DelegatingAsyncResultFuture implements BiConsumer<Object, Throwable> {
+
+ private final ResultFuture<Object> delegatedResultFuture;
+ private final List<Object> synchronousResults = new ArrayList<>();
+ private Function<Object, RowData> outputFactory;
+ private CompletableFuture<Object> future;
+ private CompletableFuture<Object> convertedFuture;
+
+ public DelegatingAsyncResultFuture(ResultFuture<Object> delegatedResultFuture) {
+ this.delegatedResultFuture = delegatedResultFuture;
+ }
+
+ public synchronized void addSynchronousResult(Object object) {
+ synchronousResults.add(object);
+ }
+
+ public synchronized Object getSynchronousResult(int index) {
+ return synchronousResults.get(index);
+ }
+
+ public synchronized void setOutputFactory(Function<Object, RowData> outputFactory) {
Review Comment:
I think you're right. The way it's used is that everything is set up and then `createAsyncFuture` is called which gets passed to the UDF. Then another thread calls back `accept`. When there's an initialization phase in one thread (after which everything is immutable) followed by this sort of async callback, it's usually fine (per the java memory-model [happens before relationship](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility) ). I had originally had multiple futures handled in this class, which complicated that since I had to contend with registering new futures while potentially getting callbacks at the same time. I'll remove the synchronization now, but might need to this a little differently when we handle multiple concurrent futures.
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/codegen/AsyncCodeGeneratorTest.java:
##########
@@ -0,0 +1,228 @@
+/*
+ * 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.codegen;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.streaming.api.functions.async.ResultFuture;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.catalog.UnresolvedIdentifier;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.planner.calcite.FlinkContext;
+import org.apache.flink.table.planner.calcite.SqlToRexConverter;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+import org.apache.flink.table.planner.utils.PlannerMocks;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.types.logical.BigIntType;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.IntType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.TimestampType;
+import org.apache.flink.table.types.logical.VarCharType;
+import org.apache.flink.table.utils.CatalogManagerMocks;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigDecimal;
+import java.time.Instant;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Test for {@link AsyncCodeGenerator}. */
+public class AsyncCodeGeneratorTest {
+
+ private static final RowType INPUT_TYPE =
+ RowType.of(new IntType(), new BigIntType(), new VarCharType());
+
+ private PlannerMocks plannerMocks;
+ private SqlToRexConverter converter;
+
+ private RelDataType tableRowType;
+
+ @BeforeEach
+ public void before() {
+ plannerMocks = PlannerMocks.create();
+ tableRowType =
+ plannerMocks
+ .getPlannerContext()
+ .getTypeFactory()
+ .buildRelNodeRowType(
+ JavaScalaConversionUtil.toScala(ImmutableList.of("f1", "f2", "f3")),
+ JavaScalaConversionUtil.toScala(
+ ImmutableList.of(
+ new IntType(),
+ new BigIntType(),
+ new VarCharType())));
+ converter =
+ plannerMocks
+ .getPlanner()
+ .createToRelContext()
+ .getCluster()
+ .getPlanner()
+ .getContext()
+ .unwrap(FlinkContext.class)
+ .getRexFactory()
+ .createSqlToRexConverter(tableRowType, null);
+
+ plannerMocks
+ .getFunctionCatalog()
+ .registerTemporaryCatalogFunction(
+ UnresolvedIdentifier.of(
+ CatalogManagerMocks.DEFAULT_CATALOG,
+ CatalogManagerMocks.DEFAULT_DATABASE,
+ "myFunc"),
+ new AsyncFunc(),
+ false);
+ }
+
+ @Test
+ public void testStringReturnType() throws Exception {
+ RowData rowData =
+ execute(
+ "myFunc(f1, f2, f3)",
+ RowType.of(new VarCharType()),
+ GenericRowData.of(2, 3L, StringData.fromString("foo")));
+ assertThat(rowData).isEqualTo(GenericRowData.of(StringData.fromString("complete foo 4 6")));
+ }
+
+ @Test
+ public void testTimestampReturnType() throws Exception {
+ RowData rowData =
+ execute(
+ "myFunc(f2)",
+ RowType.of(new TimestampType()),
+ GenericRowData.of(2, 3L, StringData.fromString("foo")));
+ assertThat(rowData).isEqualTo(GenericRowData.of(TimestampData.fromEpochMillis(3)));
+ }
+
+ @Test
+ public void testDecimalReturnType() throws Exception {
+ RowData rowData =
+ execute(
+ "myFunc(f1)",
+ RowType.of(new DecimalType()),
+ GenericRowData.of(2, 3L, StringData.fromString("foo")));
+ assertThat(rowData)
+ .isEqualTo(
+ GenericRowData.of(
+ DecimalData.fromBigDecimal(BigDecimal.valueOf(1024), 12, 3)));
+ }
+
+ @Test
+ public void testTwoReturnTypes_passThroughFirst() throws Exception {
+ RowData rowData =
+ execute(
+ ImmutableList.of("f2", "myFunc(f1, f2, f3)"),
+ RowType.of(new VarCharType(), new BigIntType()),
+ GenericRowData.of(2, 3L, StringData.fromString("foo")));
+ assertThat(rowData)
+ .isEqualTo(GenericRowData.of(3L, StringData.fromString("complete foo 4 6")));
+ }
+
+ @Test
+ public void testTwoReturnTypes_passThroughSecond() throws Exception {
+ RowData rowData =
+ execute(
+ ImmutableList.of("myFunc(f1, f2, f3)", "f2"),
+ RowType.of(new VarCharType(), new BigIntType()),
+ GenericRowData.of(2, 3L, StringData.fromString("foo")));
+ assertThat(rowData)
+ .isEqualTo(GenericRowData.of(StringData.fromString("complete foo 4 6"), 3L));
+ }
+
+ private RowData execute(String sqlExpression, RowType resultType, RowData input)
+ throws Exception {
+ return execute(ImmutableList.of(sqlExpression), resultType, input);
+ }
+
+ private RowData execute(List<String> sqlExpressions, RowType resultType, RowData input)
+ throws Exception {
+ List<RexNode> nodes =
+ sqlExpressions.stream()
+ .map(sql -> converter.convertToRexNode(sql))
+ .collect(Collectors.toList());
+ GeneratedFunction<AsyncFunction<RowData, RowData>> function =
+ AsyncCodeGenerator.generateFunction(
+ "name",
+ INPUT_TYPE,
+ resultType,
+ GenericRowData.class,
+ nodes,
+ true,
+ new Configuration(),
+ Thread.currentThread().getContextClassLoader());
+ AsyncFunction<RowData, RowData> asyncFunction =
+ function.newInstance(Thread.currentThread().getContextClassLoader());
+ TestResultFuture resultFuture = new TestResultFuture();
+ asyncFunction.asyncInvoke(input, resultFuture);
+ Collection<RowData> result = resultFuture.getResult().get();
+ assertThat(result).hasSize(1);
+ return result.iterator().next();
+ }
+
+ /** Test function. */
+ public static final class AsyncFunc extends AsyncScalarFunction {
+ public void eval(CompletableFuture<String> f, Integer i, Long l, String s) {
+ f.complete("complete " + s + " " + (i * i) + " " + (2 * l));
+ }
+
+ public void eval(CompletableFuture<Instant> f, Long l) {
+ f.complete(Instant.ofEpochMilli(l));
+ }
+
+ public void eval(
+ @DataTypeHint("DECIMAL(12, 3)") CompletableFuture<BigDecimal> f, Integer i) {
+ f.complete(BigDecimal.valueOf(i).pow(10));
+ }
+ }
+
+ /** Test result future. */
+ public static final class TestResultFuture implements ResultFuture<RowData> {
+
+ CompletableFuture<Collection<RowData>> data = new CompletableFuture<>();
+
+ @Override
+ public void complete(Collection<RowData> result) {
+ data.complete(result);
+ }
+
+ @Override
+ public void completeExceptionally(Throwable error) {
Review Comment:
Nope, but good call. Added.
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/table/AsyncCalcITCase.java:
##########
@@ -0,0 +1,561 @@
+/*
+ * 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.runtime.stream.table;
+
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.api.EnvironmentSettings;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.TableEnvironment;
+import org.apache.flink.table.api.TableResult;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.config.ExecutionConfigOptions;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionContext;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** IT Case tests for {@link AsyncScalarFunction}. */
+public class AsyncCalcITCase extends AbstractTestBase {
+
+ private StreamExecutionEnvironment env;
+
+ private TableEnvironment tEnv;
+
+ @BeforeEach
+ public void before() throws Exception {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.setParallelism(1);
+ env.setMaxParallelism(1);
+ tEnv = StreamTableEnvironment.create(env, EnvironmentSettings.inStreamingMode());
+ tEnv.getConfig().set(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_DEFAULT_PARALLELISM, 1);
+ tEnv.getConfig().set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY, 1);
+ tEnv.getConfig()
+ .set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_TIMEOUT, Duration.ofMinutes(1));
+ }
+
+ @Test
+ public void testSimpleTableSelect() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of("val 1"), Row.of("val 2"), Row.of("val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testLiteralPlusTableSelect() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select 'foo', func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(
+ Row.of("foo", "val 1"), Row.of("foo", "val 2"), Row.of("foo", "val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testFieldPlusTableSelect() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select f1, func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of(1, "val 1"), Row.of(2, "val 2"), Row.of(3, "val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testTwoCalls() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(f1), func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(
+ Row.of("val 1", "val 1"),
+ Row.of("val 2", "val 2"),
+ Row.of("val 3", "val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testNestedCalls() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFuncAdd10());
+ final List<Row> results = executeSql("select func(func(func(f1))) from t1");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(31), Row.of(32), Row.of(33));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testThreeNestedCalls() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFuncAdd10());
+ final List<Row> results =
+ executeSql("select func(func(f1)), func(func(func(f1))), func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of(21, 31, 11), Row.of(22, 32, 12), Row.of(23, 33, 13));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testPassedToOtherUDF() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select Concat(func(f1), 'foo') from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of("val 1foo"), Row.of("val 2foo"), Row.of("val 3foo"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testJustCall() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(1)");
+ final List<Row> expectedRows = ImmutableList.of(Row.of("val 1"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testWhereCondition() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql("select f1 from t1 where REGEXP(func(f1), 'val (2|3)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2), Row.of(3));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testWhereConditionAndProjection() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql("select func(f1) from t1 where REGEXP(func(f1), 'val (2|3)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of("val 2"), Row.of("val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testWhereConditionWithInts() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFuncAdd10());
+ final List<Row> results = executeSql("select f1 from t1 where func(f1) >= 12");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2), Row.of(3));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testAggregate() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 1, 3, 4).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFuncAdd10Long());
+ final List<Row> results = executeSql("select f1, func(count(*)) from t1 group by f1");
+ final List<Row> expectedRows =
+ ImmutableList.of(
+ Row.of(1, 11L),
+ Row.of(2, 11L),
+ Row.of(3, 11L),
+ Row.ofKind(RowKind.UPDATE_BEFORE, 1, 11L),
+ Row.ofKind(RowKind.UPDATE_AFTER, 1, 12L),
+ Row.ofKind(RowKind.UPDATE_BEFORE, 3, 11L),
+ Row.ofKind(RowKind.UPDATE_AFTER, 3, 12L),
+ Row.of(4, 11L));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testSelectCallWithIntArray() {
+ Table t1 = tEnv.fromValues(new int[] {1, 2}, new int[] {3, 4}).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFuncAdd10IntArray());
+ final List<Row> results = executeSql("select func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(
+ Row.of(new Object[] {new Integer[] {11, 12}}),
+ Row.of(new Object[] {new Integer[] {13, 14}}));
+ // When run here, the plan is a union of the two AsyncCalcs so order is
+ // not retained!
+ assertThat(results).containsExactlyInAnyOrderElementsOf(expectedRows);
+ }
+
+ @Test
+ public void testInnerJoinWithFuncInOn() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql(
+ "select f1 from t1 INNER JOIN t2 ON func(f1) = func(f2) AND REGEXP(func(f1), 'val (2|4)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2), Row.of(4));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testInnerJoinWithFuncProjection() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(f1) from t1 INNER JOIN t2 ON f1 = f2");
+ final List<Row> expectedRows = ImmutableList.of(Row.of("val 2"), Row.of("val 4"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testInnerJoinWithFuncInWhere() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql(
+ "select f1 from t1 INNER JOIN t2 ON f1 = f2 WHERE REGEXP(func(f1), 'val (2|3)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testLeftJoinWithFuncInOn() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql("select f1, f2 from t1 LEFT JOIN t2 ON func(f1) = func(f2)");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of(1, null), Row.of(2, 2), Row.of(3, null), Row.of(4, 4));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testLeftJoinWithFuncInWhere() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql(
+ "select f1, f2 from t1 LEFT JOIN t2 ON f1 = f2 WHERE REGEXP(func(f1), 'val (2|3)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2, 2), Row.of(3, null));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testRightJoinWithFuncInOn() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql("select f1, f2 from t1 FULL OUTER JOIN t2 ON func(f1) = func(f2)");
+ assertThat(results).hasSize(8);
+ }
+
+ @Test
+ public void testSelectWithConfigs() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.getConfig()
+ .set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY.key(), "10");
+ tEnv.getConfig().set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_TIMEOUT.key(), "1m");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of("val 1"), Row.of("val 2"), Row.of("val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testProjectCallInSubquery() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql(
+ "select blah FROM (select func(f1) as blah from t1) "
+ + "WHERE REGEXP(blah, 'val (2|3)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of("val 2"), Row.of("val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testWhereConditionCallInSubquery() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql(
+ "select blah FROM (select f1 as blah from t1 "
+ + "WHERE REGEXP(func(f1), 'val (2|3)'))");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2), Row.of(3));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testWhereNotInSubquery() {
Review Comment:
Ok, whittled it down to 13 tests that are not too redundant. Happy to go further, if you think some still are.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.codegen;
+
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.functions.FunctionKind;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitorImpl;
+import org.apache.commons.text.StringSubstitutor;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * Generates an {@link AsyncFunction} which can be used to evaluate calc projections from an async
+ * scalar function.
+ */
+public class AsyncCodeGenerator {
+
+ public static final String DEFAULT_EXCEPTION_TERM = "e";
+ public static final String DEFAULT_DELEGATING_FUTURE_TERM = "f";
+
+ /**
+ * Creates a generated function which produces an {@link AsyncFunction} which executes the calc
+ * projections.
+ *
+ * @param name The name used to generate the underlying function name
+ * @param inputType The RowType of the input RowData
+ * @param returnType The RowType of the resulting RowData
+ * @param outRowClass The class used to generate the output RowData
+ * @param retainHeader If the header of the row should be retained
+ * @param calcProjection The list of projections to be executed by this function
+ * @param tableConfig The table configuration
+ * @param classLoader The classloader to use while resolving classes
+ * @return A {@link GeneratedFunction} returning an {@link AsyncFunction} executing the given
+ * list of projections
+ */
+ public static GeneratedFunction<AsyncFunction<RowData, RowData>> generateFunction(
+ String name,
+ RowType inputType,
+ RowType returnType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> calcProjection,
+ boolean retainHeader,
+ ReadableConfig tableConfig,
+ ClassLoader classLoader) {
+ CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig, classLoader);
+ String processCode =
+ generateProcessCode(
+ ctx,
+ inputType,
+ returnType,
+ outRowClass,
+ calcProjection,
+ retainHeader,
+ CodeGenUtils.DEFAULT_INPUT1_TERM(),
+ CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
+ DEFAULT_EXCEPTION_TERM,
+ CodeGenUtils.DEFAULT_OUT_RECORD_TERM(),
+ DEFAULT_DELEGATING_FUTURE_TERM);
+ return FunctionCodeGenerator.generateFunction(
+ ctx,
+ name,
+ getFunctionClass(),
+ processCode,
+ returnType,
+ inputType,
+ CodeGenUtils.DEFAULT_INPUT1_TERM(),
+ JavaScalaConversionUtil.toScala(Optional.empty()),
+ JavaScalaConversionUtil.toScala(Optional.empty()),
+ CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
+ CodeGenUtils.DEFAULT_CONTEXT_TERM());
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Class<AsyncFunction<RowData, RowData>> getFunctionClass() {
+ return (Class<AsyncFunction<RowData, RowData>>) (Object) AsyncFunction.class;
+ }
+
+ private static String generateProcessCode(
+ CodeGeneratorContext ctx,
+ RowType inputType,
+ RowType outRowType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> projection,
+ boolean retainHeader,
+ String inputTerm,
+ String collectorTerm,
+ String errorTerm,
+ String recordTerm,
+ String delegatingFutureTerm) {
+
+ projection.forEach(n -> n.accept(new AsyncScalarFunctionsValidator()));
+
+ ExprCodeGenerator exprGenerator =
+ new ExprCodeGenerator(ctx, false)
+ .bindInput(
+ inputType,
+ inputTerm,
+ JavaScalaConversionUtil.toScala(Optional.empty()));
+
+ List<GeneratedExpression> projectionExprs =
+ projection.stream()
+ .map(exprGenerator::generateExpression)
+ .collect(Collectors.toList());
+ int syncIndex = 0;
+ int index = 0;
+ StringBuilder outputs = new StringBuilder();
+ StringBuilder syncInvocations = new StringBuilder();
+ StringBuilder asyncInvocation = new StringBuilder();
+ if (retainHeader) {
+ outputs.append(String.format("%s.setRowKind(rowKind);\n", recordTerm, inputTerm));
+ }
+ for (GeneratedExpression fieldExpr : projectionExprs) {
+ if (fieldExpr.resultTerm().isEmpty()) {
+ outputs.append(
+ String.format("%s.setField(%d, resultObject);\n", recordTerm, index));
+ asyncInvocation.append(fieldExpr.code());
+ } else {
+ outputs.append(
+ String.format(
+ "%s.setField(%d, %s.getSynchronousResult(%d));\n",
+ recordTerm, index, delegatingFutureTerm, syncIndex));
+ syncInvocations.append(fieldExpr.code());
+ syncInvocations.append(
+ String.format(
+ "%s.addSynchronousResult(%s);\n",
+ delegatingFutureTerm, fieldExpr.resultTerm()));
+ syncIndex++;
+ }
+ index++;
+ }
+
+ Map<String, String> values = new HashMap<>();
+ values.put("delegatingFuture", delegatingFutureTerm);
+ values.put("collectorTerm", collectorTerm);
+ values.put("typeTerm", outRowClass.getCanonicalName());
+ values.put("recordTerm", recordTerm);
+ values.put("inputTerm", inputTerm);
+ values.put("fieldCount", Integer.toString(LogicalTypeChecks.getFieldCount(outRowType)));
+ values.put("outputs", outputs.toString());
+ values.put("syncInvocations", syncInvocations.toString());
+ values.put("asyncInvocation", asyncInvocation.toString());
+ values.put("errorTerm", errorTerm);
+
+ return StringSubstitutor.replace(
+ String.join(
+ "\n",
+ new String[] {
+ "final org.apache.flink.table.runtime.operators.calc.async.DelegatingAsyncResultFuture ${delegatingFuture} ",
Review Comment:
Ok, sounds good.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/AsyncUtil.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.utils;
+
+import org.apache.flink.streaming.api.datastream.AsyncDataStream;
+import org.apache.flink.streaming.api.functions.async.AsyncRetryStrategy;
+import org.apache.flink.streaming.util.retryable.AsyncRetryStrategies;
+import org.apache.flink.table.api.config.ExecutionConfigOptions;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionDefinition;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.Collection;
+import java.util.Objects;
+import java.util.function.Predicate;
+
+/** Contains utilities for AsyncScalarFunctions. */
+public class AsyncUtil {
+
+ private static final EmptyResponseResultStrategy EMPTY_RESPONSE =
+ new EmptyResponseResultStrategy();
+ private static final Predicate<Throwable> ANY_EXCEPTION = new AnyExceptionStrategy();
+
+ /**
+ * Checks whether it contains the specified kind of async function call in the specified node.
+ *
+ * @param node the RexNode to check
+ * @return true if it contains an async function call in the specified node.
+ */
+ public static boolean containsAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(true, true));
+ }
+
+ /**
+ * Checks whether it contains non-async function call in the specified node.
+ *
+ * @param node the RexNode to check
+ * @return true if it contains a non-async function call in the specified node.
+ */
+ public static boolean containsNonAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(false, true));
+ }
+
+ /**
+ * Checks whether the specified node is the specified kind of async function call.
+ *
+ * @param node the RexNode to check
+ * @return true if the specified node is an async function call.
+ */
+ public static boolean isAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(true, false));
+ }
+
+ /**
+ * Checks whether the specified node is a non-async function call.
+ *
+ * @param node the RexNode to check
+ * @return true if the specified node is a non-async function call.
+ */
+ public static boolean isNonAsyncCall(RexNode node) {
+ return node.accept(new FunctionFinder(false, false));
+ }
+
+ /**
+ * Gets the options required to run the operator.
+ *
+ * @param config The config from which to fetch the options
+ * @return Extracted options
+ */
+ public static AsyncUtil.Options getAsyncOptions(ExecNodeConfig config) {
+ return new AsyncUtil.Options(
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY),
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_TIMEOUT).toMillis(),
+ AsyncDataStream.OutputMode.ORDERED,
+ getResultRetryStrategy(
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_RETRY_STRATEGY),
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_RETRY_DELAY),
+ config.get(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_MAX_ATTEMPTS)));
+ }
+
+ /** Options for configuring async behavior. */
+ public static class Options {
+
+ public final int asyncBufferCapacity;
+ public final long asyncTimeout;
+ public final AsyncDataStream.OutputMode asyncOutputMode;
+ public final AsyncRetryStrategy<RowData> asyncRetryStrategy;
+
+ @JsonCreator
+ public Options(
+ int asyncBufferCapacity,
+ long asyncTimeout,
+ AsyncDataStream.OutputMode asyncOutputMode,
+ AsyncRetryStrategy<RowData> asyncRetryStrategy) {
+ this.asyncBufferCapacity = asyncBufferCapacity;
+ this.asyncTimeout = asyncTimeout;
+ this.asyncOutputMode = asyncOutputMode;
+ this.asyncRetryStrategy = asyncRetryStrategy;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ Options that = (Options) o;
+ return asyncBufferCapacity == that.asyncBufferCapacity
+ && asyncTimeout == that.asyncTimeout
+ && asyncOutputMode == that.asyncOutputMode;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(asyncBufferCapacity, asyncTimeout, asyncOutputMode);
+ }
+
+ @Override
+ public String toString() {
+ return asyncOutputMode + ", " + asyncTimeout + "ms, " + asyncBufferCapacity;
+ }
+ }
+
+ private static AsyncRetryStrategy<RowData> getResultRetryStrategy(
+ ExecutionConfigOptions.RetryStrategy retryStrategy,
+ Duration retryDelay,
+ int retryMaxAttempts) {
+ // Only fixed delay is allowed at the moment, so just ignore the config.
+ return new AsyncRetryStrategies.FixedDelayRetryStrategyBuilder<RowData>(
+ retryMaxAttempts, retryDelay.toMillis())
+ .ifResult(EMPTY_RESPONSE)
+ .ifException(ANY_EXCEPTION)
+ .build();
+ // return NO_RETRY_STRATEGY;
+ }
+
+ private static class FunctionFinder extends RexDefaultVisitor<Boolean> {
+
+ private final boolean findAsyncCall;
+ private final boolean recursive;
+
+ public FunctionFinder(boolean findAsyncCall, boolean recursive) {
+ this.findAsyncCall = findAsyncCall;
+ this.recursive = recursive;
+ }
+
+ @Override
+ public Boolean visitNode(RexNode rexNode) {
+ return false;
+ }
+
+ private boolean isImmediateAsyncCall(RexCall call) {
+ if (!(call.getOperator() instanceof BridgingSqlFunction)) {
+ return false;
+ }
+ FunctionDefinition definition =
+ ((BridgingSqlFunction) call.getOperator()).getDefinition();
+ return AsyncScalarFunction.class.isAssignableFrom(definition.getClass());
+ }
+
+ @Override
+ public Boolean visitCall(RexCall call) {
+ boolean isImmediateAsyncCall = isImmediateAsyncCall(call);
+ return findAsyncCall == isImmediateAsyncCall
+ || (recursive
+ && call.getOperands().stream().anyMatch(node -> node.accept(this)));
+ }
+ }
+
+ private static class EmptyResponseResultStrategy
+ implements Predicate<Collection<RowData>>, Serializable {
+ private static final long serialVersionUID = 5065281655787318565L;
+
+ @Override
+ public boolean test(Collection<RowData> c) {
+ return null == c || c.isEmpty();
+ }
+ }
+
+ private static class AnyExceptionStrategy implements Predicate<Throwable>, Serializable {
Review Comment:
Yeah, good call. Moved to `flink-table-runtime` and package `org.apache.flink.table.runtime.operators.calc.async` which contains other runtime pieces.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRule.java:
##########
@@ -0,0 +1,194 @@
+/*
+ * 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.flink.table.planner.plan.utils.AsyncUtil;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+import scala.Option;
+import scala.Tuple3;
+import scala.collection.Seq;
+
+/**
+ * Defines split rules for async calc nodes. These largely exist to isolate and simplify the calls
+ * to the async function from other calc operations, so that the operator can handle just that
Review Comment:
I added examples for both of the rules in this file.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.codegen;
+
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.functions.FunctionKind;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitorImpl;
+import org.apache.commons.text.StringSubstitutor;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * Generates an {@link AsyncFunction} which can be used to evaluate calc projections from an async
+ * scalar function.
+ */
+public class AsyncCodeGenerator {
+
+ public static final String DEFAULT_EXCEPTION_TERM = "e";
+ public static final String DEFAULT_DELEGATING_FUTURE_TERM = "f";
+
+ /**
+ * Creates a generated function which produces an {@link AsyncFunction} which executes the calc
+ * projections.
+ *
+ * @param name The name used to generate the underlying function name
+ * @param inputType The RowType of the input RowData
+ * @param returnType The RowType of the resulting RowData
+ * @param outRowClass The class used to generate the output RowData
+ * @param retainHeader If the header of the row should be retained
+ * @param calcProjection The list of projections to be executed by this function
+ * @param tableConfig The table configuration
+ * @param classLoader The classloader to use while resolving classes
+ * @return A {@link GeneratedFunction} returning an {@link AsyncFunction} executing the given
+ * list of projections
+ */
+ public static GeneratedFunction<AsyncFunction<RowData, RowData>> generateFunction(
+ String name,
+ RowType inputType,
+ RowType returnType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> calcProjection,
+ boolean retainHeader,
+ ReadableConfig tableConfig,
+ ClassLoader classLoader) {
+ CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig, classLoader);
+ String processCode =
+ generateProcessCode(
+ ctx,
+ inputType,
+ returnType,
+ outRowClass,
+ calcProjection,
+ retainHeader,
+ CodeGenUtils.DEFAULT_INPUT1_TERM(),
+ CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
+ DEFAULT_EXCEPTION_TERM,
+ CodeGenUtils.DEFAULT_OUT_RECORD_TERM(),
+ DEFAULT_DELEGATING_FUTURE_TERM);
+ return FunctionCodeGenerator.generateFunction(
+ ctx,
+ name,
+ getFunctionClass(),
+ processCode,
+ returnType,
+ inputType,
+ CodeGenUtils.DEFAULT_INPUT1_TERM(),
+ JavaScalaConversionUtil.toScala(Optional.empty()),
+ JavaScalaConversionUtil.toScala(Optional.empty()),
+ CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
+ CodeGenUtils.DEFAULT_CONTEXT_TERM());
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Class<AsyncFunction<RowData, RowData>> getFunctionClass() {
+ return (Class<AsyncFunction<RowData, RowData>>) (Object) AsyncFunction.class;
+ }
+
+ private static String generateProcessCode(
+ CodeGeneratorContext ctx,
+ RowType inputType,
+ RowType outRowType,
+ Class<? extends RowData> outRowClass,
+ List<RexNode> projection,
+ boolean retainHeader,
+ String inputTerm,
+ String collectorTerm,
+ String errorTerm,
+ String recordTerm,
+ String delegatingFutureTerm) {
+
+ projection.forEach(n -> n.accept(new AsyncScalarFunctionsValidator()));
+
+ ExprCodeGenerator exprGenerator =
+ new ExprCodeGenerator(ctx, false)
+ .bindInput(
+ inputType,
+ inputTerm,
+ JavaScalaConversionUtil.toScala(Optional.empty()));
+
+ List<GeneratedExpression> projectionExprs =
+ projection.stream()
+ .map(exprGenerator::generateExpression)
+ .collect(Collectors.toList());
+ int syncIndex = 0;
+ int index = 0;
+ StringBuilder outputs = new StringBuilder();
+ StringBuilder syncInvocations = new StringBuilder();
+ StringBuilder asyncInvocation = new StringBuilder();
+ if (retainHeader) {
+ outputs.append(String.format("%s.setRowKind(rowKind);\n", recordTerm, inputTerm));
+ }
+ for (GeneratedExpression fieldExpr : projectionExprs) {
+ if (fieldExpr.resultTerm().isEmpty()) {
+ outputs.append(
+ String.format("%s.setField(%d, resultObject);\n", recordTerm, index));
+ asyncInvocation.append(fieldExpr.code());
+ } else {
+ outputs.append(
+ String.format(
+ "%s.setField(%d, %s.getSynchronousResult(%d));\n",
+ recordTerm, index, delegatingFutureTerm, syncIndex));
+ syncInvocations.append(fieldExpr.code());
+ syncInvocations.append(
+ String.format(
+ "%s.addSynchronousResult(%s);\n",
+ delegatingFutureTerm, fieldExpr.resultTerm()));
+ syncIndex++;
+ }
+ index++;
+ }
+
+ Map<String, String> values = new HashMap<>();
+ values.put("delegatingFuture", delegatingFutureTerm);
+ values.put("collectorTerm", collectorTerm);
+ values.put("typeTerm", outRowClass.getCanonicalName());
+ values.put("recordTerm", recordTerm);
+ values.put("inputTerm", inputTerm);
+ values.put("fieldCount", Integer.toString(LogicalTypeChecks.getFieldCount(outRowType)));
+ values.put("outputs", outputs.toString());
+ values.put("syncInvocations", syncInvocations.toString());
+ values.put("asyncInvocation", asyncInvocation.toString());
+ values.put("errorTerm", errorTerm);
+
+ return StringSubstitutor.replace(
+ String.join(
+ "\n",
+ new String[] {
+ "final org.apache.flink.table.runtime.operators.calc.async.DelegatingAsyncResultFuture ${delegatingFuture} ",
+ " = new org.apache.flink.table.runtime.operators.calc.async.DelegatingAsyncResultFuture(${collectorTerm});",
+ "final org.apache.flink.types.RowKind rowKind = ${inputTerm}.getRowKind();\n",
+ "try {",
+ " java.util.function.Function<Object, ${typeTerm}> outputFactory = ",
+ " new java.util.function.Function<Object, ${typeTerm}>() {",
+ " @Override",
+ " public ${typeTerm} apply(Object resultObject) {",
+ " final ${typeTerm} ${recordTerm} = new ${typeTerm}(${fieldCount});",
+ " ${outputs}",
+ " return ${recordTerm};",
+ " }",
+ " };",
+ "",
+ " ${delegatingFuture}.setOutputFactory(outputFactory);",
+ // Ensure that sync invocations come first so that we know that they're
+ // available when the async callback occurs.
+ " ${syncInvocations}",
+ " ${asyncInvocation}",
+ "",
+ "} catch (Throwable ${errorTerm}) {",
+ " ${collectorTerm}.completeExceptionally(${errorTerm});",
+ "}"
+ }),
+ values);
+ }
+
+ private static class AsyncScalarFunctionsValidator extends RexVisitorImpl<Void> {
+ public AsyncScalarFunctionsValidator() {
+ super(true);
+ }
+
+ @Override
+ public Void visitCall(RexCall call) {
+ super.visitCall(call);
+
+ if (call.getOperator() instanceof BridgingSqlFunction
+ && ((BridgingSqlFunction) call.getOperator()).getDefinition().getKind()
+ != FunctionKind.ASYNC_SCALAR) {
+ throw new ValidationException(
Review Comment:
I see. Ok, changed to `CodeGenException`
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalCalcRule.scala:
##########
@@ -35,7 +36,8 @@ class StreamPhysicalCalcRule(config: Config) extends ConverterRule(config) {
override def matches(call: RelOptRuleCall): Boolean = {
val calc: FlinkLogicalCalc = call.rel(0)
val program = calc.getProgram
- !program.getExprList.asScala.exists(containsPythonCall(_))
+ !program.getExprList.asScala.exists(containsPythonCall(_)) &&
+ !program.getExprList.asScala.exists(AsyncUtil.containsAsyncCall)
Review Comment:
Done, added static import
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecAsyncCalc.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.common;
+
+import org.apache.flink.api.dag.Transformation;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.streaming.api.functions.async.AsyncFunction;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperatorFactory;
+import org.apache.flink.streaming.api.operators.async.AsyncWaitOperatorFactory;
+import org.apache.flink.streaming.api.transformations.OneInputTransformation;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
+import org.apache.flink.table.planner.codegen.AsyncCodeGenerator;
+import org.apache.flink.table.planner.delegation.PlannerBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.SingleTransformationTranslator;
+import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
+import org.apache.flink.table.planner.plan.utils.AsyncUtil;
+import org.apache.flink.table.runtime.generated.GeneratedFunction;
+import org.apache.flink.table.runtime.operators.calc.async.AsyncFunctionRunner;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/** Base class for exec Async Calc. */
+public abstract class CommonExecAsyncCalc extends ExecNodeBase<RowData>
+ implements SingleTransformationTranslator<RowData> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(CommonExecAsyncCalc.class);
+
+ public static final String ASYNC_CALC_TRANSFORMATION = "async-calc";
+
+ public static final String FIELD_NAME_PROJECTION = "projection";
+
+ public static final String FIELD_NAME_SYNC_MODE = "syncMode";
+
+ @JsonProperty(FIELD_NAME_PROJECTION)
+ private final List<RexNode> projection;
+
+ public CommonExecAsyncCalc(
+ int id,
+ ExecNodeContext context,
+ ReadableConfig persistedConfig,
+ List<RexNode> projection,
Review Comment:
There is a rule (`RemoteCalcSplitConditionRule`) which, if there is an async call in the condition, moves it to a projection and creates a classic Calc (no async) with the condition for the result after it. Also, there's another rule (`RemoteCalcPushConditionRule`) which, if it sees a condition on a calc with async in the projection, pushes it down to be earlier in a new classic Calc (no async). So after these are both applied, there should be only projections on this async Calc. This is a similar technique used for python (`CommonExecPythonCalc`).
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecAsyncCalc.java:
##########
@@ -0,0 +1,75 @@
+/*
+ * 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.stream;
+
+import org.apache.flink.FlinkVersion;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeMetadata;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.common.CommonExecAsyncCalc;
+import org.apache.flink.table.types.logical.RowType;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
+
+import org.apache.calcite.rex.RexNode;
+
+import java.util.Collections;
+import java.util.List;
+
+/** Stream {@link ExecNode} for AsyncScalarFunctions. */
+@ExecNodeMetadata(
+ name = "stream-exec-async-calc",
+ version = 1,
+ producedTransformations = CommonExecAsyncCalc.ASYNC_CALC_TRANSFORMATION,
+ minPlanVersion = FlinkVersion.v1_17,
Review Comment:
Done
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalAsyncCalc.java:
##########
@@ -0,0 +1,85 @@
+/*
+ * 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.physical.stream;
+
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
+import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecAsyncCalc;
+import org.apache.flink.table.planner.plan.utils.AsyncUtil;
+
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Calc;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.table.planner.utils.ShortcutUtils.unwrapTableConfig;
+
+/** Stream physical RelNode for AsyncScalarFunctions. */
+public class StreamPhysicalAsyncCalc extends StreamPhysicalCalcBase {
+ private final RelOptCluster cluster;
+ private final RexProgram calcProgram;
+ private final RelDataType outputRowType;
+
+ public StreamPhysicalAsyncCalc(
+ RelOptCluster cluster,
+ RelTraitSet traitSet,
+ RelNode inputRel,
+ RexProgram calcProgram,
+ RelDataType outputRowType) {
+ super(cluster, traitSet, inputRel, calcProgram, outputRowType);
+ this.cluster = cluster;
+ this.calcProgram = calcProgram;
+ this.outputRowType = outputRowType;
+ }
+
+ @Override
+ public Calc copy(RelTraitSet traitSet, RelNode child, RexProgram program) {
+ return new StreamPhysicalAsyncCalc(cluster, traitSet, child, program, outputRowType);
+ }
+
+ @Override
+ public ExecNode<?> translateToExecNode() {
+ List<RexNode> projection =
+ calcProgram.getProjectList().stream()
+ .map(calcProgram::expandLocalRef)
+ .collect(Collectors.toList());
+ if (calcProgram.getCondition() != null) {
+ throw new TableException("The condition of StreamPhysicalAsyncCalc should be null.");
Review Comment:
Did `IllegalStateException`
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/BridgingFunctionGenUtil.scala:
##########
@@ -380,7 +411,9 @@ object BridgingFunctionGenUtil {
functionName: String): Unit = {
if (udf.getKind == FunctionKind.TABLE) {
verifyImplementation(TABLE_EVAL, argumentDataTypes, None, udf, functionName)
- } else if (udf.getKind == FunctionKind.ASYNC_TABLE) {
+ } else if (
+ udf.getKind == FunctionKind.ASYNC_TABLE || udf.getKind == FunctionKind.ASYNC_SCALAR
Review Comment:
Done, good call.
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/FlinkStreamRuleSets.scala:
##########
@@ -382,7 +382,16 @@ object FlinkStreamRuleSets {
PythonCalcSplitRule.PUSH_CONDITION,
PythonCalcSplitRule.REWRITE_PROJECT,
PythonMapRenameRule.INSTANCE,
- PythonMapMergeRule.INSTANCE
+ PythonMapMergeRule.INSTANCE,
+ AsyncCalcSplitRule.SPLIT_CONDITION_REX_FIELD,
+ AsyncCalcSplitRule.SPLIT_PROJECTION_REX_FIELD,
+ AsyncCalcSplitRule.SPLIT_CONDITION,
+ AsyncCalcSplitRule.SPLIT_PROJECT,
+ AsyncCalcSplitRule.EXPAND_PROJECT,
+ AsyncCalcSplitRule.PUSH_CONDITION,
+ AsyncCalcSplitRule.REWRITE_PROJECT,
+ AsyncCalcSplitRule.NESTED_SPLIT,
Review Comment:
Done. Most of the comments are "Avoids having this: ..." since effectively most of the rules are to simplify the types of things an operator can see.
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRuleTest.java:
##########
@@ -0,0 +1,274 @@
+/*
+ * 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.api.common.typeinfo.TypeInformation;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.api.TableConfig;
+import org.apache.flink.table.api.Types;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.planner.plan.optimize.program.BatchOptimizeContext;
+import org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram;
+import org.apache.flink.table.planner.plan.optimize.program.FlinkHepRuleSetProgramBuilder;
+import org.apache.flink.table.planner.plan.optimize.program.HEP_RULES_EXECUTION_TYPE;
+import org.apache.flink.table.planner.plan.rules.FlinkStreamRuleSets;
+import org.apache.flink.table.planner.utils.TableTestBase;
+import org.apache.flink.table.planner.utils.TableTestUtil;
+import org.apache.flink.types.Row;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.apache.calcite.plan.hep.HepMatchOrder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.concurrent.CompletableFuture;
+
+/** Test for {@link AsyncCalcSplitRule}. */
+public class AsyncCalcSplitRuleTest extends TableTestBase {
+
+ private TableTestUtil util = streamTestUtil(TableConfig.getDefault());
+
+ @BeforeEach
+ public void setup() {
+ FlinkChainedProgram programs = new FlinkChainedProgram<BatchOptimizeContext>();
+ programs.addLast(
+ "logical_rewrite",
+ FlinkHepRuleSetProgramBuilder.newBuilder()
+ .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE())
+ .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
+ .add(FlinkStreamRuleSets.LOGICAL_REWRITE())
+ .build());
+
+ util.addTableSource(
Review Comment:
Yes, didn't realize I could just do this:
```
TableEnvironment tEnv = util.getTableEnv();
tEnv.executeSql("CREATE TABLE MyTable (\n"
+ " a int,\n"
+ " b bigint,\n"
+ " c string,\n"
+ " d ARRAY<INT NOT NULL>\n"
+ ") ;");
```
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/table/AsyncCalcITCase.java:
##########
@@ -0,0 +1,561 @@
+/*
+ * 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.runtime.stream.table;
+
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.api.EnvironmentSettings;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.TableEnvironment;
+import org.apache.flink.table.api.TableResult;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.config.ExecutionConfigOptions;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionContext;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** IT Case tests for {@link AsyncScalarFunction}. */
+public class AsyncCalcITCase extends AbstractTestBase {
+
+ private StreamExecutionEnvironment env;
+
+ private TableEnvironment tEnv;
+
+ @BeforeEach
+ public void before() throws Exception {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.setParallelism(1);
+ env.setMaxParallelism(1);
+ tEnv = StreamTableEnvironment.create(env, EnvironmentSettings.inStreamingMode());
+ tEnv.getConfig().set(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_DEFAULT_PARALLELISM, 1);
+ tEnv.getConfig().set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY, 1);
+ tEnv.getConfig()
+ .set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_TIMEOUT, Duration.ofMinutes(1));
+ }
+
+ @Test
+ public void testSimpleTableSelect() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
Review Comment:
Done
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/table/AsyncCalcITCase.java:
##########
@@ -0,0 +1,561 @@
+/*
+ * 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.runtime.stream.table;
+
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.annotation.DataTypeHint;
+import org.apache.flink.table.api.EnvironmentSettings;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.TableEnvironment;
+import org.apache.flink.table.api.TableResult;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.config.ExecutionConfigOptions;
+import org.apache.flink.table.functions.AsyncScalarFunction;
+import org.apache.flink.table.functions.FunctionContext;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableList;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** IT Case tests for {@link AsyncScalarFunction}. */
+public class AsyncCalcITCase extends AbstractTestBase {
+
+ private StreamExecutionEnvironment env;
+
+ private TableEnvironment tEnv;
+
+ @BeforeEach
+ public void before() throws Exception {
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.setParallelism(1);
+ env.setMaxParallelism(1);
+ tEnv = StreamTableEnvironment.create(env, EnvironmentSettings.inStreamingMode());
+ tEnv.getConfig().set(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_DEFAULT_PARALLELISM, 1);
+ tEnv.getConfig().set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY, 1);
+ tEnv.getConfig()
+ .set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_TIMEOUT, Duration.ofMinutes(1));
+ }
+
+ @Test
+ public void testSimpleTableSelect() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of("val 1"), Row.of("val 2"), Row.of("val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testLiteralPlusTableSelect() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select 'foo', func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(
+ Row.of("foo", "val 1"), Row.of("foo", "val 2"), Row.of("foo", "val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testFieldPlusTableSelect() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select f1, func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of(1, "val 1"), Row.of(2, "val 2"), Row.of(3, "val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testTwoCalls() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(f1), func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(
+ Row.of("val 1", "val 1"),
+ Row.of("val 2", "val 2"),
+ Row.of("val 3", "val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testNestedCalls() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFuncAdd10());
+ final List<Row> results = executeSql("select func(func(func(f1))) from t1");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(31), Row.of(32), Row.of(33));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testThreeNestedCalls() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFuncAdd10());
+ final List<Row> results =
+ executeSql("select func(func(f1)), func(func(func(f1))), func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of(21, 31, 11), Row.of(22, 32, 12), Row.of(23, 33, 13));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testPassedToOtherUDF() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select Concat(func(f1), 'foo') from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of("val 1foo"), Row.of("val 2foo"), Row.of("val 3foo"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testJustCall() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(1)");
+ final List<Row> expectedRows = ImmutableList.of(Row.of("val 1"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testWhereCondition() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql("select f1 from t1 where REGEXP(func(f1), 'val (2|3)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2), Row.of(3));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testWhereConditionAndProjection() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql("select func(f1) from t1 where REGEXP(func(f1), 'val (2|3)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of("val 2"), Row.of("val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testWhereConditionWithInts() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFuncAdd10());
+ final List<Row> results = executeSql("select f1 from t1 where func(f1) >= 12");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2), Row.of(3));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testAggregate() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 1, 3, 4).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFuncAdd10Long());
+ final List<Row> results = executeSql("select f1, func(count(*)) from t1 group by f1");
+ final List<Row> expectedRows =
+ ImmutableList.of(
+ Row.of(1, 11L),
+ Row.of(2, 11L),
+ Row.of(3, 11L),
+ Row.ofKind(RowKind.UPDATE_BEFORE, 1, 11L),
+ Row.ofKind(RowKind.UPDATE_AFTER, 1, 12L),
+ Row.ofKind(RowKind.UPDATE_BEFORE, 3, 11L),
+ Row.ofKind(RowKind.UPDATE_AFTER, 3, 12L),
+ Row.of(4, 11L));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testSelectCallWithIntArray() {
+ Table t1 = tEnv.fromValues(new int[] {1, 2}, new int[] {3, 4}).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFuncAdd10IntArray());
+ final List<Row> results = executeSql("select func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(
+ Row.of(new Object[] {new Integer[] {11, 12}}),
+ Row.of(new Object[] {new Integer[] {13, 14}}));
+ // When run here, the plan is a union of the two AsyncCalcs so order is
+ // not retained!
+ assertThat(results).containsExactlyInAnyOrderElementsOf(expectedRows);
+ }
+
+ @Test
+ public void testInnerJoinWithFuncInOn() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql(
+ "select f1 from t1 INNER JOIN t2 ON func(f1) = func(f2) AND REGEXP(func(f1), 'val (2|4)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2), Row.of(4));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testInnerJoinWithFuncProjection() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(f1) from t1 INNER JOIN t2 ON f1 = f2");
+ final List<Row> expectedRows = ImmutableList.of(Row.of("val 2"), Row.of("val 4"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testInnerJoinWithFuncInWhere() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql(
+ "select f1 from t1 INNER JOIN t2 ON f1 = f2 WHERE REGEXP(func(f1), 'val (2|3)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testLeftJoinWithFuncInOn() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql("select f1, f2 from t1 LEFT JOIN t2 ON func(f1) = func(f2)");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of(1, null), Row.of(2, 2), Row.of(3, null), Row.of(4, 4));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testLeftJoinWithFuncInWhere() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql(
+ "select f1, f2 from t1 LEFT JOIN t2 ON f1 = f2 WHERE REGEXP(func(f1), 'val (2|3)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2, 2), Row.of(3, null));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testRightJoinWithFuncInOn() {
+ Table t1 = tEnv.fromValues(1, 2, 3, 4).as("f1");
+ Table t2 = tEnv.fromValues(2, 4).as("f2");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryView("t2", t2);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql("select f1, f2 from t1 FULL OUTER JOIN t2 ON func(f1) = func(f2)");
+ assertThat(results).hasSize(8);
+ }
+
+ @Test
+ public void testSelectWithConfigs() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.getConfig()
+ .set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_BUFFER_CAPACITY.key(), "10");
+ tEnv.getConfig().set(ExecutionConfigOptions.TABLE_EXEC_ASYNC_SCALAR_TIMEOUT.key(), "1m");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results = executeSql("select func(f1) from t1");
+ final List<Row> expectedRows =
+ ImmutableList.of(Row.of("val 1"), Row.of("val 2"), Row.of("val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testProjectCallInSubquery() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql(
+ "select blah FROM (select func(f1) as blah from t1) "
+ + "WHERE REGEXP(blah, 'val (2|3)')");
+ final List<Row> expectedRows = ImmutableList.of(Row.of("val 2"), Row.of("val 3"));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testWhereConditionCallInSubquery() {
+ Table t1 = tEnv.fromValues(1, 2, 3).as("f1");
+ tEnv.createTemporaryView("t1", t1);
+ tEnv.createTemporaryFunction("func", new AsyncFunc());
+ final List<Row> results =
+ executeSql(
+ "select blah FROM (select f1 as blah from t1 "
+ + "WHERE REGEXP(func(f1), 'val (2|3)'))");
+ final List<Row> expectedRows = ImmutableList.of(Row.of(2), Row.of(3));
+ assertThat(results).containsSequence(expectedRows);
+ }
+
+ @Test
+ public void testWhereNotInSubquery() {
Review Comment:
Yeah, I agree. I originally had the tests actually test things about the plan, e.g. that it was in sync mode, so had all sorts of query types that I wanted to verify, but sync mode no longer is a thing in this PR. And there are rule tests anyway that are probably more appropriate for that if that gets readded.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org