LuciferYang commented on code in PR #13837:
URL: https://github.com/apache/gluten/pull/13837#discussion_r4799587616


##########
backends-velox/src-lance/test/scala/org/apache/gluten/connector/write/LanceColumnarBatchDataWriterSuite.scala:
##########
@@ -0,0 +1,270 @@
+/*
+ * 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.arrow.c.{ArrowArray, ArrowArrayStream, Data}
+import org.apache.arrow.memory.{AllocationListener, BufferAllocator, 
OutOfMemoryException, RootAllocator}
+import org.apache.arrow.vector.{IntVector, ValueVector, VectorSchemaRoot}
+import org.apache.arrow.vector.types.TimeUnit
+import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType, Schema}
+import org.lance.FragmentMetadata
+import org.scalatest.funsuite.AnyFunSuite
+
+import java.io.IOException
+import java.util.{List => JList}
+import java.util.Collections
+import java.util.concurrent.atomic.AtomicLong
+
+import scala.collection.JavaConverters._
+
+class LanceColumnarBatchDataWriterSuite extends AnyFunSuite {
+  private val int32 = new ArrowType.Int(32, true)
+  private val int64 = new ArrowType.Int(64, true)
+  private val utf8 = ArrowType.Utf8.INSTANCE
+
+  private def field(name: String, arrowType: ArrowType): Field =
+    Field.nullable(name, arrowType)
+
+  private def schema(fields: Field*): Schema = new Schema(fields.asJava)
+
+  private def mismatch(expected: Schema, exported: Schema): Option[String] =
+    LanceColumnarBatchDataWriter.layoutMismatch(expected, exported)
+
+  /** Stands in for a batch exported by Velox. */
+  private def exportInts(source: BufferAllocator, rows: Int): ArrowArray = {
+    val ints = new IntVector("i", source)
+    ints.allocateNew(rows)
+    (0 until rows).foreach(i => ints.set(i, i))
+    ints.setValueCount(rows)
+    val root = VectorSchemaRoot.of(ints)
+    val array = ArrowArray.allocateNew(source)
+    try Data.exportVectorSchemaRoot(source, root, null, array)
+    finally root.close()
+    array
+  }
+
+  /** Grants the first `granted` reservations and refuses the rest. */
+  private class Reservations(granted: Int) extends AllocationListener {
+    val held = new AtomicLong()
+    private var calls = 0
+
+    override def onPreAllocation(size: Long): Unit = {
+      calls += 1
+      if (calls > granted) {
+        throw new OutOfMemoryException(s"refused $size bytes")
+      }
+      held.addAndGet(size)
+    }
+
+    override def onRelease(size: Long): Unit = held.addAndGet(-size)
+  }
+
+  private def ints(allocator: BufferAllocator): VectorSchemaRoot =
+    VectorSchemaRoot.create(schema(field("i", int32)), allocator)
+
+  test("refused import still releases the batch") {
+    // The import reserves the struct copy first, then the validity and data 
buffers.
+    Seq(0, 1, 2).foreach {
+      granted =>
+        val source = new RootAllocator()
+        val reservations = new Reservations(granted)
+        val parent = new RootAllocator(reservations, Long.MaxValue)
+        val imports = LanceFragmentWriter.importAllocator(parent)
+        val root = ints(parent)
+        val batch = new LanceFragmentWriter.ExportedBatch(exportInts(source, 
1000))
+        val refused = intercept[RuntimeException](batch.importInto(imports, 
root))
+        assert(refused.getMessage.contains("refused"), refused)
+        // The source allocator plays Velox: the batch is freed when its 
release callback runs.
+        assert(source.getAllocatedMemory == 0, s"with $granted reservations 
granted")
+        root.close()
+        source.close()
+        // Arrow leaks a refused struct copy, so only check the allocators in 
the other cases.
+        if (granted > 0) {
+          imports.close()
+          parent.close()
+          assert(reservations.held.get == 0, s"with $granted reservations 
granted")
+        }
+    }
+  }
+
+  test("imported batch is reserved once and released with its vectors") {
+    val source = new RootAllocator()
+    val reservations = new Reservations(Int.MaxValue)
+    val parent = new RootAllocator(reservations, Long.MaxValue)
+    try {
+      val imports = LanceFragmentWriter.importAllocator(parent)
+      val root = ints(parent)
+      new LanceFragmentWriter.ExportedBatch(exportInts(source, 1000))
+        .importInto(imports, root)
+      // The buffers moved to the vectors' allocator, which releases through 
the same listener.
+      assert(reservations.held.get == parent.getAllocatedMemory)
+      assert(root.getVector(0).asInstanceOf[IntVector].get(999) == 999)
+      root.close()
+      assert(reservations.held.get == 0)
+      assert(source.getAllocatedMemory == 0)
+      imports.close()
+    } finally {
+      parent.close()
+      source.close()
+    }
+  }
+
+  /**
+   * Fails like a page write in Lance: frees the stream and throws while an 
encode task still holds
+   * a column of the last batch.
+   */
+  private class FailedWrite(allocator: BufferAllocator, lance: BufferAllocator)
+    extends LanceFragmentWriter(null, schema(field("i", int32)), allocator) {
+    @volatile var held: ValueVector = _
+
+    override protected def writeFragments(stream: ArrowArrayStream): 
JList[FragmentMetadata] = {
+      // A view, since Lance takes the stream by address and leaves our struct 
to us.
+      val reader = Data.importArrayStream(lance, 
ArrowArrayStream.wrap(stream.memoryAddress()))
+      try {
+        assert(reader.loadNextBatch())
+        val column = 
reader.getVectorSchemaRoot.getVector(0).getTransferPair(lance)
+        column.transfer()
+        held = column.getTo
+      } finally {
+        reader.close()
+      }
+      throw new IOException("page write failed")
+    }
+  }
+
+  test("close waits for Lance to release a batch after a failed write") {
+    val source = new RootAllocator()
+    val allocator = new RootAllocator()
+    val lance = new RootAllocator()
+    val writer = new FailedWrite(allocator, lance)
+    writer.ensureRunning()
+    writer.write(new LanceFragmentWriter.ExportedBatch(exportInts(source, 
1000)))
+    val failed = intercept[IOException](writer.finish())
+    assert(failed.getCause.getMessage == "page write failed")
+    // Lance still holds the batch, so Velox can't free it yet.
+    assert(source.getAllocatedMemory > 0)
+    val closing = new Thread(
+      () => {
+        // A killed task is still interrupted here.
+        Thread.currentThread().interrupt()
+        writer.close()
+      })
+    closing.setDaemon(true)
+    closing.start()
+    closing.join(500)
+    assert(closing.isAlive, "close() returned while Lance still held the 
batch")
+    // The encode task finishes and lets go of the batch.
+    writer.held.close()
+    closing.join(10000)
+    assert(!closing.isAlive, "close() still waiting after Lance let go of the 
batch")
+    // The source allocator plays Velox: the task frees its memory once 
close() returns.
+    assert(source.getAllocatedMemory == 0)
+    assert(allocator.getAllocatedMemory == 0)
+    Seq(lance, allocator, source).foreach(_.close())
+  }
+
+  /** Reads the stream like Lance until it ends or fails, and keeps nothing. */
+  private class ReadAll(allocator: BufferAllocator, lance: BufferAllocator, 
afterSchema: () => Unit)
+    extends LanceFragmentWriter(null, schema(field("i", int32)), allocator) {
+    override protected def writeFragments(stream: ArrowArrayStream): 
JList[FragmentMetadata] = {
+      val reader = Data.importArrayStream(lance, 
ArrowArrayStream.wrap(stream.memoryAddress()))
+      try {
+        reader.getVectorSchemaRoot
+        afterSchema()
+        while (reader.loadNextBatch()) {}
+      } finally {
+        reader.close()
+      }
+      Collections.emptyList()
+    }
+  }
+
+  /** Refuses the next reservation once armed. */
+  private class RefuseNext extends AllocationListener {
+    @volatile var armed = false
+
+    override def onPreAllocation(size: Long): Unit = if (armed) {
+      armed = false
+      throw new OutOfMemoryException(s"refused $size bytes")
+    }
+  }
+
+  test("close doesn't wait for what a refused import leaked") {
+    val source = new RootAllocator()
+    val refuse = new RefuseNext
+    val allocator = new RootAllocator(refuse, Long.MaxValue)
+    val lance = new RootAllocator()
+    // The next reservation after the schema is the import's struct copy, 
which Arrow leaks.
+    val writer = new ReadAll(allocator, lance, () => refuse.armed = true)
+    writer.ensureRunning()
+    writer.write(new LanceFragmentWriter.ExportedBatch(exportInts(source, 
1000)))
+    val failed = intercept[IOException](writer.finish())
+    assert(failed.getCause.getMessage.contains("refused"), failed.getCause)
+    // On its own thread, so a wait for the leak fails here and not after 
minutes.
+    val closing = new Thread(() => writer.close())
+    closing.setDaemon(true)
+    closing.start()
+    closing.join(10000)
+    assert(!closing.isAlive, "close() waited for what the refused import 
leaked")
+    assert(source.getAllocatedMemory == 0)
+    // Only the leak is left, in the import allocator, for the task's leak 
check.
+    assert(allocator.getAllocatedMemory > 0)
+    assert(
+      allocator.getChildAllocators.asScala.toSeq.map(_.getAllocatedMemory).sum 
==
+        allocator.getAllocatedMemory)
+    // allocator stays open, like the refused case above.
+    Seq(lance, source).foreach(_.close())
+  }
+
+  test("names, nullability and metadata are not compared") {
+    val expected = schema(
+      new Field("id", new FieldType(true, int32, null, Map("k" -> 
"v").asJava), null),
+      field("s", utf8))
+    val exported =
+      schema(new Field("n0_0", FieldType.notNullable(int32), null), 
field("n0_1", utf8))
+    assert(mismatch(expected, exported).isEmpty)
+  }
+
+  test("timestamps differ by unit, not by time zone") {
+    val expected = schema(field("t", new 
ArrowType.Timestamp(TimeUnit.MICROSECOND, "UTC")))
+    val noZone = schema(field("t", new 
ArrowType.Timestamp(TimeUnit.MICROSECOND, null)))
+    val nanos = schema(field("t", new ArrowType.Timestamp(TimeUnit.NANOSECOND, 
"UTC")))
+    assert(mismatch(expected, noZone).isEmpty)
+    assert(mismatch(expected, nanos).exists(_.startsWith("column t has Arrow 
type Timestamp")))
+  }
+
+  test("mismatched column type is named") {
+    val expected = schema(field("id", int32), field("v", int64))
+    val exported = schema(field("id", int32), field("v", int32))
+    assert(
+      mismatch(expected, exported).contains(
+        "column v has Arrow type Int(32, true) where Lance expects Int(64, 
true)"))
+  }
+
+  test("unsigned integers are refused") {

Review Comment:
   `unexportableColumn` refuses more than the unsigned case the suite checks: 
dates in milliseconds, timestamps outside microseconds and fixed-size binary 
all go through the `other` branch, and those layouts are reachable because 
lance-spark rebuilds them from the column metadata when a table that has them 
is appended to. The integration suite covers nested, vector, large string and 
blob, so the remaining rows of the fallback table have no test. A table-driven 
case over `unexportableColumn`, one per row, would keep the table and the 
whitelist in step.
   
   A widened whitelist would still fail the task through `layoutMismatch` 
rather than write bad data, so this is about the documented fallback staying 
true.



##########
backends-velox/src-lance/test/scala/org/apache/gluten/execution/VeloxLanceWriteSuite.scala:
##########
@@ -0,0 +1,716 @@
+/*
+ * 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.config.{GlutenConfig, GlutenLanceConfig}
+
+import org.apache.spark.SparkConf
+import org.apache.spark.scheduler.{SparkListener, SparkListenerTaskEnd}
+import org.apache.spark.sql.{DataFrame, Row}
+import org.apache.spark.sql.connector.write.{BatchWrite, DataWriterFactory, 
PhysicalWriteInfo, Write, WriterCommitMessage}
+import org.apache.spark.sql.execution.{ColumnarToRowTransition, 
QueryExecution, RowToColumnarTransition, SparkPlan}
+import org.apache.spark.sql.execution.datasources.v2.{AppendDataExec, 
OverwriteByExpressionExec}
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.MetadataBuilder
+import org.apache.spark.sql.util.QueryExecutionListener
+import org.apache.spark.task.TaskResources
+import org.apache.spark.utils.GlutenSuiteUtils
+
+import org.apache.commons.lang3.exception.ExceptionUtils
+import org.lance.Dataset
+import org.lance.spark.utils.{BlobUtils, JsonUtils}
+
+import java.io.File
+import java.util.Collections
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicLong
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable.ArrayBuffer
+
+/** Native Lance writes, and the writes that fall back to lance-spark's 
writer. */
+class VeloxLanceWriteSuite extends VeloxWholeStageTransformerSuite {
+  override protected val resourcePath: String = "/tpch-data-parquet"
+  override protected val fileFormat: String = "parquet"
+
+  override protected def sparkConf: SparkConf = {
+    super.sparkConf
+      .set("spark.shuffle.manager", 
"org.apache.spark.shuffle.sort.ColumnarShuffleManager")
+      .set("spark.sql.shuffle.partitions", "1")
+      .set("spark.memory.offHeap.size", "2g")
+      // ANSI mode, the default on Spark 4.x, makes Gluten fall back every 
query.
+      .set("spark.sql.ansi.enabled", "false")
+      .set("spark.sql.catalog.lance", 
"org.lance.spark.LanceNamespaceSparkCatalog")
+      .set(GlutenLanceConfig.ENABLE_NATIVE_WRITE.key, "true")
+  }
+
+  /** Rows of the common types the native write supports. Only `s` has nulls. 
*/
+  private def rows(start: Long, n: Long, partitions: Int = 1): DataFrame =
+    spark
+      .range(start, start + n, 1, partitions)
+      .selectExpr(
+        "cast(id as int) as id",
+        "id * 3 as l",
+        "cast(id as double) / 2 as d",
+        "case when id % 7 = 0 then null else concat('s', cast(id as string)) 
end as s",
+        "cast(id as decimal(10, 2)) as dec",
+        "date_add(date'2020-01-01', cast(id as int)) as dt",
+        "timestamp_seconds(id * 1000) as ts",
+        "id % 2 = 0 as b",
+        "cast(concat('b', cast(id as string)) as binary) as bin"
+      )
+
+  private def read(uri: String): DataFrame = 
spark.read.format("lance").option("path", uri).load()
+
+  private def withLanceTable(initial: DataFrame)(f: String => Unit): Unit = {
+    withTempPath {
+      path =>
+        val uri = s"${path.getCanonicalPath}/t.lance"
+        initial.write.format("lance").option("path", uri).save()
+        f(uri)
+    }
+  }
+
+  private val catalogs = new AtomicLong()
+
+  /** Runs `f` with a Lance catalog on a temp directory. */
+  private def withLanceCatalog(f: String => Unit): Unit = {
+    withTempDir {
+      dir =>
+        // Spark caches catalogs by name, so use a new name each time.
+        val catalog = s"lance_write_${catalogs.incrementAndGet()}"
+        withSQLConf(
+          s"spark.sql.catalog.$catalog" -> 
"org.lance.spark.LanceNamespaceSparkCatalog",
+          s"spark.sql.catalog.$catalog.impl" -> "dir",
+          s"spark.sql.catalog.$catalog.root" -> dir.getCanonicalPath
+        ) {
+          spark.sql(s"CREATE NAMESPACE IF NOT EXISTS $catalog.default")
+          f(catalog)
+        }
+    }
+  }
+
+  private def sqlRows(start: Int, end: Int): String =
+    s"SELECT cast(id as int) as id, concat('s', cast(id as string)) as s FROM 
range($start, $end)"
+
+  private def expectedSqlRows(start: Int, end: Int): Seq[Row] =
+    (start until end).map(i => Row(i, s"s$i"))
+
+  /** Runs `f` and checks its tasks didn't leak Arrow memory. */
+  private def assertNoArrowLeak(f: => Unit): Unit = {
+    val before = TaskResources.ACCUMULATED_LEAK_BYTES.get()
+    f
+    GlutenSuiteUtils.waitUntilEmpty(spark.sparkContext)
+    assert(TaskResources.ACCUMULATED_LEAK_BYTES.get() == before, "Arrow memory 
leaked")
+  }
+
+  private def causedBy(e: Throwable, text: String): Boolean =
+    ExceptionUtils.getThrowableList(e).asScala.exists(
+      t => String.valueOf(t.getMessage).contains(text))
+
+  /** Executed plans of the queries `action` runs. */
+  private def executedPlans(action: => Unit): Seq[SparkPlan] = {
+    val plans = ArrayBuffer[SparkPlan]()
+    val listener = new QueryExecutionListener {
+      override def onSuccess(funcName: String, qe: QueryExecution, durationNs: 
Long): Unit =
+        plans.synchronized(plans += qe.executedPlan)
+      override def onFailure(funcName: String, qe: QueryExecution, exception: 
Exception): Unit = {}
+    }
+    // Listener events are async; flush earlier ones (e.g. setup writes) so we 
don't collect them.
+    GlutenSuiteUtils.waitUntilEmpty(spark.sparkContext)
+    spark.listenerManager.register(listener)
+    try {
+      action
+      GlutenSuiteUtils.waitUntilEmpty(spark.sparkContext)
+    } finally {
+      spark.listenerManager.unregister(listener)
+    }
+    plans.synchronized(plans.toList)
+  }
+
+  private def fileFormatVersions(uri: String): Seq[String] = withDataset(uri) {
+    dataset =>
+      for {
+        fragment <- dataset.getFragments.asScala.toSeq
+        file <- fragment.metadata().getFiles.asScala
+      } yield s"${file.getFileMajorVersion}.${file.getFileMinorVersion}"
+  }
+
+  private def withDataset[T](uri: String)(f: Dataset => T): T = {
+    val dataset = Dataset.open(uri)
+    try f(dataset)
+    finally dataset.close()
+  }
+
+  private def assertOffloaded[T <: LanceWriteExec: 
scala.reflect.ClassTag](plans: Seq[SparkPlan])
+      : Unit = {
+    val cls = implicitly[scala.reflect.ClassTag[T]].runtimeClass
+    assert(plans.exists(_.exists(cls.isInstance(_))), s"Expected 
${cls.getSimpleName} in:\n$plans")
+  }
+
+  /** Checks the write stayed vanilla and, if given, that the offload refused 
it for `reason`. */
+  private def assertFellBack(plans: Seq[SparkPlan], reason: String = ""): Unit 
= {
+    assert(!plans.exists(_.exists(_.isInstanceOf[LanceWriteExec])), 
s"Unexpected offload:\n$plans")
+    val vanilla = plans.flatMap(_.collect {
+      case w @ (_: AppendDataExec | _: OverwriteByExpressionExec) => w
+    })
+    assert(vanilla.nonEmpty, s"Expected a vanilla write in:\n$plans")
+    if (reason.nonEmpty) {
+      val refusals = vanilla.collect {
+        case a: AppendDataExec => 
VeloxLanceAppendDataExec(a).doValidateInternal()
+      }
+      assert(refusals.exists(r => !r.ok() && r.reason().contains(reason)), 
refusals.map(_.reason()))
+    }
+  }
+
+  test("append offloads to Velox and keeps every value") {
+    withLanceTable(rows(0, 50)) {
+      uri =>
+        // range() makes 1,000-row batches, so each of the 4 tasks writes 4 
batches.
+        val plans = executedPlans {
+          assertNoArrowLeak {
+            rows(50, 16000, partitions = 4).write
+              .format("lance")
+              .mode("append")
+              .option("path", uri)
+              .save()
+          }
+        }
+        assertOffloaded[VeloxLanceAppendDataExec](plans)
+        checkAnswer(read(uri), rows(0, 16050))
+    }
+  }
+
+  test("append with write_mode=overwrite replaces the table") {
+    withLanceTable(rows(0, 50)) {
+      uri =>
+        val plans = executedPlans {
+          rows(200, 20).write
+            .format("lance")
+            .mode("append")
+            .option("write_mode", "overwrite")
+            .option("path", uri)
+            .save()
+        }
+        assertOffloaded[VeloxLanceAppendDataExec](plans)
+        checkAnswer(read(uri), rows(200, 20))
+    }
+  }
+
+  test("an empty append commits no fragments") {
+    withLanceTable(rows(0, 20)) {
+      uri =>
+        // lance-spark skips the commit when there are no fragments.
+        val plans = executedPlans {
+          rows(0, 0).write.format("lance").mode("append").option("path", 
uri).save()
+        }
+        assertOffloaded[VeloxLanceAppendDataExec](plans)
+        checkAnswer(read(uri), rows(0, 20))
+    }
+  }
+
+  test("append to a table with a dropped column") {
+    withTempPath {
+      path =>
+        val uri = s"${path.getCanonicalPath}/t.lance"
+        spark
+          .range(0, 10)
+          .selectExpr("cast(id as int) as a", "cast(id as int) as b", "cast(id 
* 10 as int) as c")
+          .write
+          .format("lance")
+          .option("path", uri)
+          .save()
+        withDataset(uri)(_.dropColumns(Collections.singletonList("b")))
+
+        val plans = executedPlans {
+          spark
+            .range(10, 20)
+            .selectExpr("cast(id as int) as a", "cast(id * 10 as int) as c")
+            .write
+            .format("lance")
+            .mode("append")
+            .option("path", uri)
+            .save()
+        }
+        assertOffloaded[VeloxLanceAppendDataExec](plans)
+        checkAnswer(read(uri), (0 until 20).map(i => Row(i, i * 10)))
+    }
+  }
+
+  test("append keeps the table's file format version") {
+    withTempPath {
+      path =>
+        val uri = s"${path.getCanonicalPath}/t.lance"
+        // 2.1 isn't Lance's default, so 2.1 files from the append mean it 
kept the table's version.
+        rows(0, 20).write
+          .format("lance")
+          .option("file_format_version", "2.1")
+          .option("path", uri)
+          .save()
+        val plans = executedPlans {
+          rows(20, 50).write
+            .format("lance")
+            .mode("append")
+            .option("max_row_per_file", "10")
+            .option("path", uri)
+            .save()
+        }
+        assertOffloaded[VeloxLanceAppendDataExec](plans)
+        val versions = fileFormatVersions(uri)
+        // The first file plus at least five 10-row files from the append.
+        assert(versions.size >= 6, s"Expected the append to roll files: 
$versions")
+        assert(versions.forall(_ == "2.1"), s"Expected only 2.1 files: 
$versions")
+        checkAnswer(read(uri), rows(0, 70))
+    }
+  }
+
+  test("failed task leaves the table unchanged and no files behind") {
+    withLanceTable(rows(0, 50)) {
+      uri =>
+        val dataFiles = new File(uri, "data").list().toSet
+        // 1,000-row batches and files, so Lance has finished several files 
before id 19000 fails.
+        val failing = rows(50, 20000).where("assert_true(id < 19000) is null")
+        assertNoArrowLeak {
+          val e = intercept[Exception] {
+            failing.write
+              .format("lance")
+              .mode("append")
+              .option("path", uri)
+              .option("max_row_per_file", "1000")
+              .save()
+          }
+          assert(causedBy(e, "is not true"), e)
+        }
+        checkAnswer(read(uri), rows(0, 50))
+        // Abort fails the stream, so Lance deletes everything it wrote for 
the task.
+        assert(new File(uri, "data").list().toSet == dataFiles)
+    }
+  }
+
+  test("write metrics") {
+    withLanceTable(rows(0, 10)) {
+      uri =>
+        val stageRecords = new AtomicLong()
+        val stageBytes = new AtomicLong()
+        val listener = new SparkListener {
+          override def onTaskEnd(taskEnd: SparkListenerTaskEnd): Unit = {
+            Option(taskEnd.taskMetrics).foreach {
+              metrics =>
+                stageRecords.addAndGet(metrics.outputMetrics.recordsWritten)
+                stageBytes.addAndGet(metrics.outputMetrics.bytesWritten)
+            }
+          }
+        }
+        GlutenSuiteUtils.waitUntilEmpty(spark.sparkContext)
+        spark.sparkContext.addSparkListener(listener)
+        val plans =
+          try {
+            executedPlans {
+              rows(10, 100, partitions = 2).write
+                .format("lance")
+                .mode("append")
+                .option("path", uri)
+                .save()
+            }
+          } finally {
+            spark.sparkContext.removeSparkListener(listener)
+          }
+        val node = plans.flatMap(_.collect { case w: VeloxLanceAppendDataExec 
=> w }).head
+        assert(node.metrics("recordsWritten").value == 100)
+        assert(node.metrics("numWrittenFiles").value >= 2)
+        assert(node.metrics("numWrittenBytes").value > 0)
+        assert(stageRecords.get == 100)
+        assert(stageBytes.get == node.metrics("numWrittenBytes").value)
+    }
+  }
+
+  test("killed task stops the writer and frees its batches") {

Review Comment:
   Neither test proves the write was offloaded. The killed-task test only 
checks that no `gluten-lance-write` thread is left, which is also true on a 
fallback to lance-spark's writer, and the failed-task test only checks the 
table and the data directory, which lance-spark's abort leaves unchanged too. 
The exception comes from the child either way, so a write-level fallback keeps 
both green while `abort()`, `stop()` and `close()` never run.
   
   `executedPlans` only records on success and both actions throw, so the 
helper has to record `qe.executedPlan` in `onFailure`, with the failing 
`save()` inside the block so the listener sees it, before the assertions can 
check for `VeloxLanceAppendDataExec`. The "Lance failure fails the task" test 
already checks the native message, so this is only about these two.



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