viirya commented on code in PR #6130: URL: https://github.com/apache/datafusion-comet/pull/6130#discussion_r4107073304
########## spark/src/main/spark-4.1+/org/apache/spark/sql/comet/CometArrowEvalPythonExec.scala: ########## @@ -0,0 +1,167 @@ +/* + * 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.spark.sql.comet + +import scala.jdk.CollectionConverters._ + +import org.apache.spark.api.python.PythonEvalType +import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, Expression, NamedArgumentExpression, NamedExpression, PythonUDF} +import org.apache.spark.sql.execution.{PartitioningPreservingUnaryExecNode, SparkPlan} +import org.apache.spark.sql.execution.python.ArrowEvalPythonExec +import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, DataType, DateType, DecimalType, DoubleType, FloatType, IntegerType, LongType, ShortType, StringType, TimestampNTZType} + +import com.google.protobuf.ByteString + +import org.apache.comet.{CometConf, ConfigEntry, NativeBase} +import org.apache.comet.CometSparkSessionExtensions.withFallbackReason +import org.apache.comet.serde.{CometOperatorSerde, Compatible, OperatorOuterClass, QueryPlanSerde, SupportLevel, Unsupported} +import org.apache.comet.serde.OperatorOuterClass.Operator + +/** Native execution for Spark 4.1+ scalar `@arrow_udf` functions. */ +object CometArrowEvalPythonExec extends CometOperatorSerde[ArrowEvalPythonExec] { + + // SparkContext adds this entry even when the user has not configured a Python + // environment. Keep other overrides on Spark's worker path. + private def hasUnsupportedEnvironment(env: java.util.Map[String, String]): Boolean = + env != null && env.asScala.exists { case (key, value) => + key != "PYTHONHASHSEED" || value != "0" + } + + private def hasCompatibleArrowSchema(dataType: DataType): Boolean = dataType match { + case _: BooleanType | _: ByteType | _: ShortType | _: IntegerType | _: LongType | + _: FloatType | _: DoubleType | _: BinaryType | _: DateType | _: DecimalType | + _: TimestampNTZType => + true + // Spark's Arrow conversion accepts plain strings. Collated and constrained strings + // may carry semantics that are not represented by Comet's Utf8 Arrow type. + case s: StringType if s == StringType => true + case _ => false + } + + override def enabledConfig: Option[ConfigEntry[Boolean]] = + Some(CometConf.COMET_NATIVE_ARROW_PYTHON_UDF_ENABLED) + + override def getSupportLevel(op: ArrowEvalPythonExec): SupportLevel = { + if (!NativeBase.supportsPythonUdf()) { + return Unsupported(Some("Native library lacks the python-udf feature")) + } + if (op.evalType != PythonEvalType.SQL_SCALAR_ARROW_UDF) { + return Unsupported(Some("Only scalar @arrow_udf is supported")) + } + if (op.udfs.isEmpty || op.udfs.length != op.resultAttrs.length) { + return Unsupported(Some("Arrow UDF functions and result attributes do not match")) + } + if (op.conf.arrowUseLargeVarTypes) { + return Unsupported(Some("Arrow UDF large variable types are not supported in-process")) + } + if (op.conf.pythonUDFProfiler.nonEmpty) { + return Unsupported(Some("Arrow UDF profiling is not supported in-process")) + } + if (op.udfs.exists(_.children.exists(expr => !hasCompatibleArrowSchema(expr.dataType))) || + op.resultAttrs.exists(attr => !hasCompatibleArrowSchema(attr.dataType))) { + return Unsupported(Some("Arrow UDF type is outside the verified native Arrow schema set")) + } + op.udfs.collectFirst { + case udf if udf.func.broadcastVars != null && !udf.func.broadcastVars.isEmpty => + "Arrow UDF broadcast variables are not supported in-process" + case udf if udf.func.pythonIncludes != null && !udf.func.pythonIncludes.isEmpty => + "Arrow UDF Python includes are not supported in-process" + case udf if hasUnsupportedEnvironment(udf.func.envVars) => + "Arrow UDF Python environment overrides are not supported in-process" + case udf if udf.children.exists(_.find(_.isInstanceOf[PythonUDF]).nonEmpty) => + "Chained Arrow UDFs are not supported in-process" + } match { + case Some(reason) => Unsupported(Some(reason)) + case None => Compatible(None) + } + } + + override def convert( + op: ArrowEvalPythonExec, + builder: Operator.Builder, + childOp: Operator*): Option[Operator] = { + if (childOp.length != 1) { + withFallbackReason(op, "Arrow UDF requires one native child") + return None + } + + val functions = op.udfs.zip(op.resultAttrs).map { case (udf, attr) => + val args: Seq[(Expression, String)] = udf.children.map { + case NamedArgumentExpression(key, value) => (value, key) + case other => (other, "") + } + val argProtos = args.map { case (expr, _) => + QueryPlanSerde.exprToProto(expr, op.child.output) + } + val returnType = QueryPlanSerde.serializeDataType(attr.dataType) + if (argProtos.exists(_.isEmpty) || returnType.isEmpty) { + None + } else { + Some( + OperatorOuterClass.ArrowPythonFunction + .newBuilder() + .setCommand(ByteString.copyFrom(udf.func.command.toArray)) + .addAllArgs(argProtos.map(_.get).asJava) + .addAllArgNames(args.map(_._2).asJava) + .setReturnType(returnType.get) + .setReturnName(attr.name) + .setPythonVersion(udf.func.pythonVer) + .build()) + } + } + if (functions.exists(_.isEmpty)) { + withFallbackReason(op, "Arrow UDF argument or return type cannot be serialized") + None + } else { + val native = OperatorOuterClass.ArrowPythonUdf + .newBuilder() + .addAllFunctions(functions.map(_.get).asJava) + .setMaxRecordsPerBatch(op.conf.arrowMaxRecordsPerBatch) Review Comment: Thanks for the detailed reproduction. Fixed in `c73d8b599`: Scala now passes `arrowMaxBytesPerBatch` to the native operator. Rust splits all UDF arguments at the same boundary when either the row or byte limit is reached, counting Arrow values, offsets, and validity buffers. I added Rust tests and a real PySpark `@arrow_udf` test with a 16-byte limit and four `long` values. The Spark 4.1 and 4.2 PyArrow CI jobs pass. ########## spark/src/test/resources/pyspark/test_pyarrow_udf.py: ########## @@ -112,6 +112,50 @@ def _assert_plan_matches_mode( ) +def test_scalar_arrow_udf_uses_native_path_and_spark_batch_limit(spark): + # This must use PySpark's real UDF wrapper: it populates the default + # PYTHONHASHSEED entry that a hand-built SimplePythonFunction omits. + from pyspark.sql.pandas import functions as pandas_functions + + if not hasattr(pandas_functions, "arrow_udf"): + pytest.skip("scalar arrow_udf requires Spark 4.1 or later") + + @pandas_functions.arrow_udf("long") + def batch_length(values): + return pa.array([len(values)] * len(values), type=pa.int64()) + + @pandas_functions.arrow_udf("long") + def string_hash(values): + return pa.array([hash(value) for value in values.to_pylist()], type=pa.int64()) + + source = spark.range(1, 5, 1, 1) + spark.conf.set("spark.sql.adaptive.enabled", "false") + spark.conf.set("spark.sql.execution.arrow.maxRecordsPerBatch", "2") + spark.conf.set("spark.comet.sparkToColumnar.enabled", "true") + try: + spark.conf.set("spark.comet.exec.nativeArrowPythonUDF.enabled", "false") + spark_rows = source.select(batch_length("id")).collect() Review Comment: Thanks, I confirmed the Spark 4.2 failure. The reference query now runs with `spark.comet.enabled=false` and checks that its plan contains no Comet operator. The test restores Comet before the native query and retains the native-plan and two-row batch assertions. The Spark 4.2 PyArrow CI job now passes. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
