viirya commented on code in PR #60545:
URL: https://github.com/apache/spark/pull/60545#discussion_r4581655710


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowBatchExporter.scala:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.execution.python
+
+import java.util.UUID
+
+import scala.collection.mutable.ArrayBuffer
+import scala.jdk.CollectionConverters._
+
+import org.apache.arrow.c.{ArrowArray, ArrowSchema, BaseStruct}
+import org.apache.arrow.util.AutoCloseables
+import org.apache.arrow.vector.{BaseFixedWidthVector, 
BaseLargeVariableWidthVector, BaseVariableWidthVector, ValueVector, 
VectorSchemaRoot}
+import org.apache.arrow.vector.types.pojo.{Field, Schema}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.api.python.PythonFunction
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.execution.arrow.ArrowWriter
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.execution.python.EvalPythonExec.ArgumentMetadata
+import org.apache.spark.sql.util.ArrowUtils
+import org.apache.spark.sql.vectorized.{ArrowColumnVector, ColumnarBatch, 
ColumnVector}
+import org.apache.spark.unsafe.array.ByteArrayMethods
+import org.apache.spark.util.Utils
+
+/**
+ * Exports batches of UDF arguments to in-process Python over the Arrow C Data 
Interface, and
+ * imports the results of the UDFs. Each batch owns its Arrow buffers, so that 
Python can
+ * safely retain input arrays.
+ *
+ * The exporter holds one batch at a time, which is in one of these states:
+ *  - none: before the first `startBatch`, and after `close`.
+ *  - filling (`startBatch`): `write` adds rows to the batch, counted by 
`rowCount`.
+ *  - evaluated (`evaluate`): the batch was exported and the results of every 
UDF imported.
+ *    The returned rows read the input and result vectors of the batch, and 
are valid until
+ *    the next `startBatch` or `close`, which release those vectors.
+ *
+ * The UDFs are registered with the session before the first batch is 
exported, and released
+ * by `close` if any registration was attempted. A failure leaves the batch 
and the
+ * registrations to `close`.
+ *
+ * The exporter is not thread safe. The consumer of the evaluator's iterator 
calls
+ * `startBatch`, `write` and `evaluate`, with the iterator's lock held. 
`close` is called once,
+ * with that lock held too and not while Python runs, by the consumer or by 
the task
+ * completion listener (see 
[[InProcessArrowEvalPythonEvaluatorFactory.IteratorResources]]).
+ *
+ * @param session the interpreter session to register and invoke the UDFs with
+ * @param functions the Python function of each UDF
+ * @param argMetas the arguments of each UDF, as ordinals of `arrowSchema`
+ * @param expectedFields the Arrow field that the result of each UDF must have
+ * @param arrowSchema the Arrow schema of the UDF arguments, which the written 
rows have
+ * @param readBackInput whether the returned rows start with the input 
columns, read back from
+ *                      the exported input vectors
+ * @param metrics the metrics of `InProcessArrowEvalPythonExec`, except 
`pythonTotalTime`

Review Comment:
   Documented.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowBatchExporter.scala:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.execution.python
+
+import java.util.UUID
+
+import scala.collection.mutable.ArrayBuffer
+import scala.jdk.CollectionConverters._
+
+import org.apache.arrow.c.{ArrowArray, ArrowSchema, BaseStruct}
+import org.apache.arrow.util.AutoCloseables
+import org.apache.arrow.vector.{BaseFixedWidthVector, 
BaseLargeVariableWidthVector, BaseVariableWidthVector, ValueVector, 
VectorSchemaRoot}
+import org.apache.arrow.vector.types.pojo.{Field, Schema}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.api.python.PythonFunction
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.execution.arrow.ArrowWriter
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.execution.python.EvalPythonExec.ArgumentMetadata
+import org.apache.spark.sql.util.ArrowUtils
+import org.apache.spark.sql.vectorized.{ArrowColumnVector, ColumnarBatch, 
ColumnVector}
+import org.apache.spark.unsafe.array.ByteArrayMethods
+import org.apache.spark.util.Utils
+
+/**
+ * Exports batches of UDF arguments to in-process Python over the Arrow C Data 
Interface, and
+ * imports the results of the UDFs. Each batch owns its Arrow buffers, so that 
Python can
+ * safely retain input arrays.
+ *
+ * The exporter holds one batch at a time, which is in one of these states:
+ *  - none: before the first `startBatch`, and after `close`.
+ *  - filling (`startBatch`): `write` adds rows to the batch, counted by 
`rowCount`.
+ *  - evaluated (`evaluate`): the batch was exported and the results of every 
UDF imported.
+ *    The returned rows read the input and result vectors of the batch, and 
are valid until
+ *    the next `startBatch` or `close`, which release those vectors.
+ *
+ * The UDFs are registered with the session before the first batch is 
exported, and released
+ * by `close` if any registration was attempted. A failure leaves the batch 
and the
+ * registrations to `close`.
+ *
+ * The exporter is not thread safe. The consumer of the evaluator's iterator 
calls
+ * `startBatch`, `write` and `evaluate`, with the iterator's lock held. 
`close` is called once,
+ * with that lock held too and not while Python runs, by the consumer or by 
the task
+ * completion listener (see 
[[InProcessArrowEvalPythonEvaluatorFactory.IteratorResources]]).
+ *
+ * @param session the interpreter session to register and invoke the UDFs with
+ * @param functions the Python function of each UDF
+ * @param argMetas the arguments of each UDF, as ordinals of `arrowSchema`
+ * @param expectedFields the Arrow field that the result of each UDF must have
+ * @param arrowSchema the Arrow schema of the UDF arguments, which the written 
rows have
+ * @param readBackInput whether the returned rows start with the input 
columns, read back from
+ *                      the exported input vectors
+ * @param metrics the metrics of `InProcessArrowEvalPythonExec`, except 
`pythonTotalTime`
+ * @param context the task context, checked for cancellation before each UDF 
is invoked
+ */
+private[python] class InProcessArrowBatchExporter(
+    session: InProcessPythonRuntime.InterpreterSession,
+    functions: Seq[PythonFunction],
+    argMetas: Array[Array[ArgumentMetadata]],
+    expectedFields: Seq[Field],
+    arrowSchema: Schema,
+    readBackInput: Boolean,
+    hideTraceback: Boolean,

Review Comment:
   Used named arguments at both call sites for now. I would leave grouping the 
parameters to a follow-up, to keep this PR close to a move.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessArrowBatchExporterSuite.scala:
##########
@@ -0,0 +1,215 @@
+/*
+ * 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.execution.python
+
+import java.util.Collections
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.arrow.vector.types.pojo.Field
+
+import org.apache.spark.{SparkFunSuite, TaskContext, TaskKilledException}
+import org.apache.spark.api.python.{PythonFunction, SimplePythonFunction}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.execution.python.EvalPythonExec.ArgumentMetadata
+import org.apache.spark.sql.types._
+import org.apache.spark.sql.util.ArrowUtils
+import org.apache.spark.unsafe.types.UTF8String
+
+/** Batches of [[InProcessArrowBatchExporter]] and their release, which need 
no Python. */
+class InProcessArrowBatchExporterSuite extends SparkFunSuite {
+  import InProcessEvaluatorTestUtils._
+
+  // This session has no interpreter: registrations fail after the session 
recorded them.
+  private var session: InProcessPythonRuntime.InterpreterSession = _
+  private var allocatedBefore = 0L
+
+  override def beforeEach(): Unit = {
+    super.beforeEach()
+    session = new InProcessPythonRuntime.InterpreterSession()
+    allocatedBefore = ArrowUtils.rootAllocator.getAllocatedMemory
+  }
+
+  override def afterEach(): Unit = {
+    try {
+      assert(ArrowUtils.rootAllocator.getAllocatedMemory == allocatedBefore)
+      session.shutdown()
+    } finally {
+      super.afterEach()
+    }
+  }
+
+  private val schema = new StructType().add("id", LongType).add("s", 
StringType)
+
+  /** The calls into Python that an exporter made, by the metric each was 
charged to. */
+  private class Calls(metrics: Map[String, SQLMetric]) {
+    val charged = ArrayBuffer.empty[String]
+    val run: InProcessArrowBatchExporter.PythonCall = (metric, call) => {
+      charged += metrics.find(_._2 eq metric).get._1
+      metric += call()
+    }
+  }
+
+  private def exporter(
+      metrics: Map[String, SQLMetric],
+      functions: Seq[PythonFunction] = Seq.empty,
+      readBackInput: Boolean = true,
+      context: TaskContext = TaskContext.empty()): InProcessArrowBatchExporter 
= {
+    val fields: Seq[Field] =
+      functions.map(_ => ArrowUtils.toArrowField("result", LongType, true, 
"UTC"))
+    new InProcessArrowBatchExporter(session, functions,
+      functions.map(_ => Array(ArgumentMetadata(0, None))).toArray, fields,
+      ArrowUtils.toArrowSchema(schema, "UTC", false), readBackInput,
+      false, false, false, true, metrics, context)
+  }
+
+  private def function(): PythonFunction = SimplePythonFunction(

Review Comment:
   Moved to `InProcessEvaluatorTestUtils.emptyFunction()` and reused in both 
suites.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowBatchExporter.scala:
##########
@@ -0,0 +1,246 @@
+/*
+ * 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.
+ */
+
+

Review Comment:
   Fixed in both files.



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

Reply via email to