dongjoon-hyun commented on code in PR #60545: URL: https://github.com/apache/spark/pull/60545#discussion_r4581405125
########## 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) Review Comment: If this assertion fails, e.g. after a test fails before `exporter.close()`, `session.shutdown()` is skipped and the session is never shut down. `InProcessPythonRuntimeSuite` uses `try { runtime.shutdown() } finally { super.afterEach() }` for this. Shall we run `session.shutdown()` in its own `finally`? ```scala override def afterEach(): Unit = { try { assert(ArrowUtils.rootAllocator.getAllocatedMemory == allocatedBefore) } finally { try { session.shutdown() } finally { super.afterEach() } } } ``` ########## 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( + Seq.empty, Collections.emptyMap[String, String](), Collections.emptyList[String](), + "", "3.12", Collections.emptyList(), null) + + 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 for batches") { + 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) + } + + 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() + session.shutdown() + assert(session.isTerminated) + } + + test("cancellation is checked before each UDF is invoked") { Review Comment: None of the tests fails a call into Python after the inputs are exported: the refused test throws on the first registration call, and this test is killed before any struct is allocated. So a regression in the `AutoCloseables.close(structs)` cleanup or in `track` would not be caught. Since the registration can be faked as here, how about a test whose `PythonCall` throws only for `pythonProcessingTime`, relying on the allocation check in `afterEach`? ```scala val run: InProcessArrowBatchExporter.PythonCall = (metric, _) => { if (metric eq metrics("pythonProcessingTime")) throw new IllegalStateException("invoke") } ``` ########## 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, + 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 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 = { + // 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() + 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() } + } + numRows = 0 + } + + /** Adds a row of UDF arguments to the current batch. */ + def write(row: InternalRow): Unit = { + writer.write(row) + numRows += 1 + } + + /** + * Registers the UDFs if this is the first batch, exports the arguments of each UDF, + * invokes it, and imports its result. Returns the rows of the batch: the input columns if + * `readBackInput`, followed by the result of each UDF. + * + * @param python runs each call into Python + */ + def evaluate(python: PythonCall): Iterator[InternalRow] = { + if (!registered) { + // Mark before registering so failure after any registration still cleans up. + registered = true + functions.indices.foreach { i => + val func = functions(i) + python(metrics("pythonInitTime"), () => session.register(handles(i), + func.command.toArray, expectedFields(i), func.pythonVer, hideTraceback, + simplifiedTraceback, tracebackWithLocals, fullValidation)) + } + } + writer.finish() + metrics("pythonDataSent") += writer.sizeInBytes() + + handles.indices.foreach { udfIndex => + val handle = handles(udfIndex) + val ordinals = inputOrdinals(udfIndex) + context.killTaskIfInterrupted() + // Register each acquired resource immediately, including partially exported + // inputs and results of earlier UDFs if a later UDF throws. + val structs = ArrayBuffer.empty[AutoCloseable] + def track[S <: BaseStruct](struct: S): S = { + val closer: AutoCloseable = () => InProcessArrowBridge.closeStruct(struct) + structs += closer + struct + } + def array(): ArrowArray = track(ArrowArray.allocateNew(ArrowUtils.rootAllocator)) + def schema(): ArrowSchema = track(ArrowSchema.allocateNew(ArrowUtils.rootAllocator)) + Utils.tryWithSafeFinally { + val inArrays = ordinals.map(_ => array()) + val inSchemas = ordinals.map(_ => schema()) + val outArray = array() + val outSchema = schema() + ordinals.indices.foreach { i => + InProcessArrowBridge.exportColumn( + writer.root.getVector(ordinals(i)), inArrays(i), inSchemas(i)) + } + python(metrics("pythonProcessingTime"), () => session.invoke( + handle, + inArrays.map(_.memoryAddress()).toArray, + inSchemas.map(_.memoryAddress()).toArray, + outArray.memoryAddress(), outSchema.memoryAddress(), + numRows, argMetas(udfIndex).map(_.name.getOrElse("")))) + results += InProcessArrowBridge.cdiToColumn( + outArray, outSchema, Some(expectedFields(udfIndex))) + metrics("pythonDataReceived") += results.last.getValueVector.getBufferSize + } { + AutoCloseables.close(structs.asJava) + } + } + + metrics("pythonNumRowsReceived") += numRows + // Input vectors are closed with the writer's root, not with the results. + val inputs = if (readBackInput) { + writer.root.getFieldVectors.asScala.map(new ArrowColumnVector(_)) + } else { + Nil + } + val columns = (inputs ++ results).toArray[ColumnVector] + new ColumnarBatch(columns, numRows).rowIterator().asScala + } + + /** Releases the current batch, if any, and the registrations of the UDFs. */ + override def close(): Unit = { Review Comment: `close()` leaves `registered = true`, so the exporter is not terminal, although the class doc lists "after `close`" under the none state, from which `startBatch` is allowed. If `startBatch()`, `write()` and `evaluate()` were called after `close()`, the registration would be skipped and `session.invoke` would run with handles that `close()` already released. The current factory doesn't reach this thanks to `IteratorResources`, but shall we either make `close()` terminal (e.g. a `closed` flag) or document that the exporter cannot be reused after `close`? ########## 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, + 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 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 = { + // 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() + 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() } + } + numRows = 0 + } + + /** Adds a row of UDF arguments to the current batch. */ + def write(row: InternalRow): Unit = { + writer.write(row) + numRows += 1 + } + + /** + * Registers the UDFs if this is the first batch, exports the arguments of each UDF, + * invokes it, and imports its result. Returns the rows of the batch: the input columns if + * `readBackInput`, followed by the result of each UDF. + * + * @param python runs each call into Python + */ + def evaluate(python: PythonCall): Iterator[InternalRow] = { + if (!registered) { + // Mark before registering so failure after any registration still cleans up. + registered = true + functions.indices.foreach { i => + val func = functions(i) + python(metrics("pythonInitTime"), () => session.register(handles(i), + func.command.toArray, expectedFields(i), func.pythonVer, hideTraceback, + simplifiedTraceback, tracebackWithLocals, fullValidation)) + } + } + writer.finish() + metrics("pythonDataSent") += writer.sizeInBytes() + + handles.indices.foreach { udfIndex => + val handle = handles(udfIndex) + val ordinals = inputOrdinals(udfIndex) + context.killTaskIfInterrupted() + // Register each acquired resource immediately, including partially exported + // inputs and results of earlier UDFs if a later UDF throws. + val structs = ArrayBuffer.empty[AutoCloseable] + def track[S <: BaseStruct](struct: S): S = { + val closer: AutoCloseable = () => InProcessArrowBridge.closeStruct(struct) + structs += closer + struct + } + def array(): ArrowArray = track(ArrowArray.allocateNew(ArrowUtils.rootAllocator)) + def schema(): ArrowSchema = track(ArrowSchema.allocateNew(ArrowUtils.rootAllocator)) + Utils.tryWithSafeFinally { + val inArrays = ordinals.map(_ => array()) + val inSchemas = ordinals.map(_ => schema()) + val outArray = array() + val outSchema = schema() + ordinals.indices.foreach { i => + InProcessArrowBridge.exportColumn( + writer.root.getVector(ordinals(i)), inArrays(i), inSchemas(i)) + } + python(metrics("pythonProcessingTime"), () => session.invoke( + handle, + inArrays.map(_.memoryAddress()).toArray, + inSchemas.map(_.memoryAddress()).toArray, + outArray.memoryAddress(), outSchema.memoryAddress(), + numRows, argMetas(udfIndex).map(_.name.getOrElse("")))) + results += InProcessArrowBridge.cdiToColumn( + outArray, outSchema, Some(expectedFields(udfIndex))) + metrics("pythonDataReceived") += results.last.getValueVector.getBufferSize + } { + AutoCloseables.close(structs.asJava) + } + } + + metrics("pythonNumRowsReceived") += numRows + // Input vectors are closed with the writer's root, not with the results. + val inputs = if (readBackInput) { + writer.root.getFieldVectors.asScala.map(new ArrowColumnVector(_)) + } else { + Nil + } + val columns = (inputs ++ results).toArray[ColumnVector] + new ColumnarBatch(columns, numRows).rowIterator().asScala + } + + /** Releases the current batch, if any, and the registrations of the UDFs. */ + override def close(): Unit = { + Utils.tryWithSafeFinally { + closeBatch() + } { + if (registered) session.release(handles) + } + } + + private def closeBatch(): Unit = { + val resources = ArrayBuffer.empty[AutoCloseable] + resources ++= results + results.clear() + if (writer != null) { + resources += writer.root + writer = null + } + AutoCloseables.close(resources.asJava) + } +} + +private[python] object InProcessArrowBatchExporter { + /** + * Runs a call into Python, which returns the nanoseconds it took, and adds them to the + * metric. It may throw instead of running the call, or after it, to stop the evaluation. + */ + type PythonCall = (SQLMetric, () => Long) => Unit Review Comment: The doc says a `PythonCall` may throw instead of running the call, but nothing prevents it from returning without running it, and then `evaluate` continues. If the registration is skipped, `invoke` runs with an unregistered handle. If the invocation is skipped, `cdiToColumn` imports the unfilled `outArray` and `outSchema`. Could we state explicitly that a `PythonCall` must either run `call` or throw? (The cancellation test skips the registration call on purpose, which is fine for a test fake.) ########## 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: These four Booleans are only forwarded to `session.register`. They make 12 constructor parameters, with five positional Booleans in a row at the call sites (e.g. `readBackInput, false, false, false, true` in the test), and a swapped order still compiles. How about named arguments at the call sites, or grouping them (e.g. a small case class, or a registration closure built by the factory)? ########## 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: This is the same empty `SimplePythonFunction` as the one in `InProcessPythonRuntimeSuite` (`evaluators retain the generation captured before consuming any input`). Shall we move it to `InProcessEvaluatorTestUtils`, which already collects the fixtures of in-process evaluator tests that need no Python, and reuse it in both suites? ########## 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( + Seq.empty, Collections.emptyMap[String, String](), Collections.emptyList[String](), + "", "3.12", Collections.emptyList(), null) + + 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 for batches") { + 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) + } + + 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() + session.shutdown() + assert(session.isTerminated) Review Comment: This assertion holds even if `close()` releases nothing. The `PythonCall` throws before `session.register` runs, so the session has no registrations and `shutdown()` terminates it either way. Since the previous test already covers the release of a failed registration, shall we remove these two lines? ########## 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, + 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 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 = { + // 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() + 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() } + } + numRows = 0 + } + + /** Adds a row of UDF arguments to the current batch. */ + def write(row: InternalRow): Unit = { + writer.write(row) + numRows += 1 + } + + /** + * Registers the UDFs if this is the first batch, exports the arguments of each UDF, + * invokes it, and imports its result. Returns the rows of the batch: the input columns if + * `readBackInput`, followed by the result of each UDF. + * + * @param python runs each call into Python + */ + def evaluate(python: PythonCall): Iterator[InternalRow] = { Review Comment: `evaluate` doesn't check that the batch is in the filling state. Calling it twice on the same batch would call `writer.finish()` again, append a second set of result vectors to `results` (so the rows get duplicated result columns), and count `pythonDataSent` and `pythonNumRowsReceived` twice. Since the class doc defines the states, how about asserting the state here? ########## 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, + 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 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 = { + // 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() + 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() } + } + numRows = 0 + } + + /** Adds a row of UDF arguments to the current batch. */ + def write(row: InternalRow): Unit = { + writer.write(row) + numRows += 1 + } + + /** + * Registers the UDFs if this is the first batch, exports the arguments of each UDF, + * invokes it, and imports its result. Returns the rows of the batch: the input columns if + * `readBackInput`, followed by the result of each UDF. + * + * @param python runs each call into Python + */ + def evaluate(python: PythonCall): Iterator[InternalRow] = { + if (!registered) { + // Mark before registering so failure after any registration still cleans up. + registered = true + functions.indices.foreach { i => + val func = functions(i) + python(metrics("pythonInitTime"), () => session.register(handles(i), + func.command.toArray, expectedFields(i), func.pythonVer, hideTraceback, + simplifiedTraceback, tracebackWithLocals, fullValidation)) + } + } + writer.finish() + metrics("pythonDataSent") += writer.sizeInBytes() + + handles.indices.foreach { udfIndex => + val handle = handles(udfIndex) + val ordinals = inputOrdinals(udfIndex) + context.killTaskIfInterrupted() + // Register each acquired resource immediately, including partially exported + // inputs and results of earlier UDFs if a later UDF throws. + val structs = ArrayBuffer.empty[AutoCloseable] + def track[S <: BaseStruct](struct: S): S = { + val closer: AutoCloseable = () => InProcessArrowBridge.closeStruct(struct) + structs += closer + struct + } + def array(): ArrowArray = track(ArrowArray.allocateNew(ArrowUtils.rootAllocator)) + def schema(): ArrowSchema = track(ArrowSchema.allocateNew(ArrowUtils.rootAllocator)) + Utils.tryWithSafeFinally { + val inArrays = ordinals.map(_ => array()) + val inSchemas = ordinals.map(_ => schema()) + val outArray = array() + val outSchema = schema() + ordinals.indices.foreach { i => + InProcessArrowBridge.exportColumn( + writer.root.getVector(ordinals(i)), inArrays(i), inSchemas(i)) + } + python(metrics("pythonProcessingTime"), () => session.invoke( + handle, + inArrays.map(_.memoryAddress()).toArray, + inSchemas.map(_.memoryAddress()).toArray, + outArray.memoryAddress(), outSchema.memoryAddress(), + numRows, argMetas(udfIndex).map(_.name.getOrElse("")))) + results += InProcessArrowBridge.cdiToColumn( + outArray, outSchema, Some(expectedFields(udfIndex))) + metrics("pythonDataReceived") += results.last.getValueVector.getBufferSize + } { + AutoCloseables.close(structs.asJava) + } + } + + metrics("pythonNumRowsReceived") += numRows + // Input vectors are closed with the writer's root, not with the results. + val inputs = if (readBackInput) { + writer.root.getFieldVectors.asScala.map(new ArrowColumnVector(_)) + } else { + Nil + } + val columns = (inputs ++ results).toArray[ColumnVector] + new ColumnarBatch(columns, numRows).rowIterator().asScala + } + + /** Releases the current batch, if any, and the registrations of the UDFs. */ + override def close(): Unit = { + Utils.tryWithSafeFinally { + closeBatch() + } { + if (registered) session.release(handles) + } + } + + private def closeBatch(): Unit = { Review Comment: nit: `closeBatch()` doesn't reset `numRows`. In the none state (after `close()`, or when `startBatch()` fails after `closeBatch()`), `rowCount` still returns the row count of the previous batch, while `sizeInBytes` throws an NPE because `writer` is null. Shall we reset `numRows = 0` here so that `rowCount` matches its doc? ########## 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: nit: there are two blank lines between the license header and `package`, while the other files in this package use one. The same applies to `InProcessArrowBatchExporterSuite.scala`. ########## 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: nit: `hideTraceback`, `simplifiedTraceback`, `tracebackWithLocals` and `fullValidation` are the only constructor parameters without `@param`. Could we document them too, e.g. that they are passed to `session.register`? -- 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]
