Copilot commented on code in PR #4884:
URL: https://github.com/apache/datafusion-comet/pull/4884#discussion_r3622957210


##########
thirdparty/comet-uniffle/src/main/scala/org/apache/spark/sql/comet/uniffle/CometUniffleShuffleReader.scala:
##########
@@ -0,0 +1,240 @@
+/*
+ * 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.spark.sql.comet.uniffle
+
+import java.util
+import java.util.{Collections, Optional}
+import java.util.function.Supplier
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.spark.{InterruptibleIterator, TaskContext}
+import org.apache.spark.executor.ShuffleReadMetrics
+import org.apache.spark.shuffle.{RssShuffleHandle, RssSparkConfig}
+import org.apache.spark.shuffle.reader.RssShuffleReader
+import org.apache.spark.sql.comet.execution.shuffle.CometShuffleDependency
+import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.util.CompletionIterator
+import org.apache.uniffle.client.api.{ShuffleManagerClient, ShuffleReadClient}
+import org.apache.uniffle.client.factory.ShuffleClientFactory
+import org.apache.uniffle.common.{ShuffleDataDistributionType, 
ShuffleServerInfo}
+import org.apache.uniffle.common.compression.Codec
+import org.apache.uniffle.common.config.RssConf
+import 
org.apache.uniffle.shaded.org.roaringbitmap.longlong.Roaring64NavigableMap
+import org.apache.uniffle.storage.handler.impl.ShuffleServerReadCostTracker
+
+import org.apache.comet.Native
+import org.apache.comet.shuffle.{CometNativeShuffleReader, 
CometShuffleBlockIterator}
+import org.apache.comet.vector.NativeUtil
+
+class CometUniffleShuffleReader[K, C](
+    startPartition: Int,
+    endPartition: Int,
+    mapStartIndex: Int,
+    mapEndIndex: Int,
+    context: TaskContext,
+    rssShuffleHandle: RssShuffleHandle[K, _, C],
+    basePath: String,
+    hadoopConf: Configuration,
+    partitionNum: Int,
+    partitionToExpectBlocks: util.Map[Integer, Roaring64NavigableMap],
+    taskIdBitmap: Roaring64NavigableMap,
+    readMetrics: ShuffleReadMetrics,
+    managerClientSupplier: Supplier[ShuffleManagerClient],
+    rssConf: RssConf,
+    dataDistributionType: ShuffleDataDistributionType,
+    allPartitionToServers: util.Map[Integer, util.List[ShuffleServerInfo]])
+    extends RssShuffleReader[K, C](
+      startPartition,
+      endPartition,
+      mapStartIndex,
+      mapEndIndex,
+      context,
+      rssShuffleHandle,
+      basePath,
+      hadoopConf,
+      partitionNum,
+      partitionToExpectBlocks,
+      taskIdBitmap,
+      readMetrics,
+      managerClientSupplier,
+      rssConf,
+      dataDistributionType,
+      allPartitionToServers)
+    with CometNativeShuffleReader {
+
+  private val shuffleServerReadCostTracker = new ShuffleServerReadCostTracker
+  private val dep = 
rssShuffleHandle.getDependency.asInstanceOf[CometShuffleDependency[_, _, _]]
+
+  override def read(): Iterator[Product2[K, C]] = {
+    val nativeLib = new Native()
+    val nativeUtil = new NativeUtil()
+
+    val shuffleBlockIterator =
+      new CometUniffleShuffleBlockIterator(startPartition, endPartition, 
createShuffleReadClient)
+
+    context.addTaskCompletionListener[Unit] { _ =>
+      shuffleBlockIterator.close()
+      nativeUtil.close()
+    }
+
+    val recordIter: Iterator[(Int, ColumnarBatch)] = new Iterator[(Int, 
ColumnarBatch)]
+      with AutoCloseable {
+      private var currentBatch: ColumnarBatch = null
+
+      // To avoid calling hasNext() multiple times for the same iterator,
+      // we cache the result of the last hasNext() call.
+      private var lastHasNext: Option[Boolean] = None
+      override def hasNext: Boolean = {
+        if (lastHasNext.isDefined) {
+          return lastHasNext.get
+        }
+        lastHasNext = Some(shuffleBlockIterator.hasNext != -1)
+        lastHasNext.get
+      }
+
+      override def next(): (Int, ColumnarBatch) = {
+        lastHasNext = None
+        if (currentBatch != null) {
+          currentBatch.close()
+        }

Review Comment:
   `next()` does not validate that more data is available. If a caller invokes 
`next()` after exhaustion (or without a prior `hasNext`), this can end up 
decoding with a stale/zero `currentBlockLength` instead of throwing 
`NoSuchElementException` per the `Iterator` contract. The local shuffle path’s 
`NativeBatchDecoderIterator` guards with `if (!hasNext) throw ...`; doing the 
same here keeps behavior consistent.



##########
thirdparty/comet-uniffle/src/main/scala/org/apache/spark/sql/comet/uniffle/CometUniffleShuffleBlockIterator.scala:
##########
@@ -0,0 +1,155 @@
+/*
+ * 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.spark.sql.comet.uniffle
+
+import java.nio.{ByteBuffer, ByteOrder}
+
+import scala.annotation.tailrec
+
+import org.apache.spark.internal.Logging
+import org.apache.uniffle.client.api.ShuffleReadClient
+import org.apache.uniffle.client.response.ShuffleBlock
+
+import org.apache.comet.shuffle.CometShuffleBlockIterator
+
+class CometUniffleShuffleBlockIterator(
+    startPartition: Int,
+    endPartition: Int,
+    createShuffleReadClient: Int => ShuffleReadClient)
+    extends CometShuffleBlockIterator
+    with Logging {
+  private var currentPartition: Int = startPartition
+  private var current: ByteBuffer = _
+  private var currentShuffleReadClient: ShuffleReadClient = 
createShuffleReadClient(
+    currentPartition)
+
+  private val headerBuf = 
ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN)
+  private val INITIAL_BUFFER_SIZE = 128 * 1024
+  private var dataBuf = ByteBuffer.allocateDirect(INITIAL_BUFFER_SIZE)
+  private var currentBlockLength = 0
+
+  var currentBatchFieldCount: Int = _
+
+  override def hasNext: Int = {
+    headerBuf.clear()
+    if (!readFully(headerBuf)) {
+      if (headerBuf.position() == 0) {
+        return -1
+      }
+      throw new IllegalStateException("Unexpected end of shuffle data while 
reading block header")
+    }
+    headerBuf.flip()
+
+    val compressedLength = headerBuf.getLong
+    currentBatchFieldCount = headerBuf.getLong.toInt
+
+    // Subtract 8 because compressedLength includes the 8-byte field count we 
already read
+    val bytesToRead = compressedLength - 8
+    if (bytesToRead > Integer.MAX_VALUE) {
+      throw new IllegalStateException(
+        "Native shuffle block size of " + bytesToRead + " exceeds maximum of "
+          + Integer.MAX_VALUE + ". Try reducing 
spark.comet.columnar.shuffle.batch.size.")
+    }
+    currentBlockLength = bytesToRead.toInt
+
+    if (dataBuf.capacity < currentBlockLength) {
+      val newCapacity = Math.min(bytesToRead * 2L, Integer.MAX_VALUE).toInt
+      dataBuf = ByteBuffer.allocateDirect(newCapacity)
+    }
+    dataBuf.clear
+    dataBuf.limit(currentBlockLength)
+
+    if (!readFully(dataBuf)) {
+      throw new IllegalStateException(
+        "Unexpected end of shuffle data while reading block of length " + 
currentBlockLength)
+    }
+
+    currentBlockLength
+  }
+
+  private def readFully(target: ByteBuffer): Boolean = {
+    while (target.hasRemaining) {
+      if (current == null || !current.hasRemaining) {
+        val nextBlock = nextShuffleBlock()
+        if (nextBlock.isEmpty) {
+          return false
+        }
+        current = nextBlock.get
+      }
+
+      val oldLimit = current.limit()
+      try {
+        current.limit(current.position() + Math.min(target.remaining(), 
current.remaining()))
+        target.put(current)
+      } finally {
+        current.limit(oldLimit)
+      }
+    }
+    true
+  }
+
+  @tailrec
+  private def nextShuffleBlock(): Option[ByteBuffer] = {
+    val shuffleBlock: ShuffleBlock = if (currentShuffleReadClient != null) {
+      currentShuffleReadClient.readShuffleBlockData
+    } else {
+      null
+    }
+    val rawData = if (shuffleBlock != null) {
+      shuffleBlock.getByteBuffer
+    } else {
+      null
+    }
+    if (rawData == null) {
+      if (currentShuffleReadClient != null) {
+        currentShuffleReadClient.checkProcessedBlockIds()
+        currentShuffleReadClient.logStatics()
+        currentShuffleReadClient.close()
+        currentShuffleReadClient = null
+      }
+      currentPartition += 1
+      if (currentPartition >= endPartition) {
+        None
+      } else {
+        currentShuffleReadClient = createShuffleReadClient(currentPartition)
+        nextShuffleBlock()
+      }
+    } else {
+      Some(rawData)
+    }
+  }
+
+  override def getBuffer: ByteBuffer = dataBuf
+
+  override def getCurrentBlockLength: Int = currentBlockLength
+
+  override def close(): Unit = {
+    if (current != null) {
+      current = null
+    }
+    if (dataBuf != null) {
+      dataBuf = ByteBuffer.allocateDirect(INITIAL_BUFFER_SIZE)
+    }
+    if (currentShuffleReadClient != null) {
+      currentShuffleReadClient.close()
+      currentShuffleReadClient = null
+    }
+  }

Review Comment:
   `close()` allocates a new direct buffer (`ByteBuffer.allocateDirect`) 
instead of releasing references. This creates an extra direct allocation at 
close time and relies on GC to eventually reclaim the old buffer, which can 
increase direct-memory pressure if `close()` is invoked multiple times (for 
example via both a completion listener and an explicit close). Prefer dropping 
references (set `dataBuf = null`) and resetting lengths, without allocating a 
new buffer during close.



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