malinjawi commented on code in PR #13595:
URL: https://github.com/apache/gluten/pull/13595#discussion_r4647688070


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

Review Comment:
   Good catch. Gluten maps NTZ to Velox's `TIMESTAMP_UTC`, which is a subclass 
of its timestamp type, so the Arrow export converts its values with the same 
code (`toMicros()`, picked by type kind). The values under null struct rows 
would fail the same way. I didn't run that case, but I added `TimestampNTZType` 
to the guard, with a test. The check is now in `VeloxLanceWriteExec`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to