HyukjinKwon commented on code in PR #59933: URL: https://github.com/apache/spark/pull/59933#discussion_r4469615036
########## sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarDataSourceSuite.scala: ########## @@ -380,6 +970,57 @@ class TestBatchReader(lo: Long, hi: Long, schema: StructType) override def close(): Unit = if (consumed) batch.close() } +/** + * Returns the ids [lo, hi) and their names in Arrow batches of at most `batchSize` rows. It writes + * each batch to the same Arrow vectors, over the previous one. + */ +/** @param largeVarTypes whether the strings are `large_utf8`, which the writers convert */ Review Comment: Fixed in 7ee5eb7: a single doc comment, with the description and then the tags of the parameters. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/internal/connector/SupportsColumnarInput.scala: ########## @@ -0,0 +1,40 @@ +/* + * 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.internal.connector + +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.write.DataWriter +import org.apache.spark.sql.vectorized.ColumnarBatch + +/** + * An internal mixin for a `Write`, or for the `StreamingWrite` of a micro-batch write, whose data + * writers are [[ColumnarInputDataWriter]]s. When the query of an append or an overwrite, or of a + * micro-batch, produces columnar batches, Spark passes them to the data writers instead of Review Comment: Updated in 7ee5eb7: `SupportsColumnarInput` now says that Spark passes the batches only when the query only produces columnar batches and the session has no columnar rules of extensions, that the data writers get rows otherwise, for example for the scan of a cached DataFrame or a query that adaptive query execution wraps, and refers to `V2TableWriteExec.writesColumnar`. The doc of `ColumnarWrite` says the same and refers to it. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarWrite.scala: ########## @@ -214,15 +239,240 @@ class ArrowBatchingDataWriter(delegate: DataWriter[ColumnarBatch], options: Arro } } - private def flush(): Unit = { - if (root != null) { - arrowWriter.finish() - val columns = root.getFieldVectors.asScala.map(new ArrowColumnVector(_): ColumnVector) + override def writeBatch(batch: ColumnarBatch): Unit = { + val numBatchRows = batch.numRows() + val copied = copiedVectors(batch) + if (copied.forall(_.isEmpty)) { + // Without columns to copy, the values are converted as rows are. + var i = 0 + while (i < numBatchRows) { + write(batch.getRow(i)) + i += 1 + } + } else if (numBatchRows > 0) { + // A batch without rows leaves the pending batch of rows as it is. + flush() + // Each batch starts where the last one ended, so that the batches end as those of rows do. + var start = 0 + while (start < numBatchRows) { + start += writeRows( + batch, copied, start, start + math.min(numBatchRows - start, options.maxRecordsPerBatch)) + } + } + } + + /** + * Returns, for each column of a batch, its Arrow vector if it can be copied buffer by buffer, see + * `ArrowBatchingDataWriter.canCopy`. The other columns are converted value by value. + */ + private def copiedVectors(batch: ColumnarBatch): Seq[Option[FieldVector]] = { + val fields = arrowSchema.getFields.asScala + if (batch.numCols() != fields.length) { + Seq.fill(fields.length)(None) + } else { + fields.indices.map { i => + batch.column(i) match { + case column: ArrowColumnVector => column.getValueVector match { + case vector: FieldVector + if ArrowBatchingDataWriter.canCopy(vector, fields(i), batch.numRows()) => + Some(vector) + case _ => None + } + case _ => None + } + } + } + } + + /** + * Writes the batch of the rows of a columnar batch that starts at the row `start`, and returns + * its number of rows: up to `end`, or as a batch of rows ends, up to the first row with which it + * holds `maxBytesPerBatch` bytes, by the measure of `getBufferSizeFor`, which `rangeSize` + * computes for the copied columns without slicing them. + * + * @param copied the vector of each column of the batch that is copied, see `copiedVectors` + */ + private def writeRows( + batch: ColumnarBatch, + copied: Seq[Option[FieldVector]], + start: Int, + end: Int): Int = { + // The columns that are not copied, and the vectors that they are converted into. + val ordinals = copied.indices.filter(copied(_).isEmpty) + val converted = ArrayBuffer.empty[FieldVector] + Utils.tryWithSafeFinally { + val writers = ordinals.map { ordinal => + val vector = arrowSchema.getFields.get(ordinal).createVector(allocator) + converted += vector + vector.setInitialCapacity(end - start) + vector.allocateNew() + ArrowWriter.createFieldWriter(vector) + } + val length = if (writers.isEmpty) { + batchLength(copied.flatten, start, end) + } else { + convertRows(batch, copied.flatten, ordinals.zip(writers), start, end) + } + writers.foreach(_.finish()) + writeSlices(copied, converted.toSeq, start, length) + length + } { + AutoCloseables.close(converted.asJava) + } + } + + /** + * Returns the number of rows of the batch of copied columns that starts at the row `start`, see + * `writeRows`. + */ + private def batchLength(copied: Seq[FieldVector], start: Int, end: Int): Int = { + def sizeInBytes(rows: Int): Long = + copied.map(ArrowBatchingDataWriter.rangeSize(_, start, start + rows)).sum + // The size is not computed when the limit is the largest possible one, as for rows. + if (options.maxBytesPerBatch >= Int.MaxValue || + sizeInBytes(end - start) < options.maxBytesPerBatch) { + end - start + } else { + // The size grows with the number of rows. + var lo = 1 + var hi = end - start + while (lo < hi) { + val mid = (lo + hi) >>> 1 + if (sizeInBytes(mid) >= options.maxBytesPerBatch) hi = mid else lo = mid + 1 + } + lo + } + } + + /** + * Converts the columns of a columnar batch that are not copied with their writers, by ordinal, + * row by row from the row `start` up to the end of the batch, and returns its number of rows, see + * `writeRows`. As for rows, the size of the batch is computed after each row, so that the + * conversion stops at the row with which the batch holds `maxBytesPerBatch` bytes. + */ + private def convertRows( + batch: ColumnarBatch, + copied: Seq[FieldVector], + writers: Seq[(Int, ArrowFieldWriter)], + start: Int, + end: Int): Int = { + val copiedVectors = copied.toArray + val ordinals = writers.map(_._1).toArray + val fieldWriters = writers.map(_._2).toArray + // The size of the batch once it holds the rows [start, rowEnd). + def sizeInBytes(rowEnd: Int): Long = { + var size = 0L + var i = 0 + while (i < copiedVectors.length) { + size += ArrowBatchingDataWriter.rangeSize(copiedVectors(i), start, rowEnd) + i += 1 + } + i = 0 + while (i < fieldWriters.length) { + size += fieldWriters(i).getSizeInBytes() + i += 1 + } + size + } + // The size is not computed when the limit is the largest possible one, as for rows. + val sized = options.maxBytesPerBatch < Int.MaxValue + var next = start + var full = false + while (next < end && !full) { + val row = batch.getRow(next) + var i = 0 + while (i < fieldWriters.length) { + fieldWriters(i).write(row, ordinals(i)) + i += 1 + } + next += 1 + full = sized && sizeInBytes(next) >= options.maxBytesPerBatch + } + next - start + } + + /** + * Writes the rows [start, start + length) of a columnar batch, with the vectors that its columns + * that are not copied were converted into from these rows, in their order. The copied columns are + * sliced, which shares most buffers of the batch, though it allocates new offsets for lists, and + * for strings and binaries unless the offset of the row `start` is 0, and new validity buffers, + * and value buffers for booleans, unless `start` is a multiple of 8. Then each buffer of the + * slice is copied at its size. Arrow Java reads the offsets of a vector of variable width, or of + * a list, as if they started at 0, which those of a slice do. The converted vectors, which + * nothing else writes to, are written as they are. + */ + private def writeSlices( + copied: Seq[Option[FieldVector]], + converted: Seq[FieldVector], + start: Int, + length: Int): Unit = { + // The slices of the copied columns share the buffers of the batch, which their producer + // releases, so they are closed once they are copied. + val slices = ArrayBuffer.empty[FieldVector] + val copy = Utils.tryWithSafeFinally { + copied.flatten.foreach { vector => + // The slice is closed also when the buffers that it allocates fail to allocate. + val pair = vector.getTransferPair(vector.getAllocator) + slices += pair.getTo.asInstanceOf[FieldVector] + pair.splitAndTransfer(start, length) Review Comment: Added in 7ee5eb7: "copy the Arrow columns of every type, or convert the columns of a batch" now also exports its batch of every type through the C data interface and imports it, as a native read does, and copies it in slices of 3 rows and of 1 row, so that they start at rows 3 and 6, or at every row. It checks the batches and the rows written, that the imported batch is still readable afterwards, and that its allocator holds nothing once it is released. It needs no native library. -- 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]
