malinjawi commented on code in PR #13837: URL: https://github.com/apache/gluten/pull/13837#discussion_r4806331499
########## 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: Thanks, good point. I replaced the unsigned test with a table-driven one over `unexportableColumn`: one entry per fallback row it decides, with that row's Arrow types, and each type has to be refused. Letting any of the three layouts you mentioned through now fails it. -- 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]
