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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowBatchExporter.scala:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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. A batch 
is evaluated
+ *    once, also if `evaluate` fails.
+ *
+ * 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`, after which the exporter cannot start another 
batch.
+ *
+ * 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
+ * with that lock held too and not while Python runs, by the consumer or by 
the task
+ * completion listener (see 
[[InProcessArrowEvalPythonEvaluatorFactory.IteratorResources]]).
+ * Only its first call has an effect.
+ *
+ * @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 hideTraceback passed to `session.register`, like the three 
parameters that follow:
+ *                      whether Python hides the traceback of a failed UDF
+ * @param simplifiedTraceback whether Python simplifies the traceback of a 
failed UDF
+ * @param tracebackWithLocals whether the traceback of a failed UDF includes 
local variables
+ * @param fullValidation whether Python fully validates the Arrow result of 
each UDF
+ * @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,
+    simplifiedTraceback: Boolean,
+    tracebackWithLocals: Boolean,
+    fullValidation: Boolean,
+    metrics: Map[String, SQLMetric],
+    context: TaskContext) extends AutoCloseable {
+  import InProcessArrowBatchExporter.{dataBytes, roundedDensity, PythonCall}
+
+  private val inputOrdinals = argMetas.map(_.map(_.offset))
+  private val handles = functions.map(_ => UUID.randomUUID().toString)
+  private var registered = false
+  private var writer: ArrowWriter = null
+  private var numRows = 0
+  private var evaluated = false
+  private var closed = false
+  private val results = ArrayBuffer.empty[ArrowColumnVector]
+
+  /** The number of rows written to the current batch. */
+  def rowCount: Int = numRows
+
+  /** The bytes of the rows written to the current batch. */
+  def sizeInBytes: Long = writer.sizeInBytes()
+
+  /** Releases the previous batch, if any, and starts an empty one. */
+  def startBatch(): Unit = {
+    assert(!closed, "The exporter is closed")
+    // Each batch needs buffers of its own, which Python may retain, but 
sizing flat vectors
+    // like the previous batch's avoids growing them from Arrow's defaults row 
by row.
+    // Nested vectors keep the defaults, since Arrow sizes their children per 
record.
+    val capacities = if (writer == null) Seq.empty else {
+      writer.root.getFieldVectors.asScala.map(v => (v.getValueCount, 
dataBytes(v))).toSeq
+    }
+    closeBatch()
+    evaluated = false
+    val root = VectorSchemaRoot.create(arrowSchema, ArrowUtils.rootAllocator)
+    capacities.zip(root.getFieldVectors.asScala).foreach { case ((count, 
bytes), v) =>
+      if (count > 0) v match {
+        case v: BaseFixedWidthVector => v.setInitialCapacity(count)
+        case v: BaseVariableWidthVector if bytes > 0 =>
+          v.setInitialCapacity(count, roundedDensity(count, bytes, 
Int.MaxValue))
+        case v: BaseLargeVariableWidthVector if bytes > 0 =>
+          v.setInitialCapacity(count, roundedDensity(count, bytes, 
Long.MaxValue))
+        case _ =>
+      }
+    }
+    writer = try {
+      ArrowWriter.create(root)
+    } catch {
+      case t: Throwable => Utils.tryWithSafeFinally { throw t } { root.close() 
}
+    }
+  }
+
+  /** Adds a row of UDF arguments to the current batch. */
+  def write(row: InternalRow): Unit = {

Review Comment:
   Added the assertion as suggested, and the state test covers `write` before a 
batch, after `evaluate` and after `close`. I re-ran a local fill 
micro-benchmark and saw no slowdown.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessArrowBatchExporterSuite.scala:
##########
@@ -0,0 +1,247 @@
+/*
+ * 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 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
+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)
+    } finally {
+      try { 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 = 
readBackInput,
+      hideTraceback = false, simplifiedTraceback = false, tracebackWithLocals 
= false,
+      fullValidation = true, metrics = metrics, context = context)
+  }
+
+  private def function(): PythonFunction = emptyFunction()
+
+  private def fill(exporter: InProcessArrowBatchExporter, ids: Range, value: 
String): Unit = {
+    exporter.startBatch()
+    assert(exporter.rowCount == 0)
+    ids.foreach(i => exporter.write(InternalRow(i.toLong, 
UTF8String.fromString(value))))
+    assert(exporter.rowCount == ids.size && exporter.sizeInBytes > 0)
+  }
+
+  test("a batch without UDFs reads its input back, and counts its rows and 
bytes") {
+    val metrics = allMetrics()
+    val calls = new Calls(metrics)
+    val exporter = this.exporter(metrics)
+    fill(exporter, 0 until 5, "a")
+    val sent = exporter.sizeInBytes
+    val rows = exporter.evaluate(calls.run).map(r => (r.getLong(0), 
r.getString(1))).toSeq
+    assert(rows == (0 until 5).map(i => (i.toLong, "a")))
+    assert(metrics("pythonDataSent").value == sent)
+    assert(metrics("pythonNumRowsReceived").value == 5 && 
calls.charged.isEmpty)
+
+    // The next batch replaces the previous one.
+    fill(exporter, 5 until 8, "bc")
+    assert(exporter.evaluate(calls.run).map(_.getLong(0)).toSeq == Seq(5L, 6L, 
7L))
+    assert(metrics("pythonNumRowsReceived").value == 8)
+    exporter.close()
+  }
+
+  test("a batch that is not read back returns rows of the results only") {
+    val metrics = allMetrics()
+    val exporter = this.exporter(metrics, readBackInput = false)
+    fill(exporter, 0 until 5, "a")
+    val rows = exporter.evaluate(new Calls(metrics).run).toSeq
+    assert(rows.size == 5 && rows.forall(_.numFields == 0))
+    exporter.close()
+  }
+
+  test("closing releases a batch in any state, and is idempotent") {
+    val metrics = allMetrics()
+    val unused = exporter(metrics)
+    unused.close()
+    unused.close()
+
+    val filling = exporter(metrics)
+    fill(filling, 0 until 100, "abc")
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory > allocatedBefore)
+    filling.close()
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory == allocatedBefore)
+    filling.close()
+
+    val evaluated = exporter(metrics)
+    fill(evaluated, 0 until 100, "abc")
+    evaluated.evaluate(new Calls(metrics).run)

Review Comment:
   It is covered by 
`test_arrow_memory_is_released_on_success_limit_and_failure` in 
`pyspark.sql.tests.test_inprocess_udf`, which checks the allocator after 
success, an early stop by a limit, and a second UDF that fails after the first 
one returned its result. I noted that in the doc of this suite.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessArrowBatchExporterSuite.scala:
##########
@@ -0,0 +1,247 @@
+/*
+ * 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 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
+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)
+    } finally {
+      try { 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 = 
readBackInput,
+      hideTraceback = false, simplifiedTraceback = false, tracebackWithLocals 
= false,
+      fullValidation = true, metrics = metrics, context = context)
+  }
+
+  private def function(): PythonFunction = emptyFunction()
+
+  private def fill(exporter: InProcessArrowBatchExporter, ids: Range, value: 
String): Unit = {
+    exporter.startBatch()
+    assert(exporter.rowCount == 0)
+    ids.foreach(i => exporter.write(InternalRow(i.toLong, 
UTF8String.fromString(value))))
+    assert(exporter.rowCount == ids.size && exporter.sizeInBytes > 0)
+  }
+
+  test("a batch without UDFs reads its input back, and counts its rows and 
bytes") {
+    val metrics = allMetrics()
+    val calls = new Calls(metrics)
+    val exporter = this.exporter(metrics)
+    fill(exporter, 0 until 5, "a")
+    val sent = exporter.sizeInBytes
+    val rows = exporter.evaluate(calls.run).map(r => (r.getLong(0), 
r.getString(1))).toSeq
+    assert(rows == (0 until 5).map(i => (i.toLong, "a")))
+    assert(metrics("pythonDataSent").value == sent)
+    assert(metrics("pythonNumRowsReceived").value == 5 && 
calls.charged.isEmpty)
+
+    // The next batch replaces the previous one.
+    fill(exporter, 5 until 8, "bc")
+    assert(exporter.evaluate(calls.run).map(_.getLong(0)).toSeq == Seq(5L, 6L, 
7L))
+    assert(metrics("pythonNumRowsReceived").value == 8)
+    exporter.close()
+  }
+
+  test("a batch that is not read back returns rows of the results only") {
+    val metrics = allMetrics()
+    val exporter = this.exporter(metrics, readBackInput = false)
+    fill(exporter, 0 until 5, "a")
+    val rows = exporter.evaluate(new Calls(metrics).run).toSeq
+    assert(rows.size == 5 && rows.forall(_.numFields == 0))
+    exporter.close()
+  }
+
+  test("closing releases a batch in any state, and is idempotent") {
+    val metrics = allMetrics()
+    val unused = exporter(metrics)
+    unused.close()
+    unused.close()
+
+    val filling = exporter(metrics)
+    fill(filling, 0 until 100, "abc")
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory > allocatedBefore)
+    filling.close()
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory == allocatedBefore)
+    filling.close()
+
+    val evaluated = exporter(metrics)
+    fill(evaluated, 0 until 100, "abc")
+    evaluated.evaluate(new Calls(metrics).run)
+    evaluated.close()
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory == allocatedBefore)
+    assert(evaluated.rowCount == 0)
+  }
+
+  test("a batch is evaluated once, and a closed exporter starts no batch") {
+    val metrics = allMetrics()
+    val calls = new Calls(metrics)
+    val exporter = this.exporter(metrics)
+    // There is no batch before the first one is started.
+    intercept[AssertionError](exporter.evaluate(calls.run))
+    fill(exporter, 0 until 5, "a")
+    exporter.evaluate(calls.run)
+    intercept[AssertionError](exporter.evaluate(calls.run))
+    assert(metrics("pythonNumRowsReceived").value == 5)
+    // The next batch can be evaluated again.
+    fill(exporter, 0 until 3, "a")
+    exporter.evaluate(calls.run)
+    assert(metrics("pythonNumRowsReceived").value == 8)
+    exporter.close()
+    intercept[AssertionError](exporter.startBatch())
+    intercept[AssertionError](exporter.evaluate(calls.run))
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory == allocatedBefore)
+  }
+
+  test("a failed registration is released by close") {
+    val metrics = allMetrics()
+    val calls = new Calls(metrics)
+    val exporter = this.exporter(metrics, Seq(function(), function()))
+    fill(exporter, 0 until 5, "a")
+    // The session has no interpreter, so the first registration fails once it 
is recorded.
+    intercept[NullPointerException](exporter.evaluate(calls.run))
+    assert(calls.charged == Seq("pythonInitTime"))
+    assert(metrics("pythonDataSent").value == 0 && 
metrics("pythonNumRowsReceived").value == 0)
+    exporter.close()
+    // The session terminates only once every registration is released.
+    session.shutdown()
+    assert(session.isTerminated)
+  }
+
+  test("a call into Python that is refused stops the batch before anything is 
exported") {
+    val metrics = allMetrics()
+    val exporter = this.exporter(metrics, Seq(function()))
+    fill(exporter, 0 until 5, "a")
+    val e = intercept[NoSuchElementException] {
+      exporter.evaluate((_, _) => throw new NoSuchElementException("closed"))
+    }
+    assert(e.getMessage == "closed" && metrics("pythonDataSent").value == 0)
+    exporter.close()
+  }
+
+  test("a failed invocation releases the exported inputs") {
+    val metrics = allMetrics()
+    val exporter = this.exporter(metrics, Seq(function(), function()))
+    fill(exporter, 0 until 5, "a")
+    // Registration succeeds without Python, and the first invocation fails 
once its inputs
+    // are exported.
+    val run: InProcessArrowBatchExporter.PythonCall = (metric, _) => {
+      if (metric eq metrics("pythonProcessingTime")) throw new 
IllegalStateException("invoke")
+    }
+    assert(intercept[IllegalStateException](exporter.evaluate(run)).getMessage 
== "invoke")
+    assert(metrics("pythonDataSent").value > 0)
+    assert(metrics("pythonDataReceived").value == 0)
+    assert(metrics("pythonNumRowsReceived").value == 0)
+    exporter.close()
+    // The C Data structs, and the references to the input vectors they held, 
are freed.
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory == allocatedBefore)
+  }
+
+  test("cancellation is checked before each UDF is invoked") {

Review Comment:
   Agreed, renamed to `cancellation is checked before a UDF is invoked`.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessArrowBatchExporterSuite.scala:
##########
@@ -0,0 +1,247 @@
+/*
+ * 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 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
+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)
+    } finally {
+      try { 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 = 
readBackInput,
+      hideTraceback = false, simplifiedTraceback = false, tracebackWithLocals 
= false,
+      fullValidation = true, metrics = metrics, context = context)
+  }
+
+  private def function(): PythonFunction = emptyFunction()
+
+  private def fill(exporter: InProcessArrowBatchExporter, ids: Range, value: 
String): Unit = {
+    exporter.startBatch()
+    assert(exporter.rowCount == 0)
+    ids.foreach(i => exporter.write(InternalRow(i.toLong, 
UTF8String.fromString(value))))
+    assert(exporter.rowCount == ids.size && exporter.sizeInBytes > 0)
+  }
+
+  test("a batch without UDFs reads its input back, and counts its rows and 
bytes") {
+    val metrics = allMetrics()
+    val calls = new Calls(metrics)
+    val exporter = this.exporter(metrics)
+    fill(exporter, 0 until 5, "a")
+    val sent = exporter.sizeInBytes
+    val rows = exporter.evaluate(calls.run).map(r => (r.getLong(0), 
r.getString(1))).toSeq
+    assert(rows == (0 until 5).map(i => (i.toLong, "a")))
+    assert(metrics("pythonDataSent").value == sent)
+    assert(metrics("pythonNumRowsReceived").value == 5 && 
calls.charged.isEmpty)
+
+    // The next batch replaces the previous one.
+    fill(exporter, 5 until 8, "bc")
+    assert(exporter.evaluate(calls.run).map(_.getLong(0)).toSeq == Seq(5L, 6L, 
7L))
+    assert(metrics("pythonNumRowsReceived").value == 8)
+    exporter.close()
+  }
+
+  test("a batch that is not read back returns rows of the results only") {
+    val metrics = allMetrics()
+    val exporter = this.exporter(metrics, readBackInput = false)
+    fill(exporter, 0 until 5, "a")
+    val rows = exporter.evaluate(new Calls(metrics).run).toSeq
+    assert(rows.size == 5 && rows.forall(_.numFields == 0))
+    exporter.close()
+  }
+
+  test("closing releases a batch in any state, and is idempotent") {
+    val metrics = allMetrics()
+    val unused = exporter(metrics)
+    unused.close()
+    unused.close()
+
+    val filling = exporter(metrics)
+    fill(filling, 0 until 100, "abc")
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory > allocatedBefore)
+    filling.close()
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory == allocatedBefore)
+    filling.close()
+
+    val evaluated = exporter(metrics)
+    fill(evaluated, 0 until 100, "abc")
+    evaluated.evaluate(new Calls(metrics).run)
+    evaluated.close()
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory == allocatedBefore)
+    assert(evaluated.rowCount == 0)
+  }
+
+  test("a batch is evaluated once, and a closed exporter starts no batch") {
+    val metrics = allMetrics()
+    val calls = new Calls(metrics)
+    val exporter = this.exporter(metrics)
+    // There is no batch before the first one is started.
+    intercept[AssertionError](exporter.evaluate(calls.run))
+    fill(exporter, 0 until 5, "a")
+    exporter.evaluate(calls.run)
+    intercept[AssertionError](exporter.evaluate(calls.run))
+    assert(metrics("pythonNumRowsReceived").value == 5)
+    // The next batch can be evaluated again.
+    fill(exporter, 0 until 3, "a")
+    exporter.evaluate(calls.run)
+    assert(metrics("pythonNumRowsReceived").value == 8)
+    exporter.close()
+    intercept[AssertionError](exporter.startBatch())
+    intercept[AssertionError](exporter.evaluate(calls.run))
+    assert(ArrowUtils.rootAllocator.getAllocatedMemory == allocatedBefore)
+  }
+
+  test("a failed registration is released by close") {
+    val metrics = allMetrics()
+    val calls = new Calls(metrics)
+    val exporter = this.exporter(metrics, Seq(function(), function()))
+    fill(exporter, 0 until 5, "a")
+    // The session has no interpreter, so the first registration fails once it 
is recorded.

Review Comment:
   Good point, added as suggested.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessArrowBatchExporterSuite.scala:
##########
@@ -0,0 +1,247 @@
+/*
+ * 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 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
+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)
+    } finally {
+      try { 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 = 
readBackInput,
+      hideTraceback = false, simplifiedTraceback = false, tracebackWithLocals 
= false,
+      fullValidation = true, metrics = metrics, context = context)
+  }
+
+  private def function(): PythonFunction = emptyFunction()

Review Comment:
   Removed.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/InProcessArrowEvalPythonEvaluatorFactory.scala:
##########
@@ -55,6 +47,14 @@ import org.apache.spark.util.Utils
  *
  * The evaluator owns its queue, so that cleanup at task completion is 
coordinated with a
  * consumer on another thread, such as a pipelined Python writer or a 
TRANSFORM feed thread.
+ *
+ * The iterator of the evaluator pulls the input rows and returns the output 
rows. It leaves
+ * the rest to three collaborators:
+ *  - [[InProcessArrowBatchExporter]] writes the UDF arguments to Arrow 
batches, exports them
+ *    to Python and imports the results.
+ *  - a row queue buffers the input rows that are joined with the results.

Review Comment:
   Reworded both items.



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