You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@iotdb.apache.org by "Sh-Zh-7 (via GitHub)" <gi...@apache.org> on 2024/01/29 14:03:10 UTC

[PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Sh-Zh-7 opened a new pull request, #12005:
URL: https://github.com/apache/iotdb/pull/12005

   ## Description
   
   This PR we introduce a new feature: **UDAF(User-Defined Aggregation Functions)**.
   Now users can customize their aggregation functions and seamlessly integrate them into IoTDB powerful aggregation framework. 🎉🎉
   
   More details can be seen: https://apache-iotdb.feishu.cn/docx/HNawdvH1Goo5sRxtmX9cjLHyniF
   The User Manual will come later soon.
   
   
   <hr>
   
   This PR has:
   - [x] been self-reviewed.
   - [x] added documentation for new or modified features or behaviors.
   - [x] added Javadocs for most classes and all non-trivial methods. 
   - [x] added or updated version, __license__, or notice information
   - [x] added unit tests or modified existing tests to cover new code paths, ensuring the threshold 
     for code coverage.
   - [x] added integration tests.
   - [x] been tested in a test IoTDB cluster.
   
   <!-- Check the items by putting "x" in the brackets for the done things. Not all of these items 
   apply to every PR. Remove the items which are not done or not relevant to the PR. None of the items 
   from the checklist above are strictly necessary, but it would be very helpful if you at least 
   self-review the PR. -->
   
   <hr>
   
   


-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Posted by "JackieTien97 (via GitHub)" <gi...@apache.org>.
JackieTien97 commented on code in PR #12005:
URL: https://github.com/apache/iotdb/pull/12005#discussion_r1473870500


##########
iotdb-api/udf-api/src/main/java/org/apache/iotdb/udf/api/UDAF.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.iotdb.udf.api;
+
+import org.apache.iotdb.tsfile.read.common.block.column.Column;
+import org.apache.iotdb.tsfile.utils.BitMap;
+import org.apache.iotdb.udf.api.customizer.config.UDAFConfigurations;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameters;
+import org.apache.iotdb.udf.api.utils.ResultValue;
+
+public interface UDAF extends UDF {
+  void beforeStart(UDFParameters parameters, UDAFConfigurations configurations);
+
+  /** Create and initialize state. You may bind some resource in this method. */
+  State createState();
+
+  /**
+   * Batch update state with data columns. You shall iterate columns and update state with raw
+   * values
+   *
+   * @param state state to be updated
+   * @param column input columns from IoTDB TsBlock

Review Comment:
   Should remind users that column[0] will always be TimeColumn, the remaining Columns will be their parameter value column.



##########
iotdb-api/udf-api/src/main/java/org/apache/iotdb/udf/api/customizer/config/UDAFConfigurations.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.iotdb.udf.api.customizer.config;
+
+import org.apache.iotdb.udf.api.type.Type;
+
+import java.time.ZoneId;
+
+public class UDAFConfigurations extends UDFConfigurations {
+
+  protected final ZoneId zoneId;

Review Comment:
   ```suggestion
   ```
   If we don't use this field now, we should remove it.



##########
iotdb-api/udf-api/src/main/java/org/apache/iotdb/udf/api/UDAF.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.iotdb.udf.api;
+
+import org.apache.iotdb.tsfile.read.common.block.column.Column;
+import org.apache.iotdb.tsfile.utils.BitMap;
+import org.apache.iotdb.udf.api.customizer.config.UDAFConfigurations;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameters;
+import org.apache.iotdb.udf.api.utils.ResultValue;
+
+public interface UDAF extends UDF {
+  void beforeStart(UDFParameters parameters, UDAFConfigurations configurations);
+
+  /** Create and initialize state. You may bind some resource in this method. */
+  State createState();
+
+  /**
+   * Batch update state with data columns. You shall iterate columns and update state with raw
+   * values
+   *
+   * @param state state to be updated
+   * @param column input columns from IoTDB TsBlock
+   * @param bitMap define some filtered position in columns
+   */
+  void addInput(State state, Column[] column, BitMap bitMap);

Review Comment:
   ```suggestion
     void addInput(State state, Column[] columns, BitMap bitMap);
   ```



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/AggregationUtil.java:
##########
@@ -58,6 +60,9 @@ public class AggregationUtil {
 
   private static final String PARTIAL_SUFFIX = "_partial";
 
+  private static final List<String> builtinAggregationNames =

Review Comment:
   Use `BuiltinAggregationFunction.NATIVE_FUNCTION_NAMES` instead.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/parameter/AggregationDescriptor.java:
##########
@@ -63,18 +64,29 @@ public class AggregationDescriptor {
 
   protected String parametersString;
 
+  private List<String> builtinAggregationNames;
+

Review Comment:
   ```suggestion
   ```
   
   never used.



-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Posted by "Sh-Zh-7 (via GitHub)" <gi...@apache.org>.
Sh-Zh-7 commented on code in PR #12005:
URL: https://github.com/apache/iotdb/pull/12005#discussion_r1475527908


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/aggregation/UDAFAccumulator.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.iotdb.db.queryengine.execution.aggregation;
+
+import org.apache.iotdb.commons.udf.service.UDFManagementService;
+import org.apache.iotdb.commons.udf.utils.UDFDataTypeTransformer;
+import org.apache.iotdb.db.queryengine.plan.expression.Expression;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.statistics.Statistics;
+import org.apache.iotdb.tsfile.read.common.block.column.Column;
+import org.apache.iotdb.tsfile.read.common.block.column.ColumnBuilder;
+import org.apache.iotdb.tsfile.utils.Binary;
+import org.apache.iotdb.tsfile.utils.BitMap;
+import org.apache.iotdb.udf.api.State;
+import org.apache.iotdb.udf.api.UDAF;
+import org.apache.iotdb.udf.api.customizer.config.UDAFConfigurations;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameterValidator;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameters;
+import org.apache.iotdb.udf.api.utils.ResultValue;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.ZoneId;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+public class UDAFAccumulator implements Accumulator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(UDAFAccumulator.class);
+
+  private final String functionName;
+  private final UDAFConfigurations configurations;
+
+  private State state;
+
+  private UDAF udaf;
+
+  public UDAFAccumulator(
+      String functionName,
+      List<Expression> childrenExpressions,
+      TSDataType childrenExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    this.functionName = functionName;
+    this.configurations = new UDAFConfigurations(ZoneId.systemDefault());
+
+    List<String> childExpressionStrings =
+        childrenExpressions.stream()
+            .map(Expression::getExpressionString)
+            .collect(Collectors.toList());
+    beforeStart(
+        childExpressionStrings,
+        Collections.singletonList(childrenExpressionDataTypes),
+        attributes,
+        isInputRaw);
+  }
+
+  private void beforeStart(
+      List<String> childExpressions,
+      List<TSDataType> childExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    reflectAndValidateUDF(childExpressions, childExpressionDataTypes, attributes, isInputRaw);
+    configurations.check();
+  }
+
+  private void reflectAndValidateUDF(
+      List<String> childExpressions,
+      List<TSDataType> childExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    udaf = (UDAF) UDFManagementService.getInstance().reflect(functionName);
+    state = udaf.createState();
+
+    final UDFParameters parameters =
+        new UDFParameters(
+            childExpressions,
+            UDFDataTypeTransformer.transformToUDFDataTypeList(childExpressionDataTypes),
+            attributes);
+
+    // Only validate for raw input
+    // There is no need to validate for partial input
+    if (isInputRaw) {
+      try {
+        // Double validates in workers
+        udaf.validate(new UDFParameterValidator(parameters));
+      } catch (Exception e) {
+        onError("validate(UDFParameterValidator)", e);
+      }
+    }
+
+    try {
+      udaf.beforeStart(parameters, configurations);
+    } catch (Exception e) {
+      onError("beforeStart(UDFParameters, UDAFConfigurations)", e);
+    }
+  }
+
+  @Override
+  public void addInput(Column[] columns, BitMap bitMap) {
+    udaf.addInput(state, columns, bitMap);
+  }
+
+  @Override
+  public void addIntermediate(Column[] partialResult) {
+    checkArgument(partialResult.length == 1, "partialResult of UDAF should be 1");
+    if (partialResult[0].isNull(0)) {
+      return;
+    }
+
+    State otherState = udaf.createState();
+    Binary otherStateBinary = partialResult[0].getBinary(0);
+    otherState.deserialize(otherStateBinary.getValues());
+
+    udaf.combineState(state, otherState);
+  }
+
+  // Currently, UDAF does not support optimization
+  // by statistics in TsFile
+  @Override
+  public void addStatistics(Statistics statistics) {
+    throw new UnsupportedOperationException(getClass().getName());
+  }
+
+  // Currently, query engine won't generate
+  // Final -> Final AggregationStep for UDAF
+  @Override
+  public void setFinal(Column finalResult) {
+    throw new UnsupportedOperationException(getClass().getName());
+  }
+
+  @Override
+  public void outputIntermediate(ColumnBuilder[] columnBuilders) {
+    checkArgument(columnBuilders.length == 1, "partialResult of UDAF should be 1");
+
+    byte[] bytes = state.serialize();

Review Comment:
   If uninitialized state is needed, users shall add a field like `isInit` in their state class, and serialize the whole state object along with the field into binary, then handle this field in `combineState()` method. You can refer to this example: [UDAFSum.java](https://github.com/apache/iotdb/pull/12005/files#diff-e9b1b5efc75765bc2ddc3ad158368fdf40cc0b6a716c5c01b1a75899c849740dR111)



-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Posted by "JackieTien97 (via GitHub)" <gi...@apache.org>.
JackieTien97 merged PR #12005:
URL: https://github.com/apache/iotdb/pull/12005


-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Posted by "lancelly (via GitHub)" <gi...@apache.org>.
lancelly commented on code in PR #12005:
URL: https://github.com/apache/iotdb/pull/12005#discussion_r1475471640


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/aggregation/UDAFAccumulator.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.iotdb.db.queryengine.execution.aggregation;
+
+import org.apache.iotdb.commons.udf.service.UDFManagementService;
+import org.apache.iotdb.commons.udf.utils.UDFDataTypeTransformer;
+import org.apache.iotdb.db.queryengine.plan.expression.Expression;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.statistics.Statistics;
+import org.apache.iotdb.tsfile.read.common.block.column.Column;
+import org.apache.iotdb.tsfile.read.common.block.column.ColumnBuilder;
+import org.apache.iotdb.tsfile.utils.Binary;
+import org.apache.iotdb.tsfile.utils.BitMap;
+import org.apache.iotdb.udf.api.State;
+import org.apache.iotdb.udf.api.UDAF;
+import org.apache.iotdb.udf.api.customizer.config.UDAFConfigurations;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameterValidator;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameters;
+import org.apache.iotdb.udf.api.utils.ResultValue;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.ZoneId;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+public class UDAFAccumulator implements Accumulator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(UDAFAccumulator.class);
+
+  private final String functionName;
+  private final UDAFConfigurations configurations;
+
+  private State state;
+
+  private UDAF udaf;
+
+  public UDAFAccumulator(
+      String functionName,
+      List<Expression> childrenExpressions,
+      TSDataType childrenExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    this.functionName = functionName;
+    this.configurations = new UDAFConfigurations(ZoneId.systemDefault());
+
+    List<String> childExpressionStrings =
+        childrenExpressions.stream()
+            .map(Expression::getExpressionString)
+            .collect(Collectors.toList());
+    beforeStart(
+        childExpressionStrings,
+        Collections.singletonList(childrenExpressionDataTypes),
+        attributes,
+        isInputRaw);
+  }
+
+  private void beforeStart(
+      List<String> childExpressions,
+      List<TSDataType> childExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    reflectAndValidateUDF(childExpressions, childExpressionDataTypes, attributes, isInputRaw);
+    configurations.check();
+  }
+
+  private void reflectAndValidateUDF(
+      List<String> childExpressions,
+      List<TSDataType> childExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    udaf = (UDAF) UDFManagementService.getInstance().reflect(functionName);
+    state = udaf.createState();
+
+    final UDFParameters parameters =
+        new UDFParameters(
+            childExpressions,
+            UDFDataTypeTransformer.transformToUDFDataTypeList(childExpressionDataTypes),
+            attributes);
+
+    // Only validate for raw input
+    // There is no need to validate for partial input
+    if (isInputRaw) {
+      try {
+        // Double validates in workers
+        udaf.validate(new UDFParameterValidator(parameters));
+      } catch (Exception e) {
+        onError("validate(UDFParameterValidator)", e);
+      }
+    }
+
+    try {
+      udaf.beforeStart(parameters, configurations);
+    } catch (Exception e) {
+      onError("beforeStart(UDFParameters, UDAFConfigurations)", e);
+    }
+  }
+
+  @Override
+  public void addInput(Column[] columns, BitMap bitMap) {
+    udaf.addInput(state, columns, bitMap);
+  }
+
+  @Override
+  public void addIntermediate(Column[] partialResult) {
+    checkArgument(partialResult.length == 1, "partialResult of UDAF should be 1");
+    if (partialResult[0].isNull(0)) {
+      return;
+    }
+
+    State otherState = udaf.createState();
+    Binary otherStateBinary = partialResult[0].getBinary(0);
+    otherState.deserialize(otherStateBinary.getValues());
+
+    udaf.combineState(state, otherState);
+  }
+
+  // Currently, UDAF does not support optimization
+  // by statistics in TsFile
+  @Override
+  public void addStatistics(Statistics statistics) {
+    throw new UnsupportedOperationException(getClass().getName());
+  }
+
+  // Currently, query engine won't generate
+  // Final -> Final AggregationStep for UDAF
+  @Override
+  public void setFinal(Column finalResult) {
+    throw new UnsupportedOperationException(getClass().getName());
+  }
+
+  @Override
+  public void outputIntermediate(ColumnBuilder[] columnBuilders) {
+    checkArgument(columnBuilders.length == 1, "partialResult of UDAF should be 1");
+
+    byte[] bytes = state.serialize();

Review Comment:
   This method serializes the initial state into bytes[] (even if the accumulator hasn't had any values added, it will still serialize the initial state?), but in other Accumulator implementations, it checks whether an initial value has already been set, and if so, serializes the binary data; otherwise, it appends Null. Currently, it seems that this method doesn't check whether an initial value has been initialized. I wonder if this could potentially have an impact on the result.



-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Posted by "Sh-Zh-7 (via GitHub)" <gi...@apache.org>.
Sh-Zh-7 commented on code in PR #12005:
URL: https://github.com/apache/iotdb/pull/12005#discussion_r1478493012


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/AggregationUtil.java:
##########
@@ -58,6 +60,9 @@ public class AggregationUtil {
 
   private static final String PARTIAL_SUFFIX = "_partial";
 
+  private static final List<String> builtinAggregationNames =

Review Comment:
   Done.



##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/parameter/AggregationDescriptor.java:
##########
@@ -63,18 +64,29 @@ public class AggregationDescriptor {
 
   protected String parametersString;
 
+  private List<String> builtinAggregationNames;
+

Review Comment:
   Done.



-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Posted by "lancelly (via GitHub)" <gi...@apache.org>.
lancelly commented on code in PR #12005:
URL: https://github.com/apache/iotdb/pull/12005#discussion_r1475446815


##########
iotdb-api/udf-api/src/main/java/org/apache/iotdb/udf/api/customizer/config/UDAFConfigurations.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.iotdb.udf.api.customizer.config;
+
+import org.apache.iotdb.udf.api.type.Type;
+
+import java.time.ZoneId;
+
+public class UDAFConfigurations extends UDFConfigurations {
+
+  protected final ZoneId zoneId;

Review Comment:
   "UDTFConfiguration retains ZoneId, but it is not used in the internal implementation or built-in UDTFs. It may simply be kept for users who need it."



-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Posted by "lancelly (via GitHub)" <gi...@apache.org>.
lancelly commented on code in PR #12005:
URL: https://github.com/apache/iotdb/pull/12005#discussion_r1475446815


##########
iotdb-api/udf-api/src/main/java/org/apache/iotdb/udf/api/customizer/config/UDAFConfigurations.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.iotdb.udf.api.customizer.config;
+
+import org.apache.iotdb.udf.api.type.Type;
+
+import java.time.ZoneId;
+
+public class UDAFConfigurations extends UDFConfigurations {
+
+  protected final ZoneId zoneId;

Review Comment:
   UDTFConfiguration retains ZoneId, but it is not used in the internal implementation or built-in UDTFs. It may simply be kept for users who need it.



-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Posted by "Sh-Zh-7 (via GitHub)" <gi...@apache.org>.
Sh-Zh-7 commented on code in PR #12005:
URL: https://github.com/apache/iotdb/pull/12005#discussion_r1478490554


##########
iotdb-api/udf-api/src/main/java/org/apache/iotdb/udf/api/UDAF.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.iotdb.udf.api;
+
+import org.apache.iotdb.tsfile.read.common.block.column.Column;
+import org.apache.iotdb.tsfile.utils.BitMap;
+import org.apache.iotdb.udf.api.customizer.config.UDAFConfigurations;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameters;
+import org.apache.iotdb.udf.api.utils.ResultValue;
+
+public interface UDAF extends UDF {
+  void beforeStart(UDFParameters parameters, UDAFConfigurations configurations);
+
+  /** Create and initialize state. You may bind some resource in this method. */
+  State createState();
+
+  /**
+   * Batch update state with data columns. You shall iterate columns and update state with raw
+   * values
+   *
+   * @param state state to be updated
+   * @param column input columns from IoTDB TsBlock

Review Comment:
   Done.



##########
iotdb-api/udf-api/src/main/java/org/apache/iotdb/udf/api/UDAF.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.iotdb.udf.api;
+
+import org.apache.iotdb.tsfile.read.common.block.column.Column;
+import org.apache.iotdb.tsfile.utils.BitMap;
+import org.apache.iotdb.udf.api.customizer.config.UDAFConfigurations;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameters;
+import org.apache.iotdb.udf.api.utils.ResultValue;
+
+public interface UDAF extends UDF {
+  void beforeStart(UDFParameters parameters, UDAFConfigurations configurations);
+
+  /** Create and initialize state. You may bind some resource in this method. */
+  State createState();
+
+  /**
+   * Batch update state with data columns. You shall iterate columns and update state with raw
+   * values
+   *
+   * @param state state to be updated
+   * @param column input columns from IoTDB TsBlock
+   * @param bitMap define some filtered position in columns
+   */
+  void addInput(State state, Column[] column, BitMap bitMap);

Review Comment:
   Done.



-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Posted by "Sh-Zh-7 (via GitHub)" <gi...@apache.org>.
Sh-Zh-7 commented on code in PR #12005:
URL: https://github.com/apache/iotdb/pull/12005#discussion_r1475527569


##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/aggregation/UDAFAccumulator.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.iotdb.db.queryengine.execution.aggregation;
+
+import org.apache.iotdb.commons.udf.service.UDFManagementService;
+import org.apache.iotdb.commons.udf.utils.UDFDataTypeTransformer;
+import org.apache.iotdb.db.queryengine.plan.expression.Expression;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.statistics.Statistics;
+import org.apache.iotdb.tsfile.read.common.block.column.Column;
+import org.apache.iotdb.tsfile.read.common.block.column.ColumnBuilder;
+import org.apache.iotdb.tsfile.utils.Binary;
+import org.apache.iotdb.tsfile.utils.BitMap;
+import org.apache.iotdb.udf.api.State;
+import org.apache.iotdb.udf.api.UDAF;
+import org.apache.iotdb.udf.api.customizer.config.UDAFConfigurations;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameterValidator;
+import org.apache.iotdb.udf.api.customizer.parameter.UDFParameters;
+import org.apache.iotdb.udf.api.utils.ResultValue;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.ZoneId;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+public class UDAFAccumulator implements Accumulator {
+  private static final Logger LOGGER = LoggerFactory.getLogger(UDAFAccumulator.class);
+
+  private final String functionName;
+  private final UDAFConfigurations configurations;
+
+  private State state;
+
+  private UDAF udaf;
+
+  public UDAFAccumulator(
+      String functionName,
+      List<Expression> childrenExpressions,
+      TSDataType childrenExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    this.functionName = functionName;
+    this.configurations = new UDAFConfigurations(ZoneId.systemDefault());
+
+    List<String> childExpressionStrings =
+        childrenExpressions.stream()
+            .map(Expression::getExpressionString)
+            .collect(Collectors.toList());
+    beforeStart(
+        childExpressionStrings,
+        Collections.singletonList(childrenExpressionDataTypes),
+        attributes,
+        isInputRaw);
+  }
+
+  private void beforeStart(
+      List<String> childExpressions,
+      List<TSDataType> childExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    reflectAndValidateUDF(childExpressions, childExpressionDataTypes, attributes, isInputRaw);
+    configurations.check();
+  }
+
+  private void reflectAndValidateUDF(
+      List<String> childExpressions,
+      List<TSDataType> childExpressionDataTypes,
+      Map<String, String> attributes,
+      boolean isInputRaw) {
+    udaf = (UDAF) UDFManagementService.getInstance().reflect(functionName);
+    state = udaf.createState();
+
+    final UDFParameters parameters =
+        new UDFParameters(
+            childExpressions,
+            UDFDataTypeTransformer.transformToUDFDataTypeList(childExpressionDataTypes),
+            attributes);
+
+    // Only validate for raw input
+    // There is no need to validate for partial input
+    if (isInputRaw) {
+      try {
+        // Double validates in workers
+        udaf.validate(new UDFParameterValidator(parameters));
+      } catch (Exception e) {
+        onError("validate(UDFParameterValidator)", e);
+      }
+    }
+
+    try {
+      udaf.beforeStart(parameters, configurations);
+    } catch (Exception e) {
+      onError("beforeStart(UDFParameters, UDAFConfigurations)", e);
+    }
+  }
+
+  @Override
+  public void addInput(Column[] columns, BitMap bitMap) {
+    udaf.addInput(state, columns, bitMap);
+  }
+
+  @Override
+  public void addIntermediate(Column[] partialResult) {
+    checkArgument(partialResult.length == 1, "partialResult of UDAF should be 1");
+    if (partialResult[0].isNull(0)) {
+      return;
+    }
+
+    State otherState = udaf.createState();
+    Binary otherStateBinary = partialResult[0].getBinary(0);
+    otherState.deserialize(otherStateBinary.getValues());
+
+    udaf.combineState(state, otherState);
+  }
+
+  // Currently, UDAF does not support optimization
+  // by statistics in TsFile
+  @Override
+  public void addStatistics(Statistics statistics) {
+    throw new UnsupportedOperationException(getClass().getName());
+  }
+
+  // Currently, query engine won't generate
+  // Final -> Final AggregationStep for UDAF
+  @Override
+  public void setFinal(Column finalResult) {
+    throw new UnsupportedOperationException(getClass().getName());
+  }
+
+  @Override
+  public void outputIntermediate(ColumnBuilder[] columnBuilders) {
+    checkArgument(columnBuilders.length == 1, "partialResult of UDAF should be 1");
+
+    byte[] bytes = state.serialize();

Review Comment:
   I think NULL value here is just to save some space. While all built-in aggregators use additional field (like `initResult`) to indicate whether the state is initialized, we can't force users to do so. For simplicity, we just serialize the whole state object into binary.
   
   The problem is, some built-in aggregators will append NULL in columnBuilder if the state is uninitialized, and the NULL value would be skipped in `addIntermediate()` and `removeIntermediate()` method. Since UDAF won't produce NULL intermediate output, shall we remove the **skip the NULL logic** in both methods?
   
   IMHO, if the logic is removed and UT/IT is still passed, we can consider to safely apply this change.
   
   



-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce UDAF(User-Defined Aggregation Functions) [iotdb]

Posted by "Sh-Zh-7 (via GitHub)" <gi...@apache.org>.
Sh-Zh-7 commented on code in PR #12005:
URL: https://github.com/apache/iotdb/pull/12005#discussion_r1478492788


##########
iotdb-api/udf-api/src/main/java/org/apache/iotdb/udf/api/customizer/config/UDAFConfigurations.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.iotdb.udf.api.customizer.config;
+
+import org.apache.iotdb.udf.api.type.Type;
+
+import java.time.ZoneId;
+
+public class UDAFConfigurations extends UDFConfigurations {
+
+  protected final ZoneId zoneId;

Review Comment:
   Temporarily remove this field. We can add it when we actually need it in the future,



-- 
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: reviews-unsubscribe@iotdb.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org