malinjawi commented on code in PR #13837: URL: https://github.com/apache/gluten/pull/13837#discussion_r4806101225
########## 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: Thanks for spotting. `executedPlans` now records failed queries too, and both failing saves run inside it, so the two tests check for `VeloxLanceAppendDataExec`. I checked both ways locally: with the native write on, `abort()`, `stop()` and `close()` run and Lance deletes the files the task wrote; with it off, both tests fail on the new check. -- 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]
