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


##########
gluten-lance/src/main/scala/org/apache/gluten/connector/write/LanceFragmentWriter.scala:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.spark.internal.Logging
+
+import com.google.common.util.concurrent.Uninterruptibles
+import org.apache.arrow.c.{ArrowArray, ArrowArrayStream, Data}
+import org.apache.arrow.memory.{AllocationListener, BufferAllocator}
+import org.apache.arrow.vector.VectorSchemaRoot
+import org.apache.arrow.vector.ipc.ArrowReader
+import org.apache.arrow.vector.types.pojo.Schema
+import org.lance.{Fragment, FragmentMetadata}
+import org.lance.spark.write.FragmentWriteSpec
+
+import java.io.IOException
+import java.util.{List => JList}
+import java.util.concurrent.{ArrayBlockingQueue, TimeUnit}
+import java.util.concurrent.atomic.AtomicLong
+
+/**
+ * Writes a task's batches into uncommitted Lance fragments. Not tied to a 
backend.
+ *
+ * Spark pushes batches but Lance pulls them from an Arrow C stream, so Lance 
runs on a background
+ * thread and reads from a small queue, like lance-spark's own writer. The 
stream uses the commit
+ * schema, so the fragments match what LanceBatchWrite commits. Lance imports 
the batches on its own
+ * threads, under the task's allocator, so they count as task memory while 
Lance holds them. Gluten
+ * allows reserving task memory off the task thread.
+ */
+private[write] class LanceFragmentWriter(
+    spec: FragmentWriteSpec,
+    commitSchema: Schema,
+    allocator: BufferAllocator)
+  extends Logging {
+  import LanceFragmentWriter._
+
+  private val imports = importAllocator(allocator)
+  private val queue = new ArrayBlockingQueue[Item](QueueCapacity)
+
+  private var stream: ArrowArrayStream = _
+  private var thread: Thread = _
+  @volatile private var fragments: JList[FragmentMetadata] = _
+  @volatile private var failure: Throwable = _
+  @volatile private var wallNs = 0L
+  // Time Lance spent waiting on the queue rather than writing.
+  private val queueWaitNs = new AtomicLong()
+  @volatile private var streamEnded = false
+  // Makes the stream fail, which stops Lance.
+  @volatile private var stopRequested = false
+
+  def started: Boolean = thread != null
+
+  /** Write time, not counting the time spent waiting for batches. */
+  def writeWallNs: Long = wallNs
+
+  /** Starts the writer on the first batch; after that, fails fast if Lance 
has died. */
+  def ensureRunning(): Unit = if (started) checkWriter() else start()
+
+  def write(batch: ExportedBatch): Unit = enqueue(batch)
+
+  /** Ends the stream, waits for Lance and returns the fragments it wrote. */
+  def finish(): JList[FragmentMetadata] = {
+    enqueue(End)
+    thread.join()
+    throwIfFailed()
+    if (!streamEnded) {
+      throw new IllegalStateException("Lance stopped reading before the end of 
the stream")
+    }
+    fragments
+  }
+
+  /**
+   * Fails the stream so Lance stops and deletes its files, then waits for the 
thread. abort() and
+   * close() both call this, and only the first call does anything. A killed 
task is still
+   * interrupted here, and a plain join() would return at once and let the 
task free memory the
+   * thread still uses. So the wait ignores interrupts, and Guava sets the 
flag again after.
+   */
+  def stop(): Unit = {
+    if (!stopRequested) {
+      stopRequested = true
+      drain()
+      if (started) {
+        Uninterruptibles.joinUninterruptibly(thread, StopTimeoutMs, 
TimeUnit.MILLISECONDS)
+        if (thread.isAlive) {
+          logError(
+            s"Lance write thread still running ${StopTimeoutMs / 1000}s after 
stop. Its batches " +
+              "stay allocated, which can abort the executor when the task 
ends.")
+        }
+      }
+    }
+  }
+
+  def close(): Unit = {
+    stop()
+    // If the thread outlived stop() it may still read the stream, so don't 
free the stream or the
+    // import allocator under it.
+    if (!started || !thread.isAlive) {

Review Comment:
   `close()` treats a finished writer thread as proof that Lance no longer 
holds our batches, which isn't true after a failed write. When a page fails, 
Lance v12's `write_pages` returns without awaiting the other `spawn_cpu` encode 
tasks, and those can hold input arrays zero-copy. So the task can tear down 
Velox memory while a `lance-cpu` thread references an exported batch, the end 
state that aborted the JVM in your #13595 reproduction. Unlike the timeout, the 
writer logs nothing about it.
   
   The tasks are CPU-only, so the window is short. Could `close()`, after a 
failure and after releasing the stream, wait with a bound until `allocator` 
holds only what a refused import leaked, and log at ERROR if it gives up? The 
docs should mention this case too.
   
   Watch `allocator`, not `imports`, since imported buffers move to the reader 
root. Zero is never reached once an import's struct copy is refused.



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