dongjoon-hyun commented on code in PR #60545:
URL: https://github.com/apache/spark/pull/60545#discussion_r4581840367


##########
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:
   `write` doesn't check the batch state, while `startBatch` and `evaluate` do 
now. After `evaluate`, it still appends the row to the exported input vectors 
and increments `numRows`, but the row never reaches Python: the batch cannot be 
evaluated again, and the next `startBatch` releases it. In the factory's 
buffered mode, the queue would also hold a row without a result, which would 
shift the rows joined with the next results. The factory doesn't reach this, 
but since the class doc defines the states, shall we assert the filling state 
here too? If a per-row check is a concern, documenting that `write` requires a 
batch that was not evaluated yet would also work.
   
   ```scala
   def write(row: InternalRow): Unit = {
     assert(writer != null && !evaluated, "The exporter has no batch to write 
to")
     writer.write(row)
     numRows += 1
   }
   ```



##########
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:
   With a single UDF, this test also passes if the check runs once per batch, 
e.g. if `context.killTaskIfInterrupted()` moved out of the `handles` loop to 
right after `writer.finish()`. So it doesn't verify the "each UDF" part of its 
name. Since getting past the first invocation needs Python, how about naming 
the test after what it checks, e.g. `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)

Review Comment:
   Since this suite runs without Python, no test imports a UDF result, so 
`results` is always empty, also for this evaluated batch. A regression in 
releasing the imported results, e.g. dropping `resources ++= results` from 
`closeBatch()`, or in releasing the results of earlier UDFs when a later UDF 
fails, would still pass this suite. Is this covered by a test that runs Python? 
If not, shall we mention in the suite that the release of the results needs 
Python to be tested?



##########
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:
   nit: this only renames `emptyFunction()`. Shall we call `emptyFunction()` 
directly and remove this?



##########
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:
   This relies on `InterpreterSession.register` recording the handle before it 
fails on the missing interpreter. The test doesn't check that, so if the 
session ended up with no registration, `isTerminated` would hold even if 
`close()` released nothing. How about asserting that the failed registration 
keeps the session from terminating until `close()`?
   
   ```scala
   // The failed registration keeps the session from terminating until close 
releases it.
   session.shutdown(0)
   assert(!session.isTerminated)
   exporter.close()
   session.shutdown()
   assert(session.isTerminated)
   ```



##########
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:
   nit: in the `ReadBack` mode there is no row queue (`queue` is `null`), since 
the input rows are read back from the exported input vectors. Shall we qualify 
this item, e.g. "unless the input rows are read back from Arrow, a row queue 
buffers them to be joined with the results", and "both" in the next item 
accordingly (e.g. "the exporter and the queue, if any")?



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