zhztheplayer commented on code in PR #6475:
URL: https://github.com/apache/incubator-gluten/pull/6475#discussion_r1689192048


##########
cpp/velox/shuffle/VeloxShuffleReader.cc:
##########
@@ -367,47 +366,133 @@ std::shared_ptr<ColumnarBatch> 
VeloxColumnarBatchDeserializer::next() {
   return columnarBatch;
 }
 
-VeloxColumnarBatchDeserializerFactory::VeloxColumnarBatchDeserializerFactory(
+VeloxSortShuffleReaderDeserializer::VeloxSortShuffleReaderDeserializer(
+    std::shared_ptr<arrow::io::InputStream> in,
     const std::shared_ptr<arrow::Schema>& schema,
     const std::shared_ptr<arrow::util::Codec>& codec,
-    const facebook::velox::common::CompressionKind veloxCompressionType,
     const RowTypePtr& rowType,
     int32_t batchSize,
     arrow::MemoryPool* memoryPool,
-    std::shared_ptr<facebook::velox::memory::MemoryPool> veloxPool,
-    ShuffleWriterType shuffleWriterType)
-    : schema_(schema),
+    facebook::velox::memory::MemoryPool* veloxPool,
+    int64_t& deserializeTime,
+    int64_t& decompressTime)
+    : in_(std::move(in)),
+      schema_(schema),
       codec_(codec),
-      veloxCompressionType_(veloxCompressionType),
       rowType_(rowType),
       batchSize_(batchSize),
-      memoryPool_(memoryPool),
+      arrowPool_(memoryPool),
       veloxPool_(veloxPool),
-      shuffleWriterType_(shuffleWriterType) {
-  initFromSchema();
+      deserializeTime_(deserializeTime),
+      decompressTime_(decompressTime) {}
+
+std::shared_ptr<ColumnarBatch> VeloxSortShuffleReaderDeserializer::next() {
+  if (reachEos_) {
+    if (cachedRows_ > 0) {
+      return deserializeToBatch();
+    }
+    return nullptr;
+  }
+
+  if (cachedRows_ >= batchSize_) {
+    return deserializeToBatch();
+  }
+
+  while (cachedRows_ < batchSize_) {
+    uint32_t numRows;
+    GLUTEN_ASSIGN_OR_THROW(
+        auto arrowBuffers, BlockPayload::deserialize(in_.get(), schema_, 
codec_, arrowPool_, numRows, decompressTime_));
+
+    if (numRows == 0) {
+      reachEos_ = true;
+      if (cachedRows_ > 0) {
+        return deserializeToBatch();
+      }
+      return nullptr;
+    }
+    auto buffer = std::move(arrowBuffers[0]);
+    cachedInputs_.emplace_back(numRows, 
wrapInBufferViewAsOwner(buffer->data(), buffer->size(), buffer));
+    cachedRows_ += numRows;
+  }
+  return deserializeToBatch();
 }
 
-std::unique_ptr<ColumnarBatchIterator> 
VeloxColumnarBatchDeserializerFactory::createDeserializer(
-    std::shared_ptr<arrow::io::InputStream> in) {
-  if (shuffleWriterType_ == kHashShuffle) {
-    return std::make_unique<VeloxColumnarBatchDeserializer>(
-        std::move(in),
-        schema_,
-        codec_,
-        rowType_,
-        batchSize_,
-        memoryPool_,
-        veloxPool_.get(),
-        &isValidityBuffer_,
-        hasComplexType_,
-        deserializeTime_,
-        decompressTime_);
+std::shared_ptr<ColumnarBatch> 
VeloxSortShuffleReaderDeserializer::deserializeToBatch() {
+  ScopedTimer timer(&deserializeTime_);
+  std::vector<std::string_view> data;
+  data.reserve(std::min(cachedRows_, batchSize_));
+
+  uint32_t readRows = 0;
+  auto cur = cachedInputs_.begin();
+  while (readRows < batchSize_ && cur != cachedInputs_.end()) {
+    auto buffer = cur->second;
+    const auto* rawBuffer = buffer->as<char>();
+    while (rowOffset_ < cur->first && readRows < batchSize_) {
+      auto rowSize = *(uint32_t*)(rawBuffer + byteOffset_);
+      byteOffset_ += sizeof(uint32_t);
+      data.push_back(std::string_view(rawBuffer + byteOffset_, rowSize));
+      byteOffset_ += rowSize;
+      ++rowOffset_;
+      ++readRows;
+    }
+    if (rowOffset_ == cur->first) {
+      rowOffset_ = 0;
+      byteOffset_ = 0;
+      ++cur;
+    }
+  }
+  cachedRows_ -= readRows;
+  auto rowVector = facebook::velox::row::CompactRow::deserialize(data, 
rowType_, veloxPool_);
+  // Free memory.
+  auto iter = cachedInputs_.begin();
+  while (iter++ != cur) {
+    cachedInputs_.pop_front();
   }
-  return std::make_unique<VeloxShuffleReaderOutStreamWrapper>(
-      veloxPool_, rowType_, batchSize_, veloxCompressionType_, 
deserializeTime_, std::move(in));
+  return std::make_shared<VeloxColumnarBatch>(std::move(rowVector));
+}
+
+class VeloxRssSortShuffleReaderDeserializer::VeloxInputStream : public 
facebook::velox::ByteInputStream {
+ public:
+  VeloxInputStream(std::shared_ptr<arrow::io::InputStream> input, 
facebook::velox::BufferPtr buffer);
+
+  bool hasNext();
+
+  void next(bool throwIfPastEnd) override;
+
+  std::shared_ptr<arrow::io::InputStream> in_;
+  const facebook::velox::BufferPtr buffer_;
+  uint64_t offset_ = -1;
+};
+
+VeloxRssSortShuffleReaderDeserializer::VeloxInputStream::VeloxInputStream(
+    std::shared_ptr<arrow::io::InputStream> input,
+    facebook::velox::BufferPtr buffer)
+    : in_(std::move(input)), buffer_(std::move(buffer)) {
+  next(true);
 }

Review Comment:
   nit: Better to move the member function definitions to class definition?



##########
cpp/velox/shuffle/VeloxSortShuffleWriter.cc:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.
+ */
+
+#include "shuffle/VeloxSortShuffleWriter.h"
+
+#include <arrow/io/memory.h>
+
+#include "memory/ArrowMemory.h"
+#include "memory/VeloxColumnarBatch.h"
+#include "utils/Common.h"
+#include "utils/Timer.h"
+
+namespace gluten {
+
+namespace {
+constexpr uint32_t kMaskLower27Bits = (1 << 27) - 1;
+constexpr uint64_t kMaskLower40Bits = (1UL << 40) - 1;
+
+uint64_t toCompactRowId(uint32_t partitionId, uint32_t pageNumber, uint32_t 
offsetInPage) {
+  // |63 partitionId(24) |39 inputIndex(13) |26 rowIndex(27) |
+  return (uint64_t)partitionId << 40 | (uint64_t)pageNumber << 27 | 
offsetInPage;
+}
+
+uint32_t extractPartitionId(uint64_t compactRowId) {
+  return (uint32_t)(compactRowId >> 40);
+}
+
+std::pair<uint32_t, uint32_t> extractPageNumberAndOffset(uint64_t 
compactRowId) {
+  return {(compactRowId & kMaskLower40Bits) >> 27, compactRowId & 
kMaskLower27Bits};
+}
+} // namespace
+
+arrow::Result<std::shared_ptr<VeloxShuffleWriter>> 
VeloxSortShuffleWriter::create(
+    uint32_t numPartitions,
+    std::unique_ptr<PartitionWriter> partitionWriter,
+    ShuffleWriterOptions options,
+    std::shared_ptr<facebook::velox::memory::MemoryPool> veloxPool,
+    arrow::MemoryPool* arrowPool) {
+  std::shared_ptr<VeloxSortShuffleWriter> writer(new VeloxSortShuffleWriter(
+      numPartitions, std::move(partitionWriter), std::move(options), 
std::move(veloxPool), arrowPool));
+  RETURN_NOT_OK(writer->init());
+  return writer;
+}
+
+VeloxSortShuffleWriter::VeloxSortShuffleWriter(
+    uint32_t numPartitions,
+    std::unique_ptr<PartitionWriter> partitionWriter,
+    ShuffleWriterOptions options,
+    std::shared_ptr<facebook::velox::memory::MemoryPool> veloxPool,
+    arrow::MemoryPool* pool)
+    : VeloxShuffleWriter(numPartitions, std::move(partitionWriter), 
std::move(options), std::move(veloxPool), pool),
+      
allocator_{std::make_unique<facebook::velox::HashStringAllocator>(veloxPool_.get())},
+      array_{SortArray{Allocator(allocator_.get())}} {}
+
+arrow::Status VeloxSortShuffleWriter::write(std::shared_ptr<ColumnarBatch> cb, 
int64_t memLimit) {
+  ARROW_ASSIGN_OR_RAISE(auto rv, getPeeledRowVector(cb));
+  initRowType(rv);
+  RETURN_NOT_OK(insert(rv, memLimit));
+  return arrow::Status::OK();
+}
+
+arrow::Status VeloxSortShuffleWriter::stop() {
+  ARROW_RETURN_IF(evictState_ == EvictState::kUnevictable, 
arrow::Status::Invalid("Unevictable state in stop."));
+
+  EvictGuard evictGuard{evictState_};
+
+  stopped_ = true;
+  RETURN_NOT_OK(evictAllPartitions());
+  RETURN_NOT_OK(partitionWriter_->stop(&metrics_));
+  return arrow::Status::OK();
+}
+
+arrow::Status VeloxSortShuffleWriter::reclaimFixedSize(int64_t size, int64_t* 
actual) {
+  if (evictState_ == EvictState::kUnevictable || offset_ == 0) {
+    *actual = 0;
+    return arrow::Status::OK();
+  }
+  EvictGuard evictGuard{evictState_};
+  auto beforeReclaim = veloxPool_->usedBytes();
+  RETURN_NOT_OK(evictAllPartitions());
+  *actual = beforeReclaim - veloxPool_->usedBytes();
+  return arrow::Status::OK();
+}
+
+arrow::Status VeloxSortShuffleWriter::init() {
+  ARROW_RETURN_IF(
+      options_.partitioning == Partitioning::kSingle,
+      arrow::Status::Invalid("VeloxSortShuffleWriter doesn't support single 
partition."));
+  array_.resize(initialSize_);
+  return arrow::Status::OK();
+}
+
+void VeloxSortShuffleWriter::initRowType(const facebook::velox::RowVectorPtr& 
rv) {
+  if (UNLIKELY(!rowType_)) {
+    rowType_ = facebook::velox::asRowType(rv->type());
+    fixedRowSize_ = facebook::velox::row::CompactRow::fixedRowSize(rowType_);
+  }
+}
+
+arrow::Result<facebook::velox::RowVectorPtr> 
VeloxSortShuffleWriter::getPeeledRowVector(
+    const std::shared_ptr<ColumnarBatch>& cb) {
+  if (options_.partitioning == Partitioning::kRange) {
+    auto compositeBatch = 
std::dynamic_pointer_cast<CompositeColumnarBatch>(cb);

Review Comment:
   It seems that the casting highly depends on the preceding code calling 
`ColumnarBatch#compose`. Is it possible to directly call 
`VeloxColumnarBatch::from` which is more general, then operate on the output 
Velox columnar batch? Which shouldn't bring visible overhead based on my 
perspective.



##########
shims/common/src/main/scala/org/apache/gluten/GlutenConfig.scala:
##########
@@ -133,10 +133,11 @@ class GlutenConfig(conf: SQLConf) extends Logging {
       .getConfString("spark.shuffle.manager", "sort")
       .contains("UniffleShuffleManager")
 
-  def isSortBasedCelebornShuffle: Boolean =
+  def celebornShuffleWriterType: String =
     conf
-      .getConfString("spark.celeborn.client.spark.shuffle.writer", "hash")
-      .equals("sort")
+      .getConfString("spark.celeborn.client.spark.shuffle.writer", 
GLUTEN_HASH_SHUFFLE_WRITER)
+      .toLowerCase(Locale.ROOT)
+      .replace(GLUTEN_SORT_SHUFFLE_WRITER, GLUTEN_RSS_SORT_SHUFFLE_WRITER)

Review Comment:
   nit: Could move the text replacement into 
`VeloxCelebornColumnarBatchSerializer.scala`, so one knows it's native code 
that distinguishes between `sort` and `rss_sort`



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