Copilot commented on code in PR #13280:
URL: https://github.com/apache/gluten/pull/13280#discussion_r4345609411


##########
gluten-arrow/src/main/scala/org/apache/gluten/vectorized/ArrowColumnVectors.scala:
##########
@@ -0,0 +1,96 @@
+/*
+ * 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.vectorized
+
+import org.apache.gluten.memory.arrow.alloc.ArrowBufferAllocators
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.execution.arrow.ArrowWriter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.utils.{SparkArrowUtil, SparkSchemaUtil}
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+
+import org.apache.arrow.memory.BufferAllocator
+import org.apache.arrow.vector.{FieldVector, ValueVector, VectorSchemaRoot}
+import org.apache.arrow.vector.util.VectorAppender
+
+import scala.collection.JavaConverters._
+
+/** Utilities to build Gluten's Java Arrow batches of 
[[RefCountedArrowColumnVector]]s. */
+object ArrowColumnVectors {
+
+  /** Allocates an empty [[VectorSchemaRoot]] for `schema`. */
+  def allocateRoot(
+      schema: StructType,
+      allocator: BufferAllocator = ArrowBufferAllocators.contextInstance()): 
VectorSchemaRoot = {
+    val arrowSchema = SparkArrowUtil.toArrowSchema(schema, 
SparkSchemaUtil.getLocalTimezoneID)
+    VectorSchemaRoot.create(arrowSchema, allocator)
+  }
+
+  /** Wraps `vectors`, whose ownership moves to the returned column vectors. */
+  def wrap(vectors: java.util.List[FieldVector]): 
Array[RefCountedArrowColumnVector] = {
+    vectors.asScala.map(new RefCountedArrowColumnVector(_)).toArray
+  }
+
+  /** Wraps the vectors of `root` into a batch, which owns them. */
+  def toBatch(root: VectorSchemaRoot): ColumnarBatch = {
+    new ColumnarBatch(
+      wrap(root.getFieldVectors).map(_.asInstanceOf[ColumnVector]),
+      root.getRowCount)
+  }
+
+  /** Writes `rows` into a new batch with Spark's [[ArrowWriter]]. */
+  def fromRows(
+      schema: StructType,
+      rows: Iterator[InternalRow],
+      allocator: BufferAllocator = ArrowBufferAllocators.contextInstance()): 
ColumnarBatch = {
+    val root = allocateRoot(schema, allocator)
+    try {
+      val writer = ArrowWriter.create(root)
+      rows.foreach(writer.write)
+      writer.finish()
+    } catch {
+      case t: Throwable =>
+        root.close()
+        throw t

Review Comment:
   `ArrowWriter` is created but never closed. If `ArrowWriter` holds resources 
(e.g., per-field writers / temporary state), this can leak across tasks or 
increase memory pressure. Use a structured `try/finally` so the writer is 
always closed after `finish()` (and also closed on exceptions), while still 
transferring ownership of `root` to the returned batch.



##########
gluten-arrow/src/main/scala/org/apache/gluten/vectorized/ArrowColumnVectors.scala:
##########
@@ -0,0 +1,96 @@
+/*
+ * 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.vectorized
+
+import org.apache.gluten.memory.arrow.alloc.ArrowBufferAllocators
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.execution.arrow.ArrowWriter
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.utils.{SparkArrowUtil, SparkSchemaUtil}
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+
+import org.apache.arrow.memory.BufferAllocator
+import org.apache.arrow.vector.{FieldVector, ValueVector, VectorSchemaRoot}
+import org.apache.arrow.vector.util.VectorAppender
+
+import scala.collection.JavaConverters._
+
+/** Utilities to build Gluten's Java Arrow batches of 
[[RefCountedArrowColumnVector]]s. */
+object ArrowColumnVectors {
+
+  /** Allocates an empty [[VectorSchemaRoot]] for `schema`. */
+  def allocateRoot(
+      schema: StructType,
+      allocator: BufferAllocator = ArrowBufferAllocators.contextInstance()): 
VectorSchemaRoot = {
+    val arrowSchema = SparkArrowUtil.toArrowSchema(schema, 
SparkSchemaUtil.getLocalTimezoneID)
+    VectorSchemaRoot.create(arrowSchema, allocator)
+  }
+
+  /** Wraps `vectors`, whose ownership moves to the returned column vectors. */
+  def wrap(vectors: java.util.List[FieldVector]): 
Array[RefCountedArrowColumnVector] = {
+    vectors.asScala.map(new RefCountedArrowColumnVector(_)).toArray
+  }
+
+  /** Wraps the vectors of `root` into a batch, which owns them. */
+  def toBatch(root: VectorSchemaRoot): ColumnarBatch = {
+    new ColumnarBatch(
+      wrap(root.getFieldVectors).map(_.asInstanceOf[ColumnVector]),
+      root.getRowCount)
+  }
+
+  /** Writes `rows` into a new batch with Spark's [[ArrowWriter]]. */
+  def fromRows(
+      schema: StructType,
+      rows: Iterator[InternalRow],
+      allocator: BufferAllocator = ArrowBufferAllocators.contextInstance()): 
ColumnarBatch = {
+    val root = allocateRoot(schema, allocator)
+    try {
+      val writer = ArrowWriter.create(root)
+      rows.foreach(writer.write)
+      writer.finish()
+    } catch {
+      case t: Throwable =>
+        root.close()
+        throw t
+    }
+    toBatch(root)
+  }
+
+  /**
+   * Takes ownership of `vector` in `allocator`: its buffers are moved to a 
new vector without
+   * copying when it shares the allocator's root, and copied otherwise (Arrow 
buffers can't move
+   * across allocator roots, e.g. from vectors allocated by Spark).
+   */
+  def adopt(vector: ValueVector, allocator: BufferAllocator): FieldVector = {
+    if (vector.getAllocator.getRoot == allocator.getRoot) {
+      val pair = vector.getTransferPair(allocator)
+      pair.transfer()
+      pair.getTo.asInstanceOf[FieldVector]
+    } else {
+      copy(vector, allocator)
+    }
+  }
+
+  /** Copies `vector` into a new vector in `allocator`, leaving `vector` 
unchanged. */
+  def copy(vector: ValueVector, allocator: BufferAllocator): FieldVector = {
+    val target = vector.getField.createVector(allocator)
+    target.allocateNew()

Review Comment:
   `copy` always calls `target.allocateNew()` with no sizing hints, which can 
cause avoidable reallocations when appending large vectors. Consider pre-sizing 
the target using the source’s known counts (and, for variable-width vectors, 
estimated byte size when available) before appending, to reduce 
reallocation/copy overhead during `VectorAppender`.



##########
gluten-arrow/src/main/java/org/apache/gluten/columnarbatch/ColumnarBatches.java:
##########
@@ -227,6 +266,12 @@ public static ColumnarBatch load(BufferAllocator 
allocator, ColumnarBatch input)
   }
 
   public static ColumnarBatch offload(BufferAllocator allocator, ColumnarBatch 
input) {
+    if (isForeignArrowBatch(input)) {
+      // A batch of Spark ArrowColumnVectors (e.g. the output of a Spark Arrow 
operator) is owned
+      // by its producer and only valid until the next one is requested: take 
ownership of its
+      // vectors in a Gluten batch and offload that one, leaving the input to 
its producer.
+      return offload(allocator, adopt(allocator, input));
+    }

Review Comment:
   The public contract (per existing method docs) indicates 
`offload`/`ensureOffloaded` close the input batch, but for 
`isForeignArrowBatch` the implementation explicitly leaves `input` to its 
producer (i.e., does not close it). Please update the relevant JavaDoc/comments 
on `offload` (and any callers’ expectations) to document this exception 
clearly, so callers don’t leak or double-close foreign Spark-owned batches.



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