Copilot commented on code in PR #13280: URL: https://github.com/apache/gluten/pull/13280#discussion_r4331598299
########## gluten-arrow/src/main/java/org/apache/gluten/vectorized/RefCountedArrowColumnVector.java: ########## @@ -0,0 +1,57 @@ +/* + * 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.arrow.vector.ValueVector; +import org.apache.spark.sql.vectorized.ArrowColumnVector; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * Spark's {@link ArrowColumnVector} with a reference count, used by Gluten's Java Arrow batches + * (see {@link org.apache.gluten.columnarbatch.ColumnarBatches}). The count starts at 1; {@link + * #retain()} increments it and {@link #close()} decrements it. The Arrow vector is released when + * the count reaches 0. + * + * <p>Reading goes through Spark's accessors. To write, fill the Arrow vectors (e.g. with Spark's + * {@code ArrowWriter}) and wrap them, see {@link ArrowColumnVectors}. + */ +public final class RefCountedArrowColumnVector extends ArrowColumnVector { + private final AtomicLong refCnt = new AtomicLong(1L); + + public RefCountedArrowColumnVector(ValueVector vector) { + super(vector); + } + + public void retain() { + refCnt.getAndIncrement(); + } + + public long refCnt() { + return refCnt.get(); + } + + @Override + public void close() { + if (refCnt.get() == 0) { + return; + } + if (refCnt.decrementAndGet() == 0) { + super.close(); + } + } +} Review Comment: `close()` is not refcount-safe under concurrent callers: two threads can both observe `refCnt.get() != 0`, then `decrementAndGet()` can drive the count negative (e.g., 0 → -1). A negative refcount prevents reaching exactly 0 again, which can leak the Arrow vector (and is generally undefined state). Use a single atomic operation (e.g., `getAndDecrement()` and check the *previous* value) or a CAS loop to ensure the refcount never underflows; optionally throw if it would go below 0 to catch lifecycle misuse. ########## gluten-arrow/src/main/java/org/apache/gluten/columnarbatch/ColumnarBatches.java: ########## @@ -227,6 +248,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)); + } if (isZeroColumnBatch(input)) { return input; } Review Comment: The comment says this path leaves the foreign input batch “to its producer”, but `adopt()` can *transfer* buffers when allocator roots match (see `ArrowColumnVectors.adopt`), which mutates/empties the producer-owned vectors even though the input batch is not closed here. For a truly producer-owned batch, this can break invariants if the producer expects the batch contents to remain readable until it decides to close/reuse. Consider making the foreign-batch adoption path always copy (never transfer) to avoid mutating the input, or update the ownership contract and ensure callers never rely on the input batch remaining valid after `offload`. ########## gluten-arrow/src/main/scala/org/apache/gluten/vectorized/ArrowColumnVectors.scala: ########## @@ -0,0 +1,85 @@ +/* + * 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) + val writer = ArrowWriter.create(root) + rows.foreach(writer.write) + writer.finish() + toBatch(root) + } Review Comment: `ArrowWriter` is created but never closed. Even if most memory is owned by the vectors, `ArrowWriter` can hold per-field state/resources and should be closed to avoid leaks across many batches and to ensure deterministic cleanup on error paths. Wrap writing in a `try/finally` (or equivalent) that closes the writer; also consider failure handling that closes `root`/vectors if batch construction fails before the returned `ColumnarBatch` assumes ownership. ########## gluten-arrow/src/main/scala/org/apache/gluten/vectorized/ArrowColumnVectors.scala: ########## @@ -0,0 +1,85 @@ +/* + * 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) + val writer = ArrowWriter.create(root) + rows.foreach(writer.write) + writer.finish() + 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 { + val target = vector.getField.createVector(allocator) + target.allocateNew() + vector.accept(new VectorAppender(target), null) + target + } + } Review Comment: In the cross-root copy path, `target.allocateNew()` uses default sizing, which can cause repeated reallocations and significant overhead when copying large vectors. Prefer sizing `target` based on the source’s value count (and, for variable-width vectors, the source buffer size) before appending to minimize reallocations. Also, ensure the adopted `target` has the expected value count after append (depending on Arrow version, `VectorAppender` may not set it), otherwise downstream exporters/readers may observe an empty vector. -- 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]
