sezruby commented on code in PR #13595: URL: https://github.com/apache/gluten/pull/13595#discussion_r4633454710
########## backends-velox/src-lance/main/scala/org/apache/gluten/connector/write/LanceColumnarBatchDataWriter.scala: ########## @@ -0,0 +1,443 @@ +/* + * 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.gluten.connector.write + +import org.apache.gluten.backendsapi.BackendsApiManager +import org.apache.gluten.columnarbatch.{ColumnarBatches, ColumnarBatchJniWrapper} +import org.apache.gluten.memory.arrow.alloc.ArrowBufferAllocators +import org.apache.gluten.metrics.BatchWriteMetrics + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.connector.metric.CustomTaskMetric +import org.apache.spark.sql.connector.write.{DataWriter, WriterCommitMessage} +import org.apache.spark.sql.execution.metric.CustomMetrics +import org.apache.spark.sql.vectorized.ColumnarBatch + +import org.apache.arrow.c.{ArrowArray, ArrowArrayStream, ArrowSchema, CDataDictionaryProvider, Data} +import org.apache.arrow.memory.BufferAllocator +import org.apache.arrow.vector.VectorSchemaRoot +import org.apache.arrow.vector.ipc.ArrowReader +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema} +import org.lance.{Fragment, FragmentMetadata} +import org.lance.spark.write.{FragmentWriteSpec, LanceBatchWrite} +import org.lance.spark.write.metric.LanceWriteMetrics + +import java.io.IOException +import java.util.{Collections, List => JList} +import java.util.concurrent.{ArrayBlockingQueue, TimeUnit} +import java.util.concurrent.atomic.AtomicLong + +import scala.collection.JavaConverters._ + +/** + * Writes one task's Velox batches into uncommitted Lance fragments. + * + * Spark pushes batches through [[write]], while Lance pulls batches from an Arrow C stream until it + * ends. A background thread bridges the two, as lance-spark's own row writer does: each batch is + * exported to Arrow C structs on the task thread and queued, and the thread writes fragments with + * the parameters of the [[FragmentWriteSpec]] from a stream that drains the queue. + * + * The stream advertises the commit schema, so its names, nullability and timestamp zone are the + * ones `LanceBatchWrite.commit` uses. Every exported batch is checked against it, so a type Velox + * exports differently fails the task instead of writing a corrupt table. Fixed-size list columns + * arrive as plain lists and are converted by [[LanceFixedSizeLists]], and the values Velox leaves + * under nulls are zeroed by [[LanceNullSlots]] so that Lance encodes as compactly as it does for + * the row writer. + * + * The writer thread imports the batches with the task's Arrow allocator, so they count as task + * memory while Lance holds them. That reserves task memory off the task thread, which Gluten's + * memory targets allow and Velox's I/O threads do as well. A reservation that fails makes the + * stream fail, which fails the task. + * + * It reports the metrics lance-spark's row writer reports, under the same names, and fills the + * native write metrics of the write node. + */ +class LanceColumnarBatchDataWriter(spec: FragmentWriteSpec, commitSchema: Schema) + extends DataWriter[ColumnarBatch] + with Logging { + import LanceColumnarBatchDataWriter._ + + private val allocator: BufferAllocator = + ArrowBufferAllocators.contextInstance(classOf[LanceColumnarBatchDataWriter].getSimpleName) + private val queue = new ArrayBlockingQueue[Item](QueueCapacity) + private val exportedSchema = LanceFixedSizeLists.exportedSchema(commitSchema) + + private var stream: ArrowArrayStream = _ + private var thread: Thread = _ + @volatile private var fragments: JList[FragmentMetadata] = _ + @volatile private var failure: Throwable = _ + @volatile private var writeWallNs = 0L + // Time the stream waits for the task to queue its next batch, which is not time spent writing. + private val queueWaitNs = new AtomicLong() + // Set by the stream when Lance reads its end. + @volatile private var streamEnded = false + // Set by the task to make the stream fail, so Lance stops writing. + @volatile private var stopRequested = false + private var stopWaited = false + + private var recordsWritten = 0L + private var bytesWritten = 0L + private var filesWritten = 0L + + // Spark forwards bytesWritten and recordsWritten to the task's output metrics, as for the row + // writer. Lance only reports file sizes once its fragments complete, inside commit(). + private val taskMetrics: Array[CustomTaskMetric] = Array( + taskMetric(LanceWriteMetrics.RECORDS_WRITTEN, recordsWritten), + taskMetric(LanceWriteMetrics.BYTES_WRITTEN, bytesWritten), + taskMetric(BatchWriteMetrics.NUM_WRITTEN_BYTES, bytesWritten), + taskMetric(BatchWriteMetrics.NUM_WRITTEN_FILES, filesWritten), + taskMetric(BatchWriteMetrics.WRITE_WALL_NS, writeWallNs) + ) + + override def write(batch: ColumnarBatch): Unit = { + val numRows = batch.numRows() + if (numRows == 0) { + return + } + if (thread == null) { + start() + } else { + // Once Lance has failed, it reads no more batches, so do not export them. + checkWriter() + } + enqueue(exportBatch(batch)) + recordsWritten += numRows + } + + override def commit(): WriterCommitMessage = { + if (thread == null) { + // No rows in this task: commit nothing, as lance-spark's row writer does. + return LanceBatchWrite.taskCommit(Collections.emptyList()) + } + enqueue(End) + thread.join() + throwIfFailed() + if (!streamEnded) { + throw new IllegalStateException("Lance finished writing before the end of the stream") + } + fragments.asScala.foreach { + fragment => + fragment.getFiles.asScala.foreach { + file => + filesWritten += 1 + Option(file.getFileSizeBytes).foreach(size => bytesWritten += size) + } + } + LanceBatchWrite.taskCommit(fragments) + } + + override def currentMetricsValues(): Array[CustomTaskMetric] = taskMetrics + + override def abort(): Unit = { + // A failed stream makes Lance delete the files it wrote for this task, finished or not, as + // Spark expects of abort(). lance-spark's row writer ends its stream instead, which leaves + // them. + stopWriter() + // Spark adds a failed attempt's output metrics to the stage totals, so the retry would count + // these rows twice. Clear them, as lance-spark's row writer does. + recordsWritten = 0 + bytesWritten = 0 + CustomMetrics.updateMetrics(taskMetrics.toSeq, Map.empty) + } + + override def close(): Unit = { + stopWriter() + // A writer thread still running after stopWriter() waited StopTimeoutMs may still read the + // stream, so leave it rather than free it. The batch it holds then still has its memory + // reserved when the task ends. + if (stream != null && (thread == null || !thread.isAlive)) { + // Lance has taken the stream by now, unless it failed before reading it; release() then + // closes the reader, and frees nothing otherwise. + stream.release() + stream.close() + stream = null + } + } + + private def start(): Unit = { + stream = ArrowArrayStream.allocateNew(allocator) + Data.exportArrayStream(allocator, new QueueReader, stream) + thread = new Thread(() => runWriter(), "gluten-lance-write") + thread.setDaemon(true) + thread.start() + } + + /** + * Runs on the writer thread until Lance has read the stream to its end, or failed. The write time + * leaves out the time the stream waits for batches, which the operators producing them spend, as + * the time of write of Velox's own writers does. + */ + private def runWriter(): Unit = { + val startNs = System.nanoTime() + try { + fragments = Fragment + .write() + .datasetUri(spec.getDatasetUri) + .data(stream) + .writeParams(spec.toWriteParams()) + .execute() + } catch { + case t: Throwable => failure = t + } finally { + writeWallNs = System.nanoTime() - startNs - queueWaitNs.get() + } + } + + /** Exports a Velox batch to Arrow C structs, checking the schema Velox exported it with. */ + private def exportBatch(batch: ColumnarBatch): ExportedBatch = { + val handle = ColumnarBatches.getNativeHandle(BackendsApiManager.getBackendName, batch) + val exported = new ExportedBatch(ArrowArray.allocateNew(allocator)) + // An exported batch holds Velox memory, so it must be released on every path. + try { + val cSchema = ArrowSchema.allocateNew(allocator) + try { + ColumnarBatchJniWrapper.exportToArrow( + handle, + cSchema.memoryAddress(), + exported.array.memoryAddress()) + val provider = new CDataDictionaryProvider() + // Importing the schema releases and frees the struct, even when it fails. + try checkExportedSchema(Data.importSchema(allocator, cSchema, provider)) + finally provider.close() + } finally { + cSchema.close() + } + exported + } catch { + case t: Throwable => + exported.close() + throw t + } + } + + /** Queues an item, failing fast if the Lance writer has died instead of blocking forever. */ + private def enqueue(item: Item): Unit = { + try { + while (!queue.offer(item, PollIntervalMs, TimeUnit.MILLISECONDS)) { + checkWriter() + } + } catch { + case t: Throwable => + item.close() + throw t + } + } + + /** + * Makes the stream fail so Lance stops writing, then waits for the writer thread, once: abort() + * and close() both stop it, and a task should not wait twice for a writer stuck in I/O. + * + * Spark interrupts a task it kills, and the interrupt may still be pending when the task aborts + * the writer, or arrive during the wait. Either would end the wait at once, so interrupts are + * cleared for the wait and restored after: the writer has stopped, and released the batches it + * holds, before the task frees its memory. + */ + private def stopWriter(): Unit = { + stopRequested = true + drain() + if (thread != null && thread.isAlive && !stopWaited) { + stopWaited = true + var interrupted = Thread.interrupted() + val deadlineNs = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(StopTimeoutMs) + var remainingMs = StopTimeoutMs + // join(0) waits forever, so the loop stops before the time left rounds down to 0. + while (thread.isAlive && remainingMs > 0) { + try { + thread.join(remainingMs) + } catch { + case _: InterruptedException => interrupted = true + } + remainingMs = TimeUnit.NANOSECONDS.toMillis(deadlineNs - System.nanoTime()) + } + // Keep the interrupt for Spark to see. + if (interrupted) { + Thread.currentThread().interrupt() + } + if (thread.isAlive) { + logWarning("Lance write thread is still running after the task stopped it") + } + } + } + + private def drain(): Unit = { + var item = queue.poll() + while (item != null) { + item.close() + item = queue.poll() + } + } + + private def throwIfFailed(): Unit = { + if (failure != null) { + throw new IOException("Lance native write failed", failure) + } + } + + /** Fails the task if Lance has failed, or stopped reading before the end of the stream. */ + private def checkWriter(): Unit = { + throwIfFailed() + if (!thread.isAlive) { + throw new IllegalStateException("Lance write thread exited before the stream ended") + } + } + + private def checkExportedSchema(exported: Schema): Unit = + layoutMismatch(exportedSchema, exported).foreach { + mismatch => + throw new IllegalStateException( + s"Velox exported a batch that does not fit the Lance commit schema: $mismatch") + } + + /** The stream's source: imports queued batches into a root shaped like the commit schema. */ + private class QueueReader extends ArrowReader(allocator) { + // Batches with fixed-size list columns are imported as Velox exports them, then converted. + private val staging: Option[VectorSchemaRoot] = + if (exportedSchema == commitSchema) None + else + Some(VectorSchemaRoot.create(exportedSchema, LanceColumnarBatchDataWriter.this.allocator)) + + override protected def readSchema(): Schema = commitSchema + + override def loadNextBatch(): Boolean = { + if (streamEnded) { + return false + } + prepareLoadNextBatch() + val waitStartNs = System.nanoTime() + var item: Item = null + while (item == null) { + // Checked between polls, so a stop reaches Lance even when the queue is empty. + if (stopRequested) { + throw new IOException("Lance write aborted") + } + item = queue.poll(PollIntervalMs, TimeUnit.MILLISECONDS) + } + queueWaitNs.addAndGet(System.nanoTime() - waitStartNs) + item match { + case End => + streamEnded = true + false + case batch: ExportedBatch => + val writerAllocator = LanceColumnarBatchDataWriter.this.allocator + staging match { + case None => batch.importInto(writerAllocator, getVectorSchemaRoot) + case Some(root) => + batch.importInto(writerAllocator, root) + LanceFixedSizeLists.moveInto(root, getVectorSchemaRoot) + } + LanceNullSlots.zero(getVectorSchemaRoot, writerAllocator) + true + } + } + + override def bytesRead(): Long = 0 + + override protected def closeReadSource(): Unit = { + drain() + staging.foreach(_.close()) + } + } +} + +object LanceColumnarBatchDataWriter { + // Lets Lance keep encoding while the task exports the next batches. Queued batches are still + // Velox batches, so they count as task memory, each capped by maxBatchSize. + private val QueueCapacity = 4 + private val PollIntervalMs = 100L + // As long as lance-spark's row writer waits for its writer thread in abort(). + private val StopTimeoutMs = TimeUnit.MINUTES.toMillis(5) + + private def taskMetric(metricName: String, read: => Long): CustomTaskMetric = + new CustomTaskMetric { + override def name(): String = metricName + override def value(): Long = read + } + + /** + * The first difference between the layout Lance expects of a batch and the one Velox exported it + * with, if any. A batch is imported by position into vectors of the commit schema, so the types + * and the number of columns must agree at every level. Names and nullability are not compared, as + * the stream advertises the commit schema's. + */ + private[write] def layoutMismatch(expected: Schema, exported: Schema): Option[String] = + fieldsMismatch(expected.getFields, exported.getFields, "") + + private def fieldsMismatch( + expected: JList[Field], + exported: JList[Field], + parent: String): Option[String] = + if (expected.size != exported.size) { + val where = if (parent.isEmpty) "the batch" else s"column $parent" + Some(s"$where has ${exported.size} fields where Lance expects ${expected.size}") + } else { + // Lazy, so the check stops at the first difference. + expected.asScala.iterator + .zip(exported.asScala.iterator) + .map { + case (e, a) => + fieldMismatch(e, a, if (parent.isEmpty) e.getName else s"$parent.${e.getName}") + } + .collectFirst { case Some(mismatch) => mismatch } + } + + private def fieldMismatch(expected: Field, exported: Field, name: String): Option[String] = { + val sameType = (expected.getType, exported.getType) match { + // Velox exports timestamps without a time zone, which does not change their layout. + case (e: ArrowType.Timestamp, a: ArrowType.Timestamp) => e.getUnit == a.getUnit + // Nor does whether the keys of a map are sorted. + case (_: ArrowType.Map, _: ArrowType.Map) => true + case (e, a) => e == a + } + if (!sameType) { + Some( + s"column $name has Arrow type ${exported.getType} where Lance expects ${expected.getType}") + } else if (exported.getDictionary != null) { + Some(s"column $name is dictionary-encoded") + } else { + fieldsMismatch(expected.getChildren, exported.getChildren, name) + } + } + + sealed private trait Item { + def close(): Unit = {} + } + + /** An exported batch, released and freed by [[close]] unless it was imported. */ + final private class ExportedBatch(val array: ArrowArray) extends Item { + private var owned = true + + /** + * Moves the batch into `root`. Importing takes the data even when it fails, and some Arrow + * versions also free the struct, so only the idempotent close() is left to do. + */ + def importInto(allocator: BufferAllocator, root: VectorSchemaRoot): Unit = { + owned = false + try Data.importIntoVectorSchemaRoot(allocator, array, root, null) Review Comment: On the Arrow releases Gluten builds with (15, 18.x and 19.0.0), an import that the allocator refuses doesn't release the batch. `ReferenceCountedArrowArray.unsafeAssociateAllocation` calls `retain()` before `wrapForeignAllocation`, and `wrapForeignAllocation` calls `listener.onPreAllocation` outside its try block. The context allocator's `ManagedAllocationListener` reserves there through a `throwOnOom` target. If that reservation throws, the extra ref is never dropped and the exported array's release callback never runs, so the Velox batch stays allocated after the task fails. apache/arrow-java#1240 (GH-1239) fixes this. It is in 20.0.0-rc0, but not in a final release yet. Related: while Lance holds an imported batch, its bytes are reserved twice, once by Velox's pool, which still owns the buffers, and once by the `ArrowContextInstance` consumer. Lance copies what it buffers, since the file writer's `keep_original_array` defaults to false, so this covers about one batch at a time, but that batch is still counted twice. Would it work to import into an allocator that doesn't reserve, since Velox already accounts for those bytes, and keep the tracked allocator for the copies `LanceNullSlots` and `LanceFixedSizeLists` make? Transfers have to stay within one root, so it would likely need to be a child of the same root with a no-op listener. That would also avoid the leak above. A test that imports into a capped or refusing allocator would cover this either way. ########## gluten-lance/src/main/scala/org/apache/gluten/execution/LanceWriteExec.scala: ########## @@ -0,0 +1,190 @@ +/* + * 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.gluten.execution + +import org.apache.gluten.backendsapi.BackendsApiManager +import org.apache.gluten.connector.write.ColumnarStreamingDataWriterFactory + +import org.apache.spark.sql.catalyst.trees.TreeNodeTag +import org.apache.spark.sql.connector.distributions.UnspecifiedDistribution +import org.apache.spark.sql.connector.write.{BatchWrite, RequiresDistributionAndOrdering, Write} +import org.apache.spark.sql.execution.SparkPlan +import org.apache.spark.sql.types.{ArrayType, DataType, MapType, StructType, TimestampType} + +import org.apache.arrow.vector.types.{DateUnit, FloatingPointPrecision, TimeUnit} +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema} +import org.lance.spark.utils.BlobUtils +import org.lance.spark.write.{LanceBatchWrite, SparkWrite} + +import java.util.{List => JList} + +import scala.collection.JavaConverters._ + +/** + * A Lance batch write offloaded to a native backend. Executors export their native batches as an + * Arrow C stream that lance-spark writes into uncommitted fragments; lance-spark's + * [[LanceBatchWrite]] then commits them on the driver, exactly as for its own row writer. A backend + * provides the writer factory. + * + * Implementations take the [[LanceBatchWrite]] as a constructor argument, so the node keeps one + * batch write through the copies the planner makes of it, and the validation, the writer factory + * and the commit all use it. `SparkWrite.toBatch` builds a new one on every call, and each opens + * the table to pin its version, so the argument comes from [[LanceWriteExec.batchWriteOf]], which + * opens the table once per planned write. + */ +trait LanceWriteExec extends ColumnarV2TableWriteExec { + + protected def lanceBatchWrite: LanceBatchWrite = batchWrite.asInstanceOf[LanceBatchWrite] + + override protected def createStreamingWriterFactory( + schema: StructType): ColumnarStreamingDataWriterFactory = + throw new UnsupportedOperationException("Streaming writes to Lance are not offloaded") + + override def doValidateInternal(): ValidationResult = { + if (!LanceWriteExec.supportsWrite(write)) { + return ValidationResult.failed(s"Not a Lance write: ${write.getClass.getName}") + } + write match { + case r: RequiresDistributionAndOrdering + if !r.requiredDistribution().isInstanceOf[UnspecifiedDistribution] => + return ValidationResult.failed("Lance table requires a write distribution (sharded)") + case _ => + } + BackendsApiManager.getValidatorApiInstance.doSchemaValidate(query.schema) match { + case Some(reason) => return ValidationResult.failed(reason) + case None => + } + LanceWriteExec.timestampInNullableStruct(query.schema) match { + case Some(name) => + return ValidationResult.failed( + s"Timestamp column $name is inside a struct that may be null") + case None => + } + LanceWriteExec.unsupportedColumn(lanceBatchWrite.getCommitSchema) match { + case Some(reason) => ValidationResult.failed(reason) + case None => ValidationResult.succeeded + } + } +} + +object LanceWriteExec { + private val BATCH_WRITE_TAG: TreeNodeTag[BatchWrite] = + TreeNodeTag[BatchWrite]("org.apache.gluten.LanceBatchWriteTag") + + def supportsWrite(write: Write): Boolean = write.isInstanceOf[SparkWrite] + + /** + * The batch write of `write`, the write of the vanilla node `original`, built on first use and + * kept on that node. The planner offloads a node twice, first to validate the offloaded node and + * then to replace the vanilla one, so building it in each offload would open the table twice. + */ + def batchWriteOf(original: SparkPlan, write: Write): BatchWrite = + original.getTagValue(BATCH_WRITE_TAG).getOrElse { + val batchWrite = write.toBatch + original.setTagValue(BATCH_WRITE_TAG, batchWrite) + batchWrite + } + + /** + * The first column whose committed Arrow type Velox cannot export with the same layout, if any. + * Velox exports plain Utf8, Binary and List, microsecond timestamps and 128-bit decimals. The + * writer converts the plain lists of top-level fixed-size list columns, such as vectors. + */ + def unsupportedColumn(schema: Schema): Option[String] = + firstUnsupported(schema.getFields, "", topLevel = true) + + /** + * The first timestamp inside a struct that Spark says may be null, if any. Velox converts the + * timestamps of a struct's null rows too, where an expression or a join may leave any value, and + * a value out of range fails the export, as it does for Velox's own Parquet writer. Spark's + * nullability is used rather than the commit schema's, which marks every Lance column nullable. + */ + def timestampInNullableStruct(schema: StructType): Option[String] = + timestampInNullableStruct(schema, "", mayBeNull = false, inNullableStruct = false) + + private def timestampInNullableStruct( + dataType: DataType, + name: String, + mayBeNull: Boolean, + inNullableStruct: Boolean): Option[String] = dataType match { + case TimestampType => if (inNullableStruct) Some(name) else None + case s: StructType => + val inNullable = inNullableStruct || mayBeNull + s.fields.iterator + .map { + f => + val child = if (name.isEmpty) f.name else s"$name.${f.name}" + timestampInNullableStruct(f.dataType, child, f.nullable, inNullable) + } + .collectFirst { case Some(found) => found } + case a: ArrayType => + timestampInNullableStruct(a.elementType, s"$name.element", a.containsNull, inNullableStruct) + case m: MapType => + // Keys are never null, but a struct inside a key may be. + timestampInNullableStruct(m.keyType, s"$name.key", mayBeNull = false, inNullableStruct) + .orElse( + timestampInNullableStruct( + m.valueType, + s"$name.value", + m.valueContainsNull, + inNullableStruct)) + case _ => None + } + + // Lazy, so the check stops at the first unsupported field. + private def firstUnsupported( + fields: JList[Field], + prefix: String, + topLevel: Boolean): Option[String] = + fields.asScala.iterator + .map(unsupported(_, prefix, topLevel)) + .collectFirst { case Some(reason) => reason } + + private def unsupported(field: Field, prefix: String, topLevel: Boolean): Option[String] = { + val name = prefix + field.getName + if (isBlob(field)) { + return Some(s"Lance blob column $name is not offloaded") + } + field.getType match { + case t if isSignedIntOrFloat(t) => None + case _: ArrowType.Bool | _: ArrowType.Utf8 | _: ArrowType.Binary => None + case d: ArrowType.Decimal if d.getBitWidth == 128 => None + case d: ArrowType.Date if d.getUnit == DateUnit.DAY => None + case t: ArrowType.Timestamp if t.getUnit == TimeUnit.MICROSECOND => None + case _: ArrowType.List | _: ArrowType.Struct | _: ArrowType.Map => + firstUnsupported(field.getChildren, s"$name.", topLevel = false) + case _: ArrowType.FixedSizeList if topLevel => + val elementType = field.getChildren.get(0).getType + if (isSignedIntOrFloat(elementType)) None Review Comment: lance-spark 0.9.0-beta.2 only writes a fixed-size list for float and double elements, plus Float16 through metadata (`VectorUtils.shouldBeFixedSizeList`). Integer arrays with the size metadata come through as plain `List` in the commit schema, so the signed-int branch here can't be reached yet. The docs line "top-level columns of signed integers or floats" says more than what is written natively today. Should the check be narrowed to float/double, or the docs reworded? ########## gluten-lance/src/main/scala/org/apache/gluten/execution/LanceWriteExec.scala: ########## @@ -0,0 +1,190 @@ +/* + * 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.gluten.execution + +import org.apache.gluten.backendsapi.BackendsApiManager +import org.apache.gluten.connector.write.ColumnarStreamingDataWriterFactory + +import org.apache.spark.sql.catalyst.trees.TreeNodeTag +import org.apache.spark.sql.connector.distributions.UnspecifiedDistribution +import org.apache.spark.sql.connector.write.{BatchWrite, RequiresDistributionAndOrdering, Write} +import org.apache.spark.sql.execution.SparkPlan +import org.apache.spark.sql.types.{ArrayType, DataType, MapType, StructType, TimestampType} + +import org.apache.arrow.vector.types.{DateUnit, FloatingPointPrecision, TimeUnit} +import org.apache.arrow.vector.types.pojo.{ArrowType, Field, Schema} +import org.lance.spark.utils.BlobUtils +import org.lance.spark.write.{LanceBatchWrite, SparkWrite} + +import java.util.{List => JList} + +import scala.collection.JavaConverters._ + +/** + * A Lance batch write offloaded to a native backend. Executors export their native batches as an + * Arrow C stream that lance-spark writes into uncommitted fragments; lance-spark's + * [[LanceBatchWrite]] then commits them on the driver, exactly as for its own row writer. A backend + * provides the writer factory. + * + * Implementations take the [[LanceBatchWrite]] as a constructor argument, so the node keeps one + * batch write through the copies the planner makes of it, and the validation, the writer factory + * and the commit all use it. `SparkWrite.toBatch` builds a new one on every call, and each opens + * the table to pin its version, so the argument comes from [[LanceWriteExec.batchWriteOf]], which + * opens the table once per planned write. + */ +trait LanceWriteExec extends ColumnarV2TableWriteExec { + + protected def lanceBatchWrite: LanceBatchWrite = batchWrite.asInstanceOf[LanceBatchWrite] + + override protected def createStreamingWriterFactory( + schema: StructType): ColumnarStreamingDataWriterFactory = + throw new UnsupportedOperationException("Streaming writes to Lance are not offloaded") + + override def doValidateInternal(): ValidationResult = { + if (!LanceWriteExec.supportsWrite(write)) { + return ValidationResult.failed(s"Not a Lance write: ${write.getClass.getName}") + } + write match { + case r: RequiresDistributionAndOrdering + if !r.requiredDistribution().isInstanceOf[UnspecifiedDistribution] => + return ValidationResult.failed("Lance table requires a write distribution (sharded)") + case _ => + } + BackendsApiManager.getValidatorApiInstance.doSchemaValidate(query.schema) match { + case Some(reason) => return ValidationResult.failed(reason) + case None => + } + LanceWriteExec.timestampInNullableStruct(query.schema) match { + case Some(name) => + return ValidationResult.failed( + s"Timestamp column $name is inside a struct that may be null") + case None => + } + LanceWriteExec.unsupportedColumn(lanceBatchWrite.getCommitSchema) match { + case Some(reason) => ValidationResult.failed(reason) + case None => ValidationResult.succeeded + } + } +} + +object LanceWriteExec { + private val BATCH_WRITE_TAG: TreeNodeTag[BatchWrite] = + TreeNodeTag[BatchWrite]("org.apache.gluten.LanceBatchWriteTag") + + def supportsWrite(write: Write): Boolean = write.isInstanceOf[SparkWrite] + + /** + * The batch write of `write`, the write of the vanilla node `original`, built on first use and + * kept on that node. The planner offloads a node twice, first to validate the offloaded node and + * then to replace the vanilla one, so building it in each offload would open the table twice. + */ + def batchWriteOf(original: SparkPlan, write: Write): BatchWrite = + original.getTagValue(BATCH_WRITE_TAG).getOrElse { + val batchWrite = write.toBatch + original.setTagValue(BATCH_WRITE_TAG, batchWrite) + batchWrite + } + + /** + * The first column whose committed Arrow type Velox cannot export with the same layout, if any. + * Velox exports plain Utf8, Binary and List, microsecond timestamps and 128-bit decimals. The + * writer converts the plain lists of top-level fixed-size list columns, such as vectors. + */ + def unsupportedColumn(schema: Schema): Option[String] = + firstUnsupported(schema.getFields, "", topLevel = true) + + /** + * The first timestamp inside a struct that Spark says may be null, if any. Velox converts the + * timestamps of a struct's null rows too, where an expression or a join may leave any value, and + * a value out of range fails the export, as it does for Velox's own Parquet writer. Spark's + * nullability is used rather than the commit schema's, which marks every Lance column nullable. + */ + def timestampInNullableStruct(schema: StructType): Option[String] = Review Comment: facebookincubator/velox bff02cfc4 (export child rows under a null struct as null) is in Velox main, but `dft-2026_11_10` in get-velox.sh doesn't include it, so this guard is still needed. A TODO to lift it after the next Velox bump would help. Its description also covers strings under a null struct ("copies strings from views that can point anywhere") and array/map offsets. Can those reach this export with the pinned Velox, and should the guard cover more than timestamps until the bump? -- 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]
