sunchao commented on code in PR #6130: URL: https://github.com/apache/datafusion-comet/pull/6130#discussion_r4103168220
########## 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: [P2] Could this preserve `spark.sql.execution.arrow.maxBytesPerBatch` alongside the row cap? With a byte cap of `16`, a row cap of `10000`, and four `long` values, Spark sends two-row batches to Python. Native execution sends all four because only the row cap reaches the operator. A UDF that rejects `a.nbytes > 16` therefore succeeds in Spark but fails natively with `ValueError: configured byte cap exceeded: 32 > 16`. This breaks workloads using the byte limit to satisfy Python library or memory constraints. Serialize and enforce the byte limit on UDF arguments, or fall back when it cannot be honored. Evidence: Ran Spark 4.1.3 on `spark.range(1, 5, 1, 1)` with `arrow.maxRecordsPerBatch=10000` and `arrow.maxBytesPerBatch=16`. The UDF checks `a.nbytes > 16` and otherwise returns `a`. Spark returned [1, 2, 3, 4], with observed batch lengths [2, 2, 2, 2]. An isolated Rust harness importing this head’s operator and bridge used the same PySpark-cloudpickled command and one four-row child batch. It produced the stated 32-byte error. Setting the native row cap to 2 succeeded. Spark’s `BatchedPythonArrowInput.writeSizedBatch` enforces both limits. Reproduction files: `/tmp/comet-6130-4830-harness/reference.py` and `/tmp/comet-6130-4830-harness/tests/operator.rs`. ########## 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: [P2] Could the reference query run with Comet disabled, restoring it before the native query? Disabling only `nativeArrowPythonUDF.enabled` leaves `sparkToColumnar.enabled=true`. On Spark 4.2, the reference consequently uses Spark’s columnar Python runner, which forwards the four-row input batch without applying the row cap. The reference returns [4, 4, 4, 4], while the corrected native operator returns [2, 2, 2, 2]. This makes the new test fail and blocks `Required Checks`. Use a row-based Spark reference while retaining the native-plan and two-row-cap assertions. Evidence: Exact-head job https://github.com/apache/datafusion-comet/actions/runs/36100068127/job/107961195675 fails at line 142 with `Row(batch_length(id)=2) != Row(batch_length(id)=4)`. It reports 1 failed and 133 passed. Spark v4.2.0’s `ArrowEvalPythonExec` selects columnar execution for a columnar child, and `ColumnarArrowPythonInput.writeRowByRow` writes the whole batch without the `BatchedPythonArrowInput` limits. The corresponding Spark 4.1 job passes this test. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
