spark-test commented on code in PR #60545: URL: https://github.com/apache/spark/pull/60545#discussion_r4593495001
########## sql/core/src/test/scala/org/apache/spark/sql/execution/python/InProcessArrowBatchExporterSuite.scala: ########## @@ -0,0 +1,257 @@ +/* + * 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. Without + * Python no result is imported, so the release of the results, also those of earlier UDFs when + * a later UDF fails, is covered by `test_arrow_memory_is_released_on_success_limit_and_failure` + * in `pyspark.sql.tests.test_inprocess_udf`. + */ +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 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. + val row = InternalRow(0L, UTF8String.fromString("a")) + intercept[AssertionError](exporter.evaluate(calls.run)) + intercept[AssertionError](exporter.write(row)) + fill(exporter, 0 until 5, "a") + exporter.evaluate(calls.run) + intercept[AssertionError](exporter.evaluate(calls.run)) + intercept[AssertionError](exporter.write(row)) + assert(exporter.rowCount == 5) + 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.write(row)) + 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(emptyFunction(), emptyFunction())) + 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) + // 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) + } + + test("a call into Python that is refused stops the batch before anything is exported") { + val metrics = allMetrics() + val exporter = this.exporter(metrics, Seq(emptyFunction())) + 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(emptyFunction(), emptyFunction())) + 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 a UDF is invoked") { + val metrics = allMetrics() + val context = TaskContext.empty() + val calls = new Calls(metrics) + val exporter = this.exporter(metrics, Seq(emptyFunction()), context = context) + fill(exporter, 0 until 5, "a") + // Registration succeeds without Python, and the task is killed before the invocation. + val run: InProcessArrowBatchExporter.PythonCall = (metric, _) => { + calls.run(metric, () => 7L) + context.markInterrupted("test cancellation") + } + intercept[TaskKilledException](exporter.evaluate(run)) + assert(calls.charged == Seq("pythonInitTime") && metrics("pythonInitTime").value == 7L) + // The batch was finished and counted as sent, but no result was received. + assert(metrics("pythonDataSent").value > 0 && metrics("pythonNumRowsReceived").value == 0) + exporter.close() + } + + test("flat vectors of a batch are pre-sized like the previous batch") { + val metrics = allMetrics() + val exporter = this.exporter(metrics) + fill(exporter, 0 until 5000, "x" * 100) + exporter.evaluate(new Calls(metrics).run) + exporter.startBatch() + // An empty batch already holds buffers for the rows and string bytes of the previous one. + val presized = ArrowUtils.rootAllocator.getAllocatedMemory - allocatedBefore + assert(presized >= 5000 * 8 + 5000 * 100) Review Comment: **Nit (P3):** Going by Arrow 19's allocation code, the 100-byte string column alone meets this bound: after 5000 rows, `startBatch` pre-sizes its data buffer to 524288 bytes and its offset and validity buffers to 32768 bytes, 557056 bytes in all, above the 540000 bytes this line asserts. A fresh exporter's empty batch takes about 80 KB. Neither assertion depends on the long column, so the test would still pass with the `BaseFixedWidthVector` arm removed from `startBatch`, or given a count of 1, even though the `5000 * 8` term, the test name and the PR description present fixed-width pre-sizing as covered. Losing that arm changes no results; it only adds reallocation and copying while batches of fixed-width columns such as longs, doubles, dates or timestamps fill, so no other test would catch it. Could the test also check the fixed-width arm on its own, for example with an exporter over only the long column (the `exporter` helper would take the schema), asserting that after 5000 ro ws the next empty batch allocates at least `5000 * 8` bytes and more than a fresh exporter's empty batch? **Verification:** - **Regression:** With the fixed-width arm of `startBatch` removed, or given a count as small as 1, the pre-sizing test fails, and with the current code it passes; a count just below the previous batch's, such as 4999 for 5000 rows, need not fail it, because Arrow rounds the buffer up to the same power of two. - **Behavior:** An empty batch that follows a 5000-row batch of a fixed-width column holds at least 5000 times the type width, more than an empty batch of a fresh exporter, while the string column's existing pre-sizing checks still hold. -- 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]
