This is an automated email from the ASF dual-hosted git repository.

nicholasjiang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/celeborn.git


The following commit(s) were added to refs/heads/main by this push:
     new 234ff2d70 [CELEBORN-2219][CIP-14] Support PushMergedData in CppClient
234ff2d70 is described below

commit 234ff2d705bd5a6c4a6603d3976af8a3615bcbf9
Author: afterincomparableyum 
<[email protected]>
AuthorDate: Wed Apr 8 11:04:32 2026 +0800

    [CELEBORN-2219][CIP-14] Support PushMergedData in CppClient
    
    ### What changes were proposed in this pull request?
    
    Implement PushMergedData functionality in the C++ client, enabling batch 
merging and pushing of shuffle data grouped by worker address.
    
    Key changes:
      - Add mergeData() and pushMergedData() to ShuffleClient, which 
accumulateper partition data batches and push them as merged payloads when the 
buffer threshold is exceeded or at mapper end.
      - Introduce DataBatches class to manage batch accumulation thread-safe 
add/take operations and size-bounded requireBatches().
      - Add PushMergedDataCallback to handle success responses (split handling, 
congestion control, MAP_ENDED) and failure responses with revive-based retry 
via submitRetryPushMergedData().
      - Add PushMergedData network message type with encoding for 
partitionUniqueIds and batchOffsets arrays.
      - Extend Encoders with encode/decode support for vector<string> and 
vector<int32_t>.
      - Add pushMergedDataAsync() to TransportClient.
      - Add unit tests for DataBatches, PushMergedData message encoding, and 
array encoders.
    
    ### Why are the changes needed?
    
    This is needed to extend the functionality of C++ Client and there is a 
Bolt dependency on it with https://github.com/bytedance/bolt/issues/370
    
    ### Does this PR resolve a correctness bug?
    
    No
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes because it is a new functionality in the c++ client
    
    ### How was this patch tested?
    
    Tested through running unit tests and compiling locally.
    
    Closes #3611 from afterincomparableyum/cpp-client/celeborn-2219.
    
    Authored-by: afterincomparableyum 
<[email protected]>
    Signed-off-by: SteNicholas <[email protected]>
---
 .../apache/celeborn/common/write/DataBatches.java  |   2 +
 cpp/celeborn/client/CMakeLists.txt                 |   2 +
 cpp/celeborn/client/ShuffleClient.cpp              | 440 +++++++++++++++++++++
 cpp/celeborn/client/ShuffleClient.h                |  57 ++-
 cpp/celeborn/client/tests/CMakeLists.txt           |   3 +-
 .../client/tests/CelebornInputStreamRetryTest.cpp  |   5 +
 cpp/celeborn/client/tests/DataBatchesTest.cpp      | 107 +++++
 cpp/celeborn/client/writer/DataBatches.cpp         |  80 ++++
 cpp/celeborn/client/writer/DataBatches.h           |  65 +++
 .../client/writer/PushMergedDataCallback.cpp       | 360 +++++++++++++++++
 .../client/writer/PushMergedDataCallback.h         |  88 +++++
 cpp/celeborn/client/writer/PushState.cpp           |  29 +-
 cpp/celeborn/client/writer/PushState.h             |  19 +
 cpp/celeborn/network/Message.cpp                   |  37 ++
 cpp/celeborn/network/Message.h                     |  47 +++
 cpp/celeborn/network/MessageDispatcher.cpp         |   6 +
 cpp/celeborn/network/TransportClient.cpp           |  36 ++
 cpp/celeborn/network/TransportClient.h             |   5 +
 cpp/celeborn/network/tests/MessageTest.cpp         |  71 ++++
 cpp/celeborn/protocol/Encoders.cpp                 |  81 ++++
 cpp/celeborn/protocol/Encoders.h                   |  20 +
 cpp/celeborn/protocol/tests/EncodersTest.cpp       |  60 +++
 22 files changed, 1617 insertions(+), 3 deletions(-)

diff --git 
a/common/src/main/java/org/apache/celeborn/common/write/DataBatches.java 
b/common/src/main/java/org/apache/celeborn/common/write/DataBatches.java
index af6358ea9..9c17682fc 100644
--- a/common/src/main/java/org/apache/celeborn/common/write/DataBatches.java
+++ b/common/src/main/java/org/apache/celeborn/common/write/DataBatches.java
@@ -59,6 +59,8 @@ public class DataBatches {
       totalSize = 0;
       return batches;
     }
+    // TODO: ArrayList.remove(0) in a loop is O(n^2) due to element shifting.
+    // Investigate subList(0, count).clear() or use LinkedList/ArrayDeque.
     ArrayList<DataBatch> retBatches = new ArrayList<>();
     int currentSize = 0;
     while (currentSize < requestSize) {
diff --git a/cpp/celeborn/client/CMakeLists.txt 
b/cpp/celeborn/client/CMakeLists.txt
index 112b1f38d..ed00e673a 100644
--- a/cpp/celeborn/client/CMakeLists.txt
+++ b/cpp/celeborn/client/CMakeLists.txt
@@ -20,6 +20,8 @@ add_library(
         writer/PushStrategy.cpp
         writer/ReviveManager.cpp
         writer/PushDataCallback.cpp
+        writer/PushMergedDataCallback.cpp
+        writer/DataBatches.cpp
         ShuffleClient.cpp
         compress/Decompressor.cpp
         compress/Lz4Decompressor.cpp
diff --git a/cpp/celeborn/client/ShuffleClient.cpp 
b/cpp/celeborn/client/ShuffleClient.cpp
index 5f1e82dce..29ea0accf 100644
--- a/cpp/celeborn/client/ShuffleClient.cpp
+++ b/cpp/celeborn/client/ShuffleClient.cpp
@@ -18,6 +18,7 @@
 #include "celeborn/client/ShuffleClient.h"
 #include <limits>
 
+#include "celeborn/client/writer/PushMergedDataCallback.h"
 #include "celeborn/utils/CelebornUtils.h"
 
 namespace celeborn {
@@ -269,11 +270,450 @@ int ShuffleClientImpl::pushData(
   return body->remainingSize();
 }
 
+int ShuffleClientImpl::mergeData(
+    int shuffleId,
+    int mapId,
+    int attemptId,
+    int partitionId,
+    const uint8_t* data,
+    size_t offset,
+    size_t length,
+    int numMappers,
+    int numPartitions) {
+  const auto mapKey = utils::makeMapKey(shuffleId, mapId, attemptId);
+  if (checkMapperEnded(shuffleId, mapId, mapKey)) {
+    return 0;
+  }
+
+  auto partitionLocationMap =
+      getPartitionLocation(shuffleId, numMappers, numPartitions);
+  CELEBORN_CHECK_NOT_NULL(partitionLocationMap);
+  auto partitionLocationOptional = partitionLocationMap->get(partitionId);
+  if (!partitionLocationOptional.has_value()) {
+    if (!revive(
+            shuffleId,
+            mapId,
+            attemptId,
+            partitionId,
+            -1,
+            nullptr,
+            protocol::StatusCode::PUSH_DATA_FAIL_NON_CRITICAL_CAUSE)) {
+      CELEBORN_FAIL(fmt::format(
+          "Revive for shuffleId {} partitionId {} failed.",
+          shuffleId,
+          partitionId));
+    }
+    partitionLocationOptional = partitionLocationMap->get(partitionId);
+  }
+  if (checkMapperEnded(shuffleId, mapId, mapKey)) {
+    return 0;
+  }
+
+  CELEBORN_CHECK(partitionLocationOptional.has_value());
+  auto partitionLocation = partitionLocationOptional.value();
+  auto pushState = getPushState(mapKey);
+  const int nextBatchId = pushState->nextBatchId();
+
+  CELEBORN_CHECK(
+      length <= static_cast<size_t>(std::numeric_limits<int>::max()),
+      fmt::format(
+          "Data length {} exceeds maximum supported size {}",
+          length,
+          std::numeric_limits<int>::max()));
+
+  const uint8_t* dataToWrite = data + offset;
+  int lengthToWrite = static_cast<int>(length);
+  std::unique_ptr<uint8_t[]> compressedBuffer;
+
+  if (shuffleCompressionEnabled_ && compressorFactory_) {
+    auto compressor = compressorFactory_();
+    const size_t compressedCapacity =
+        compressor->getDstCapacity(static_cast<int>(length));
+    compressedBuffer = std::make_unique<uint8_t[]>(compressedCapacity);
+    const size_t compressedSize = compressor->compress(
+        dataToWrite, 0, static_cast<int>(length), compressedBuffer.get(), 0);
+
+    CELEBORN_CHECK(
+        compressedSize <= static_cast<size_t>(std::numeric_limits<int>::max()),
+        fmt::format(
+            "Compressed size {} exceeds maximum supported size {}",
+            compressedSize,
+            std::numeric_limits<int>::max()));
+
+    lengthToWrite = static_cast<int>(compressedSize);
+    dataToWrite = compressedBuffer.get();
+  }
+
+  CELEBORN_CHECK(
+      static_cast<size_t>(lengthToWrite) <=
+          std::numeric_limits<size_t>::max() - kBatchHeaderSize,
+      fmt::format(
+          "Buffer size {} + header {} would overflow",
+          lengthToWrite,
+          kBatchHeaderSize));
+
+  auto writeBuffer = memory::ByteBuffer::createWriteOnly(
+      kBatchHeaderSize + static_cast<size_t>(lengthToWrite));
+  writeBuffer->writeLE<int>(mapId);
+  writeBuffer->writeLE<int>(attemptId);
+  writeBuffer->writeLE<int>(nextBatchId);
+  writeBuffer->writeLE<int>(lengthToWrite);
+  writeBuffer->writeFromBuffer(
+      dataToWrite, 0, static_cast<size_t>(lengthToWrite));
+
+  auto body = memory::ByteBuffer::toReadOnly(std::move(writeBuffer));
+  auto addressPairKey = genAddressPairKey(*partitionLocation);
+
+  bool shouldPush = pushState->addBatchData(
+      addressPairKey, partitionLocation, nextBatchId, std::move(body));
+
+  if (shouldPush) {
+    auto dataBatches = pushState->takeDataBatches(addressPairKey);
+    if (dataBatches) {
+      auto hostAndPushPort = partitionLocation->hostAndPushPort();
+      doPushMergedData(
+          hostAndPushPort,
+          shuffleId,
+          mapId,
+          attemptId,
+          numMappers,
+          numPartitions,
+          mapKey,
+          dataBatches->requireBatches(),
+          pushState,
+          conf_->clientPushMaxReviveTimes());
+    }
+  }
+
+  CELEBORN_CHECK_LE(
+      lengthToWrite,
+      std::numeric_limits<int>::max() - static_cast<int>(kBatchHeaderSize),
+      "Batch bytes size {} + header {} would overflow int",
+      lengthToWrite,
+      kBatchHeaderSize);
+  return static_cast<int>(kBatchHeaderSize) + lengthToWrite;
+}
+
+void ShuffleClientImpl::pushMergedData(
+    int shuffleId,
+    int mapId,
+    int attemptId) {
+  const auto mapKey = utils::makeMapKey(shuffleId, mapId, attemptId);
+  auto pushState = getPushState(mapKey);
+  int pushBufferMaxSize = conf_->clientPushBufferMaxSize();
+
+  auto& batchesMap = pushState->getBatchesMap();
+  std::vector<std::string> keys;
+  batchesMap.forEach(
+      [&keys](const std::string& key, const std::shared_ptr<DataBatches>&) {
+        keys.push_back(key);
+      });
+
+  for (const auto& addressPairKey : keys) {
+    auto dataBatches = pushState->takeDataBatches(addressPairKey);
+    if (!dataBatches) {
+      continue;
+    }
+    while (dataBatches->getTotalSize() > 0) {
+      auto batches = dataBatches->requireBatches(pushBufferMaxSize);
+      if (batches.empty()) {
+        break;
+      }
+      auto hostAndPushPort = batches.front().loc->hostAndPushPort();
+      doPushMergedData(
+          hostAndPushPort,
+          shuffleId,
+          mapId,
+          attemptId,
+          0,
+          0,
+          mapKey,
+          std::move(batches),
+          pushState,
+          conf_->clientPushMaxReviveTimes());
+    }
+  }
+}
+
+void ShuffleClientImpl::doPushMergedData(
+    const std::string& hostAndPushPort,
+    int shuffleId,
+    int mapId,
+    int attemptId,
+    int numMappers,
+    int numPartitions,
+    const std::string& mapKey,
+    std::vector<DataBatch> batches,
+    std::shared_ptr<PushState> pushState,
+    int remainReviveTimes) {
+  if (batches.empty()) {
+    return;
+  }
+
+  int groupedBatchId = pushState->nextBatchId();
+  int groupedBatchBytesSize = 0;
+  for (const auto& batch : batches) {
+    CELEBORN_CHECK_LE(
+        batch.body->size(),
+        static_cast<size_t>(INT_MAX),
+        "Batch body size {} exceeds INT_MAX",
+        batch.body->size());
+    int bodySize = static_cast<int>(batch.body->size());
+    CELEBORN_CHECK_LE(
+        bodySize,
+        INT_MAX - groupedBatchBytesSize,
+        "Grouped batch size would overflow: adding {} to {}",
+        bodySize,
+        groupedBatchBytesSize);
+    groupedBatchBytesSize += bodySize;
+  }
+
+  limitMaxInFlight(mapKey, *pushState, hostAndPushPort);
+  pushState->addBatch(groupedBatchId, groupedBatchBytesSize, hostAndPushPort);
+
+  const int numBatches = static_cast<int>(batches.size());
+  std::vector<int> partitionIds(numBatches);
+  std::vector<std::string> partitionUniqueIds(numBatches);
+  std::vector<int32_t> offsets(numBatches);
+  int currentSize = 0;
+
+  // TODO: Each clone() + concat() copies data. Java avoids this with Netty's
+  // zero-copy CompositeByteBuf. We need to build something like an IOBuf chain
+  // directly (ex: via appendToChain) to eliminate the double-clone and O(n^2)
+  // re-copy from repeated pairwise concat.
+  std::vector<std::unique_ptr<memory::ReadOnlyByteBuffer>> bodyParts;
+  for (int i = 0; i < numBatches; i++) {
+    partitionIds[i] = batches[i].loc->id;
+    partitionUniqueIds[i] = batches[i].loc->uniqueId();
+    offsets[i] = currentSize;
+    int bodySize = static_cast<int>(batches[i].body->size());
+    CELEBORN_DCHECK_LE(bodySize, INT_MAX - currentSize);
+    currentSize += bodySize;
+    bodyParts.push_back(batches[i].body->clone());
+  }
+
+  // Concatenate all bodies
+  std::unique_ptr<memory::ReadOnlyByteBuffer> mergedBody;
+  if (bodyParts.size() == 1) {
+    mergedBody = std::move(bodyParts[0]);
+  } else {
+    mergedBody = memory::ByteBuffer::concat(*bodyParts[0], *bodyParts[1]);
+    for (size_t i = 2; i < bodyParts.size(); i++) {
+      mergedBody = memory::ByteBuffer::concat(*mergedBody, *bodyParts[i]);
+    }
+  }
+
+  auto shuffleKey = utils::makeShuffleKey(appUniqueId_, shuffleId);
+  network::PushMergedData pushMergedData(
+      network::Message::nextRequestId(),
+      protocol::PartitionLocation::Mode::PRIMARY,
+      shuffleKey,
+      std::move(partitionUniqueIds),
+      std::move(offsets),
+      std::move(mergedBody));
+
+  auto callback = PushMergedDataCallback::create(
+      shuffleId,
+      mapId,
+      attemptId,
+      numMappers,
+      numPartitions,
+      mapKey,
+      hostAndPushPort,
+      groupedBatchId,
+      std::move(batches),
+      std::move(partitionIds),
+      pushState,
+      weak_from_this(),
+      remainReviveTimes);
+
+  // Use the destination host and port from the first batch's location instead
+  // of parsing hostAndPushPort, to correctly handle IPv6 and avoid parse
+  // errors.
+  const auto& firstLoc = *callback->batches().front().loc;
+  const auto& host = firstLoc.host;
+  auto port = static_cast<uint16_t>(firstLoc.pushPort);
+
+  auto client = clientFactory_->createClient(host, port);
+  client->pushMergedDataAsync(
+      pushMergedData, conf_->clientPushDataTimeout(), callback);
+}
+
+void ShuffleClientImpl::submitRetryPushMergedData(
+    int shuffleId,
+    int mapId,
+    int attemptId,
+    int numMappers,
+    int numPartitions,
+    const std::string& mapKey,
+    std::vector<DataBatch> batches,
+    std::vector<std::shared_ptr<protocol::ReviveRequest>> reviveRequests,
+    int oldGroupedBatchId,
+    std::shared_ptr<PushState> pushState,
+    int remainReviveTimes,
+    long reviveResponseDueTimeMs) {
+  addPushDataRetryTask([weakClient = weak_from_this(),
+                        shuffleId,
+                        mapId,
+                        attemptId,
+                        numMappers,
+                        numPartitions,
+                        mapKey,
+                        batches = std::make_shared<std::vector<DataBatch>>(
+                            std::move(batches)),
+                        reviveRequests = std::make_shared<std::vector<
+                            std::shared_ptr<protocol::ReviveRequest>>>(
+                            std::move(reviveRequests)),
+                        oldGroupedBatchId,
+                        pushState,
+                        remainReviveTimes,
+                        reviveResponseDueTimeMs]() mutable {
+    auto sharedClient = weakClient.lock();
+    if (!sharedClient) {
+      LOG(WARNING)
+          << "ShuffleClientImpl has expired in submitRetryPushMergedData.";
+      return;
+    }
+
+    long reviveWaitTimeMs =
+        reviveResponseDueTimeMs - utils::currentTimeMillis();
+    long accumulatedTimeMs = 0;
+    const long deltaMs = 50;
+
+    // Wait for all revive requests to complete
+    for (size_t i = 0; i < reviveRequests->size(); i++) {
+      while ((*reviveRequests)[i]->reviveStatus.load() ==
+                 protocol::StatusCode::REVIVE_INITIALIZED &&
+             accumulatedTimeMs <= reviveWaitTimeMs) {
+        std::this_thread::sleep_for(utils::MS(deltaMs));
+        accumulatedTimeMs += deltaMs;
+      }
+    }
+
+    // Group successful batches by new address pair
+    std::unordered_map<std::string, std::vector<DataBatch>> 
newBatchesByAddress;
+    std::vector<DataBatch> failedBatches;
+    std::vector<std::shared_ptr<protocol::ReviveRequest>> failedRequests;
+
+    for (size_t i = 0; i < reviveRequests->size(); i++) {
+      auto& request = (*reviveRequests)[i];
+      auto& batch = (*batches)[i];
+
+      if (sharedClient->mapperEnded(shuffleId, mapId)) {
+        VLOG(1) << "Revive for push merged data success, but the mapper "
+                   "already ended for shuffle "
+                << shuffleId << " map " << mapId << " attempt " << attemptId
+                << " partition " << request->partitionId << " groupedBatch "
+                << oldGroupedBatchId << ".";
+        continue;
+      }
+
+      if (request->reviveStatus.load() == protocol::StatusCode::SUCCESS) {
+        auto locationMapOptional =
+            sharedClient->partitionLocationMaps_.get(shuffleId);
+        if (locationMapOptional.has_value()) {
+          auto newLocOptional =
+              locationMapOptional.value()->get(request->partitionId);
+          if (newLocOptional.has_value()) {
+            auto newLoc = newLocOptional.value();
+            auto newAddressKey = ShuffleClientImpl::genAddressPairKey(*newLoc);
+            batch.loc = newLoc;
+            newBatchesByAddress[newAddressKey].push_back(std::move(batch));
+            continue;
+          }
+        }
+      }
+
+      if (remainReviveTimes > 0) {
+        failedBatches.push_back(std::move(batch));
+        failedRequests.push_back(request);
+      } else {
+        auto errorMsg = fmt::format(
+            "Revive failed while pushing merged data for shuffle {} map {} "
+            "attempt {} partition {} groupedBatch {}.",
+            shuffleId,
+            mapId,
+            attemptId,
+            request->partitionId,
+            oldGroupedBatchId);
+        
pushState->setException(std::make_unique<std::runtime_error>(errorMsg));
+      }
+    }
+
+    // Push each regrouped batch set
+    for (auto& [addressKey, newBatches] : newBatchesByAddress) {
+      auto hostPort = newBatches.front().loc->hostAndPushPort();
+      sharedClient->doPushMergedData(
+          hostPort,
+          shuffleId,
+          mapId,
+          attemptId,
+          numMappers,
+          numPartitions,
+          mapKey,
+          std::move(newBatches),
+          pushState,
+          remainReviveTimes);
+    }
+
+    if (failedBatches.empty()) {
+      if (!batches->empty() && (*batches)[0].loc) {
+        pushState->removeBatch(
+            oldGroupedBatchId, (*batches)[0].loc->hostAndPushPort());
+      }
+    } else {
+      // Re-submit failed batches with new revive requests
+      std::vector<std::shared_ptr<protocol::ReviveRequest>> newReviveRequests;
+      protocol::StatusCode cause =
+          protocol::StatusCode::PUSH_DATA_CONNECTION_EXCEPTION_PRIMARY;
+      for (size_t i = 0; i < failedBatches.size(); i++) {
+        auto reviveRequest = std::make_shared<protocol::ReviveRequest>(
+            shuffleId,
+            mapId,
+            attemptId,
+            failedBatches[i].loc->id,
+            failedBatches[i].loc->epoch,
+            failedBatches[i].loc,
+            cause);
+        sharedClient->addRequestToReviveManager(reviveRequest);
+        newReviveRequests.push_back(reviveRequest);
+      }
+
+      long newDueTimeMs = utils::currentTimeMillis() +
+          sharedClient->conf_
+                  ->clientRpcRequestPartitionLocationRpcAskTimeout() /
+              utils::MS(1);
+      sharedClient->submitRetryPushMergedData(
+          shuffleId,
+          mapId,
+          attemptId,
+          numMappers,
+          numPartitions,
+          mapKey,
+          std::move(failedBatches),
+          std::move(newReviveRequests),
+          oldGroupedBatchId,
+          pushState,
+          remainReviveTimes - 1,
+          newDueTimeMs);
+    }
+  });
+}
+
+std::string ShuffleClientImpl::genAddressPairKey(
+    const protocol::PartitionLocation& loc) {
+  if (loc.hasPeer()) {
+    return loc.hostAndPushPort() + "," + loc.getPeer()->hostAndPushPort();
+  }
+  return loc.hostAndPushPort();
+}
+
 void ShuffleClientImpl::mapperEnd(
     int shuffleId,
     int mapId,
     int attemptId,
     int numMappers) {
+  pushMergedData(shuffleId, mapId, attemptId);
   mapPartitionMapperEnd(shuffleId, mapId, attemptId, numMappers, -1);
 }
 
diff --git a/cpp/celeborn/client/ShuffleClient.h 
b/cpp/celeborn/client/ShuffleClient.h
index 0a7946d12..5881ce9ce 100644
--- a/cpp/celeborn/client/ShuffleClient.h
+++ b/cpp/celeborn/client/ShuffleClient.h
@@ -20,6 +20,7 @@
 #include <functional>
 #include "celeborn/client/compress/Compressor.h"
 #include "celeborn/client/reader/CelebornInputStream.h"
+#include "celeborn/client/writer/DataBatches.h"
 #include "celeborn/client/writer/PushDataCallback.h"
 #include "celeborn/client/writer/PushState.h"
 #include "celeborn/client/writer/ReviveManager.h"
@@ -45,7 +46,18 @@ class ShuffleClient {
       int numMappers,
       int numPartitions) = 0;
 
-  // TODO: PushMergedData is not supported yet.
+  virtual int mergeData(
+      int shuffleId,
+      int mapId,
+      int attemptId,
+      int partitionId,
+      const uint8_t* data,
+      size_t offset,
+      size_t length,
+      int numMappers,
+      int numPartitions) = 0;
+
+  virtual void pushMergedData(int shuffleId, int mapId, int attemptId) = 0;
 
   virtual void
   mapperEnd(int shuffleId, int mapId, int attemptId, int numMappers) = 0;
@@ -83,6 +95,7 @@ class ShuffleClient {
 
 class ReviveManager;
 class PushDataCallback;
+class PushMergedDataCallback;
 
 /// ShuffleClientEndpoint holds all the resources of ShuffleClient, including
 /// threadPools and clientFactories. The endpoint could be reused by multiple
@@ -107,6 +120,7 @@ class ShuffleClientImpl
  public:
   friend class ReviveManager;
   friend class PushDataCallback;
+  friend class PushMergedDataCallback;
 
   using PtrReviveRequest = std::shared_ptr<protocol::ReviveRequest>;
   using PartitionLocationMap = utils::ConcurrentHashMap<
@@ -142,6 +156,19 @@ class ShuffleClientImpl
       int numMappers,
       int numPartitions) override;
 
+  int mergeData(
+      int shuffleId,
+      int mapId,
+      int attemptId,
+      int partitionId,
+      const uint8_t* data,
+      size_t offset,
+      size_t length,
+      int numMappers,
+      int numPartitions) override;
+
+  void pushMergedData(int shuffleId, int mapId, int attemptId) override;
+
   void mapperEnd(int shuffleId, int mapId, int attemptId, int numMappers)
       override;
 
@@ -216,6 +243,20 @@ class ShuffleClientImpl
 
   virtual void addPushDataRetryTask(folly::Func&& task);
 
+  virtual void submitRetryPushMergedData(
+      int shuffleId,
+      int mapId,
+      int attemptId,
+      int numMappers,
+      int numPartitions,
+      const std::string& mapKey,
+      std::vector<DataBatch> batches,
+      std::vector<std::shared_ptr<protocol::ReviveRequest>> reviveRequests,
+      int oldGroupedBatchId,
+      std::shared_ptr<PushState> pushState,
+      int remainReviveTimes,
+      long reviveResponseDueTimeMs);
+
  private:
   std::shared_ptr<PushState> getPushState(const std::string& mapKey);
 
@@ -247,6 +288,20 @@ class ShuffleClientImpl
   // until the ongoing package num decreases to zero.
   void limitZeroInFlight(const std::string& mapKey, PushState& pushState);
 
+  void doPushMergedData(
+      const std::string& hostAndPushPort,
+      int shuffleId,
+      int mapId,
+      int attemptId,
+      int numMappers,
+      int numPartitions,
+      const std::string& mapKey,
+      std::vector<DataBatch> batches,
+      std::shared_ptr<PushState> pushState,
+      int remainReviveTimes);
+
+  static std::string genAddressPairKey(const protocol::PartitionLocation& loc);
+
   // TODO: no support for WAIT as it is not used.
   static bool newerPartitionLocationExists(
       std::shared_ptr<utils::ConcurrentHashMap<
diff --git a/cpp/celeborn/client/tests/CMakeLists.txt 
b/cpp/celeborn/client/tests/CMakeLists.txt
index 1402982e0..41c636c2e 100644
--- a/cpp/celeborn/client/tests/CMakeLists.txt
+++ b/cpp/celeborn/client/tests/CMakeLists.txt
@@ -24,7 +24,8 @@ add_executable(
         ZstdDecompressorTest.cpp
         Lz4CompressorTest.cpp
         ZstdCompressorTest.cpp
-        CompressorFactoryTest.cpp)
+        CompressorFactoryTest.cpp
+        DataBatchesTest.cpp)
 
 add_test(NAME celeborn_client_test COMMAND celeborn_client_test)
 
diff --git a/cpp/celeborn/client/tests/CelebornInputStreamRetryTest.cpp 
b/cpp/celeborn/client/tests/CelebornInputStreamRetryTest.cpp
index f37ef103a..e489787ec 100644
--- a/cpp/celeborn/client/tests/CelebornInputStreamRetryTest.cpp
+++ b/cpp/celeborn/client/tests/CelebornInputStreamRetryTest.cpp
@@ -46,6 +46,11 @@ class StubShuffleClient : public ShuffleClient {
       override {
     return 0;
   }
+  int mergeData(int, int, int, int, const uint8_t*, size_t, size_t, int, int)
+      override {
+    return 0;
+  }
+  void pushMergedData(int, int, int) override {}
   void mapperEnd(int, int, int, int) override {}
   void cleanup(int, int, int) override {}
   void updateReducerFileGroup(int) override {}
diff --git a/cpp/celeborn/client/tests/DataBatchesTest.cpp 
b/cpp/celeborn/client/tests/DataBatchesTest.cpp
new file mode 100644
index 000000000..cb9c87851
--- /dev/null
+++ b/cpp/celeborn/client/tests/DataBatchesTest.cpp
@@ -0,0 +1,107 @@
+/*
+ * 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 <gtest/gtest.h>
+
+#include "celeborn/client/writer/DataBatches.h"
+
+using namespace celeborn;
+using namespace celeborn::client;
+
+namespace {
+std::shared_ptr<const protocol::PartitionLocation> makeLocation(int id) {
+  auto loc = std::make_shared<protocol::PartitionLocation>();
+  loc->id = id;
+  loc->epoch = 0;
+  loc->host = "host1";
+  loc->pushPort = 9092;
+  loc->rpcPort = 9091;
+  loc->fetchPort = 9093;
+  loc->replicatePort = 9094;
+  loc->mode = protocol::PartitionLocation::PRIMARY;
+  return loc;
+}
+
+std::unique_ptr<memory::ReadOnlyByteBuffer> makeBody(int size) {
+  auto buf = memory::ByteBuffer::createWriteOnly(size);
+  for (int i = 0; i < size; i++) {
+    buf->write<uint8_t>(static_cast<uint8_t>(i & 0xFF));
+  }
+  return memory::ByteBuffer::toReadOnly(std::move(buf));
+}
+} // namespace
+
+TEST(DataBatchesTest, addAndGetTotalSize) {
+  DataBatches batches;
+  EXPECT_EQ(batches.getTotalSize(), 0);
+
+  batches.addDataBatch(makeLocation(0), 1, makeBody(100));
+  EXPECT_EQ(batches.getTotalSize(), 100);
+
+  batches.addDataBatch(makeLocation(1), 2, makeBody(200));
+  EXPECT_EQ(batches.getTotalSize(), 300);
+}
+
+TEST(DataBatchesTest, requireAllBatches) {
+  DataBatches batches;
+  batches.addDataBatch(makeLocation(0), 1, makeBody(50));
+  batches.addDataBatch(makeLocation(1), 2, makeBody(60));
+  batches.addDataBatch(makeLocation(2), 3, makeBody(70));
+
+  auto all = batches.requireBatches();
+  EXPECT_EQ(all.size(), 3);
+  EXPECT_EQ(all[0].batchId, 1);
+  EXPECT_EQ(all[1].batchId, 2);
+  EXPECT_EQ(all[2].batchId, 3);
+  EXPECT_EQ(batches.getTotalSize(), 0);
+}
+
+TEST(DataBatchesTest, requireBatchesWithSize) {
+  DataBatches batches;
+  batches.addDataBatch(makeLocation(0), 1, makeBody(100));
+  batches.addDataBatch(makeLocation(1), 2, makeBody(100));
+  batches.addDataBatch(makeLocation(2), 3, makeBody(100));
+
+  auto partial = batches.requireBatches(150);
+  EXPECT_EQ(partial.size(), 2);
+  EXPECT_EQ(partial[0].batchId, 1);
+  EXPECT_EQ(partial[1].batchId, 2);
+  EXPECT_EQ(batches.getTotalSize(), 100);
+
+  auto rest = batches.requireBatches(200);
+  EXPECT_EQ(rest.size(), 1);
+  EXPECT_EQ(rest[0].batchId, 3);
+  EXPECT_EQ(batches.getTotalSize(), 0);
+}
+
+TEST(DataBatchesTest, requireBatchesLargerThanTotal) {
+  DataBatches batches;
+  batches.addDataBatch(makeLocation(0), 1, makeBody(50));
+
+  auto all = batches.requireBatches(1000);
+  EXPECT_EQ(all.size(), 1);
+  EXPECT_EQ(batches.getTotalSize(), 0);
+}
+
+TEST(DataBatchesTest, emptyBatches) {
+  DataBatches batches;
+  auto all = batches.requireBatches();
+  EXPECT_EQ(all.size(), 0);
+
+  auto partial = batches.requireBatches(100);
+  EXPECT_EQ(partial.size(), 0);
+}
diff --git a/cpp/celeborn/client/writer/DataBatches.cpp 
b/cpp/celeborn/client/writer/DataBatches.cpp
new file mode 100644
index 000000000..4843d2b80
--- /dev/null
+++ b/cpp/celeborn/client/writer/DataBatches.cpp
@@ -0,0 +1,80 @@
+/*
+ * 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 "celeborn/client/writer/DataBatches.h"
+#include "celeborn/utils/Exceptions.h"
+
+namespace celeborn {
+namespace client {
+
+void DataBatches::addDataBatch(
+    std::shared_ptr<const protocol::PartitionLocation> loc,
+    int batchId,
+    std::unique_ptr<memory::ReadOnlyByteBuffer> body) {
+  std::lock_guard<std::mutex> lock(mutex_);
+  CELEBORN_CHECK_LE(
+      body->size(),
+      static_cast<size_t>(INT_MAX),
+      "Data batch body size {} exceeds INT_MAX",
+      body->size());
+  int bodySize = static_cast<int>(body->size());
+  CELEBORN_CHECK_LE(
+      bodySize,
+      INT_MAX - totalSize_,
+      "Adding batch of size {} would overflow totalSize (current: {})",
+      bodySize,
+      totalSize_);
+  batches_.emplace_back(std::move(loc), batchId, std::move(body));
+  totalSize_ += bodySize;
+}
+
+int DataBatches::getTotalSize() const {
+  std::lock_guard<std::mutex> lock(mutex_);
+  return totalSize_;
+}
+
+std::vector<DataBatch> DataBatches::requireBatches() {
+  std::lock_guard<std::mutex> lock(mutex_);
+  totalSize_ = 0;
+  return std::move(batches_);
+}
+
+std::vector<DataBatch> DataBatches::requireBatches(int requestSize) {
+  std::lock_guard<std::mutex> lock(mutex_);
+  if (requestSize >= totalSize_) {
+    totalSize_ = 0;
+    return std::move(batches_);
+  }
+  std::vector<DataBatch> result;
+  int currentSize = 0;
+  size_t count = 0;
+  while (count < batches_.size() && currentSize < requestSize) {
+    int bodySize = static_cast<int>(batches_[count].body->size());
+    currentSize += bodySize;
+    totalSize_ -= bodySize;
+    ++count;
+  }
+  result.reserve(count);
+  for (size_t i = 0; i < count; ++i) {
+    result.push_back(std::move(batches_[i]));
+  }
+  batches_.erase(batches_.begin(), batches_.begin() + count);
+  return result;
+}
+
+} // namespace client
+} // namespace celeborn
diff --git a/cpp/celeborn/client/writer/DataBatches.h 
b/cpp/celeborn/client/writer/DataBatches.h
new file mode 100644
index 000000000..5cba98c01
--- /dev/null
+++ b/cpp/celeborn/client/writer/DataBatches.h
@@ -0,0 +1,65 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <memory>
+#include <mutex>
+#include <vector>
+
+#include "celeborn/memory/ByteBuffer.h"
+#include "celeborn/protocol/PartitionLocation.h"
+
+namespace celeborn {
+namespace client {
+
+struct DataBatch {
+  std::shared_ptr<const protocol::PartitionLocation> loc;
+  int batchId;
+  std::unique_ptr<memory::ReadOnlyByteBuffer> body;
+
+  DataBatch(
+      std::shared_ptr<const protocol::PartitionLocation> loc,
+      int batchId,
+      std::unique_ptr<memory::ReadOnlyByteBuffer> body)
+      : loc(std::move(loc)), batchId(batchId), body(std::move(body)) {}
+
+  DataBatch(DataBatch&& other) noexcept = default;
+  DataBatch& operator=(DataBatch&& other) noexcept = default;
+};
+
+class DataBatches {
+ public:
+  void addDataBatch(
+      std::shared_ptr<const protocol::PartitionLocation> loc,
+      int batchId,
+      std::unique_ptr<memory::ReadOnlyByteBuffer> body);
+
+  int getTotalSize() const;
+
+  std::vector<DataBatch> requireBatches();
+
+  std::vector<DataBatch> requireBatches(int requestSize);
+
+ private:
+  mutable std::mutex mutex_;
+  int totalSize_{0};
+  std::vector<DataBatch> batches_;
+};
+
+} // namespace client
+} // namespace celeborn
diff --git a/cpp/celeborn/client/writer/PushMergedDataCallback.cpp 
b/cpp/celeborn/client/writer/PushMergedDataCallback.cpp
new file mode 100644
index 000000000..08a9fb5d4
--- /dev/null
+++ b/cpp/celeborn/client/writer/PushMergedDataCallback.cpp
@@ -0,0 +1,360 @@
+/*
+ * 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 "celeborn/client/writer/PushMergedDataCallback.h"
+#include "celeborn/conf/CelebornConf.h"
+#include "celeborn/protocol/TransportMessage.h"
+#include "celeborn/utils/Exceptions.h"
+
+namespace celeborn {
+namespace client {
+
+std::shared_ptr<PushMergedDataCallback> PushMergedDataCallback::create(
+    int shuffleId,
+    int mapId,
+    int attemptId,
+    int numMappers,
+    int numPartitions,
+    const std::string& mapKey,
+    const std::string& hostAndPushPort,
+    int groupedBatchId,
+    std::vector<DataBatch> batches,
+    std::vector<int> partitionIds,
+    std::shared_ptr<PushState> pushState,
+    std::weak_ptr<ShuffleClientImpl> weakClient,
+    int remainingReviveTimes) {
+  return std::shared_ptr<PushMergedDataCallback>(new PushMergedDataCallback(
+      shuffleId,
+      mapId,
+      attemptId,
+      numMappers,
+      numPartitions,
+      mapKey,
+      hostAndPushPort,
+      groupedBatchId,
+      std::move(batches),
+      std::move(partitionIds),
+      pushState,
+      weakClient,
+      remainingReviveTimes));
+}
+
+PushMergedDataCallback::PushMergedDataCallback(
+    int shuffleId,
+    int mapId,
+    int attemptId,
+    int numMappers,
+    int numPartitions,
+    const std::string& mapKey,
+    const std::string& hostAndPushPort,
+    int groupedBatchId,
+    std::vector<DataBatch> batches,
+    std::vector<int> partitionIds,
+    std::shared_ptr<PushState> pushState,
+    std::weak_ptr<ShuffleClientImpl> weakClient,
+    int remainingReviveTimes)
+    : shuffleId_(shuffleId),
+      mapId_(mapId),
+      attemptId_(attemptId),
+      numMappers_(numMappers),
+      numPartitions_(numPartitions),
+      mapKey_(mapKey),
+      hostAndPushPort_(hostAndPushPort),
+      groupedBatchId_(groupedBatchId),
+      batches_(std::move(batches)),
+      partitionIds_(std::move(partitionIds)),
+      pushState_(pushState),
+      weakClient_(weakClient),
+      remainingReviveTimes_(remainingReviveTimes) {}
+
+void PushMergedDataCallback::onSuccess(
+    std::unique_ptr<memory::ReadOnlyByteBuffer> response) {
+  auto sharedClient = weakClient_.lock();
+  if (!sharedClient) {
+    LOG(WARNING) << "ShuffleClientImpl has expired when "
+                    "PushMergedDataCallbackOnSuccess, ignored, shuffle "
+                 << shuffleId_ << " map " << mapId_ << " attempt " << 
attemptId_
+                 << " groupedBatch " << groupedBatchId_ << ".";
+    return;
+  }
+
+  if (response->remainingSize() <= 0) {
+    pushState_->onSuccess(hostAndPushPort_);
+    pushState_->removeBatch(groupedBatchId_, hostAndPushPort_);
+    return;
+  }
+
+  protocol::StatusCode reason =
+      static_cast<protocol::StatusCode>(response->read<uint8_t>());
+  switch (reason) {
+    case protocol::StatusCode::MAP_ENDED: {
+      auto mapperEndSet = sharedClient->mapperEndSets().computeIfAbsent(
+          shuffleId_,
+          []() { return std::make_shared<utils::ConcurrentHashSet<int>>(); });
+      mapperEndSet->insert(mapId_);
+      pushState_->onSuccess(hostAndPushPort_);
+      pushState_->removeBatch(groupedBatchId_, hostAndPushPort_);
+      break;
+    }
+    case protocol::StatusCode::HARD_SPLIT:
+    case protocol::StatusCode::SOFT_SPLIT: {
+      VLOG(1) << "Push merged data to " << hostAndPushPort_
+              << " split required for shuffle " << shuffleId_ << " map "
+              << mapId_ << " attempt " << attemptId_ << " groupedBatch "
+              << groupedBatchId_ << ".";
+
+      if (response->remainingSize() > 0) {
+        // Parse PbPushMergedDataSplitPartitionInfo from TransportMessage
+        auto transportMsg = std::make_unique<protocol::TransportMessage>(
+            response->readToReadOnlyBuffer(response->remainingSize()));
+        PbPushMergedDataSplitPartitionInfo partitionInfo;
+        if (!partitionInfo.ParseFromString(transportMsg->payload())) {
+          pushState_->setException(std::make_unique<std::runtime_error>(
+              "Failed to parse PbPushMergedDataSplitPartitionInfo"));
+          return;
+        }
+
+        CELEBORN_CHECK_EQ(
+            partitionInfo.statuscodes_size(),
+            partitionInfo.splitpartitionindexes_size(),
+            "Mismatched sizes: statuscodes {} vs splitpartitionindexes {}",
+            partitionInfo.statuscodes_size(),
+            partitionInfo.splitpartitionindexes_size());
+        const int numBatches = static_cast<int>(batches_.size());
+        for (int i = 0; i < partitionInfo.splitpartitionindexes_size(); i++) {
+          int partitionIndex = partitionInfo.splitpartitionindexes(i);
+          CELEBORN_CHECK_GE(partitionIndex, 0);
+          CELEBORN_CHECK_LT(
+              partitionIndex,
+              numBatches,
+              "Partition index {} out of range [0, {})",
+              partitionIndex,
+              numBatches);
+          int statusCode = partitionInfo.statuscodes(i);
+
+          if (statusCode ==
+              static_cast<int>(protocol::StatusCode::SOFT_SPLIT)) {
+            int partitionId = partitionIds_[partitionIndex];
+            if (!ShuffleClientImpl::newerPartitionLocationExists(
+                    sharedClient->getPartitionLocationMap(shuffleId_).value(),
+                    partitionId,
+                    batches_[partitionIndex].loc->epoch)) {
+              auto reviveRequest = std::make_shared<protocol::ReviveRequest>(
+                  shuffleId_,
+                  mapId_,
+                  attemptId_,
+                  partitionId,
+                  batches_[partitionIndex].loc->epoch,
+                  batches_[partitionIndex].loc,
+                  protocol::StatusCode::SOFT_SPLIT);
+              sharedClient->addRequestToReviveManager(reviveRequest);
+            }
+          }
+        }
+
+        // For any HARD_SPLIT partitions, need to resubmit
+        std::vector<DataBatch> batchesToRetry;
+        std::vector<std::shared_ptr<protocol::ReviveRequest>> reviveRequests;
+        for (int i = 0; i < partitionInfo.splitpartitionindexes_size(); i++) {
+          int partitionIndex = partitionInfo.splitpartitionindexes(i);
+          CELEBORN_DCHECK_GE(partitionIndex, 0);
+          CELEBORN_DCHECK_LT(partitionIndex, numBatches);
+          int statusCode = partitionInfo.statuscodes(i);
+          if (statusCode ==
+              static_cast<int>(protocol::StatusCode::HARD_SPLIT)) {
+            int partitionId = partitionIds_[partitionIndex];
+            auto reviveRequest = std::make_shared<protocol::ReviveRequest>(
+                shuffleId_,
+                mapId_,
+                attemptId_,
+                partitionId,
+                batches_[partitionIndex].loc->epoch,
+                batches_[partitionIndex].loc,
+                protocol::StatusCode::HARD_SPLIT);
+            sharedClient->addRequestToReviveManager(reviveRequest);
+            reviveRequests.push_back(reviveRequest);
+            batchesToRetry.push_back(std::move(batches_[partitionIndex]));
+          }
+        }
+
+        // TODO: when dataPushFailureTrackingEnabled and pushReplicateEnabled,
+        // call pushState_->recordFailedBatch() for each batch in
+        // batchesToRetry to support adaptive skewed partition
+        // read optimization.
+        if (!batchesToRetry.empty()) {
+          long dueTimeMs = utils::currentTimeMillis() +
+              sharedClient->conf_
+                      ->clientRpcRequestPartitionLocationRpcAskTimeout() /
+                  utils::MS(1);
+          sharedClient->submitRetryPushMergedData(
+              shuffleId_,
+              mapId_,
+              attemptId_,
+              numMappers_,
+              numPartitions_,
+              mapKey_,
+              std::move(batchesToRetry),
+              std::move(reviveRequests),
+              groupedBatchId_,
+              pushState_,
+              remainingReviveTimes_,
+              dueTimeMs);
+        } else {
+          pushState_->onSuccess(hostAndPushPort_);
+          pushState_->removeBatch(groupedBatchId_, hostAndPushPort_);
+        }
+      } else {
+        // Old worker without per-partition split info: revive all batches
+        std::vector<std::shared_ptr<protocol::ReviveRequest>> reviveRequests;
+        for (size_t i = 0; i < batches_.size(); i++) {
+          auto reviveRequest = std::make_shared<protocol::ReviveRequest>(
+              shuffleId_,
+              mapId_,
+              attemptId_,
+              partitionIds_[i],
+              batches_[i].loc->epoch,
+              batches_[i].loc,
+              reason);
+          sharedClient->addRequestToReviveManager(reviveRequest);
+          reviveRequests.push_back(reviveRequest);
+        }
+
+        long dueTimeMs = utils::currentTimeMillis() +
+            sharedClient->conf_
+                    ->clientRpcRequestPartitionLocationRpcAskTimeout() /
+                utils::MS(1);
+        sharedClient->submitRetryPushMergedData(
+            shuffleId_,
+            mapId_,
+            attemptId_,
+            numMappers_,
+            numPartitions_,
+            mapKey_,
+            std::move(batches_),
+            std::move(reviveRequests),
+            groupedBatchId_,
+            pushState_,
+            remainingReviveTimes_,
+            dueTimeMs);
+      }
+      break;
+    }
+    case protocol::StatusCode::PUSH_DATA_SUCCESS_PRIMARY_CONGESTED: {
+      VLOG(1) << "Push merged data to " << hostAndPushPort_
+              << " primary congestion for shuffle " << shuffleId_ << " map "
+              << mapId_ << " attempt " << attemptId_ << " groupedBatch "
+              << groupedBatchId_ << ".";
+      pushState_->onCongestControl(hostAndPushPort_);
+      pushState_->removeBatch(groupedBatchId_, hostAndPushPort_);
+      break;
+    }
+    case protocol::StatusCode::PUSH_DATA_SUCCESS_REPLICA_CONGESTED: {
+      VLOG(1) << "Push merged data to " << hostAndPushPort_
+              << " replicate congestion for shuffle " << shuffleId_ << " map "
+              << mapId_ << " attempt " << attemptId_ << " groupedBatch "
+              << groupedBatchId_ << ".";
+      pushState_->onCongestControl(hostAndPushPort_);
+      pushState_->removeBatch(groupedBatchId_, hostAndPushPort_);
+      break;
+    }
+    case protocol::StatusCode::SUCCESS: {
+      pushState_->onSuccess(hostAndPushPort_);
+      pushState_->removeBatch(groupedBatchId_, hostAndPushPort_);
+      break;
+    }
+    default: {
+      LOG(WARNING) << "unhandled PushMergedData success StatusCode: " << 
reason;
+      pushState_->onSuccess(hostAndPushPort_);
+      pushState_->removeBatch(groupedBatchId_, hostAndPushPort_);
+    }
+  }
+}
+
+void PushMergedDataCallback::onFailure(
+    std::unique_ptr<std::exception> exception) {
+  auto sharedClient = weakClient_.lock();
+  if (!sharedClient) {
+    LOG(WARNING) << "ShuffleClientImpl has expired when "
+                    "PushMergedDataCallbackOnFailure, ignored, shuffle "
+                 << shuffleId_ << " map " << mapId_ << " attempt " << 
attemptId_
+                 << " groupedBatch " << groupedBatchId_ << ".";
+    return;
+  }
+  // TODO: When dataPushFailureTrackingEnabled, call
+  // pushState_->recordFailedBatch() for each batch (using
+  // partitionUniqueIds[i], mapId_, attemptId_, batchIds[i]) to support
+  // adaptive skewed read optimization
+  if (pushState_->exceptionExists()) {
+    return;
+  }
+
+  LOG(ERROR) << "Push merged data to " << hostAndPushPort_
+             << " failed for shuffle " << shuffleId_ << " map " << mapId_
+             << " attempt " << attemptId_ << " groupedBatch " << 
groupedBatchId_
+             << ", remain revive times " << remainingReviveTimes_;
+
+  if (remainingReviveTimes_ <= 0) {
+    pushState_->setException(std::move(exception));
+    return;
+  }
+
+  if (sharedClient->mapperEnded(shuffleId_, mapId_)) {
+    pushState_->removeBatch(groupedBatchId_, hostAndPushPort_);
+    LOG(INFO) << "Push merged data to " << hostAndPushPort_
+              << " failed but mapper already ended for shuffle " << shuffleId_
+              << " map " << mapId_ << " attempt " << attemptId_
+              << " groupedBatch " << groupedBatchId_ << ".";
+    return;
+  }
+
+  protocol::StatusCode cause =
+      protocol::StatusCode::PUSH_DATA_CONNECTION_EXCEPTION_PRIMARY;
+
+  std::vector<std::shared_ptr<protocol::ReviveRequest>> reviveRequests;
+  for (size_t i = 0; i < batches_.size(); i++) {
+    auto reviveRequest = std::make_shared<protocol::ReviveRequest>(
+        shuffleId_,
+        mapId_,
+        attemptId_,
+        partitionIds_[i],
+        batches_[i].loc->epoch,
+        batches_[i].loc,
+        cause);
+    sharedClient->addRequestToReviveManager(reviveRequest);
+    reviveRequests.push_back(reviveRequest);
+  }
+
+  long dueTimeMs = utils::currentTimeMillis() +
+      sharedClient->conf_->clientRpcRequestPartitionLocationRpcAskTimeout() /
+          utils::MS(1);
+  sharedClient->submitRetryPushMergedData(
+      shuffleId_,
+      mapId_,
+      attemptId_,
+      numMappers_,
+      numPartitions_,
+      mapKey_,
+      std::move(batches_),
+      std::move(reviveRequests),
+      groupedBatchId_,
+      pushState_,
+      remainingReviveTimes_ - 1,
+      dueTimeMs);
+}
+
+} // namespace client
+} // namespace celeborn
\ No newline at end of file
diff --git a/cpp/celeborn/client/writer/PushMergedDataCallback.h 
b/cpp/celeborn/client/writer/PushMergedDataCallback.h
new file mode 100644
index 000000000..d0ab67d60
--- /dev/null
+++ b/cpp/celeborn/client/writer/PushMergedDataCallback.h
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include "celeborn/client/ShuffleClient.h"
+#include "celeborn/client/writer/DataBatches.h"
+#include "celeborn/client/writer/PushState.h"
+
+namespace celeborn {
+namespace client {
+
+class ShuffleClientImpl;
+
+class PushMergedDataCallback
+    : public network::RpcResponseCallback,
+      public std::enable_shared_from_this<PushMergedDataCallback> {
+ public:
+  static std::shared_ptr<PushMergedDataCallback> create(
+      int shuffleId,
+      int mapId,
+      int attemptId,
+      int numMappers,
+      int numPartitions,
+      const std::string& mapKey,
+      const std::string& hostAndPushPort,
+      int groupedBatchId,
+      std::vector<DataBatch> batches,
+      std::vector<int> partitionIds,
+      std::shared_ptr<PushState> pushState,
+      std::weak_ptr<ShuffleClientImpl> weakClient,
+      int remainingReviveTimes);
+
+  void onSuccess(std::unique_ptr<memory::ReadOnlyByteBuffer> response) 
override;
+
+  void onFailure(std::unique_ptr<std::exception> exception) override;
+
+  const std::vector<DataBatch>& batches() const {
+    return batches_;
+  }
+
+ private:
+  PushMergedDataCallback(
+      int shuffleId,
+      int mapId,
+      int attemptId,
+      int numMappers,
+      int numPartitions,
+      const std::string& mapKey,
+      const std::string& hostAndPushPort,
+      int groupedBatchId,
+      std::vector<DataBatch> batches,
+      std::vector<int> partitionIds,
+      std::shared_ptr<PushState> pushState,
+      std::weak_ptr<ShuffleClientImpl> weakClient,
+      int remainingReviveTimes);
+
+  const int shuffleId_;
+  const int mapId_;
+  const int attemptId_;
+  const int numMappers_;
+  const int numPartitions_;
+  const std::string mapKey_;
+  const std::string hostAndPushPort_;
+  const int groupedBatchId_;
+  std::vector<DataBatch> batches_;
+  const std::vector<int> partitionIds_;
+  const std::shared_ptr<PushState> pushState_;
+  const std::weak_ptr<ShuffleClientImpl> weakClient_;
+  int remainingReviveTimes_;
+};
+
+} // namespace client
+} // namespace celeborn
diff --git a/cpp/celeborn/client/writer/PushState.cpp 
b/cpp/celeborn/client/writer/PushState.cpp
index 8b3158e36..0144e2859 100644
--- a/cpp/celeborn/client/writer/PushState.cpp
+++ b/cpp/celeborn/client/writer/PushState.cpp
@@ -29,7 +29,8 @@ PushState::PushState(const conf::CelebornConf& conf)
           conf.clientPushMaxBytesSizeInFlightEnabled()),
       maxInFlightBytesSizeTotal_(conf.clientPushMaxBytesSizeInFlightTotal()),
       maxInFlightBytesSizePerWorker_(
-          conf.clientPushMaxBytesSizeInFlightPerWorker()) {}
+          conf.clientPushMaxBytesSizeInFlightPerWorker()),
+      pushBufferMaxSize_(conf.clientPushBufferMaxSize()) {}
 
 int PushState::nextBatchId() {
   return currBatchId_.fetch_add(1);
@@ -227,6 +228,7 @@ void PushState::cleanup() {
   inflightBatchesPerAddress_.clear();
   totalInflightReqs_ = 0;
   pushStrategy_->clear();
+  batchesMap_.clear();
 
   if (maxInFlightBytesSizeEnabled_) {
     inflightBytesSizePerAddress_.clear();
@@ -235,6 +237,31 @@ void PushState::cleanup() {
   }
 }
 
+bool PushState::addBatchData(
+    const std::string& addressPairKey,
+    std::shared_ptr<const protocol::PartitionLocation> loc,
+    int batchId,
+    std::unique_ptr<memory::ReadOnlyByteBuffer> body) {
+  auto batches = batchesMap_.computeIfAbsent(
+      addressPairKey, [&]() { return std::make_shared<DataBatches>(); });
+  batches->addDataBatch(std::move(loc), batchId, std::move(body));
+  return batches->getTotalSize() > pushBufferMaxSize_;
+}
+
+std::shared_ptr<DataBatches> PushState::takeDataBatches(
+    const std::string& addressPairKey) {
+  auto removed = batchesMap_.erase(addressPairKey);
+  if (removed.has_value()) {
+    return removed.value();
+  }
+  return nullptr;
+}
+
+utils::ConcurrentHashMap<std::string, std::shared_ptr<DataBatches>>&
+PushState::getBatchesMap() {
+  return batchesMap_;
+}
+
 void PushState::throwIfExceptionExists() {
   auto exp = exception_.rlock();
   if (*exp) {
diff --git a/cpp/celeborn/client/writer/PushState.h 
b/cpp/celeborn/client/writer/PushState.h
index 38ee9607f..1af46a90d 100644
--- a/cpp/celeborn/client/writer/PushState.h
+++ b/cpp/celeborn/client/writer/PushState.h
@@ -20,6 +20,7 @@
 #include <atomic>
 #include <optional>
 
+#include "celeborn/client/writer/DataBatches.h"
 #include "celeborn/client/writer/PushStrategy.h"
 #include "celeborn/conf/CelebornConf.h"
 #include "celeborn/utils/CelebornUtils.h"
@@ -69,6 +70,21 @@ class PushState {
 
   void cleanup();
 
+  // Merge-related: accumulate batch data grouped by address pair.
+  // Returns true when totalSize for that address pair exceeds
+  // pushBufferMaxSize.
+  bool addBatchData(
+      const std::string& addressPairKey,
+      std::shared_ptr<const protocol::PartitionLocation> loc,
+      int batchId,
+      std::unique_ptr<memory::ReadOnlyByteBuffer> body);
+
+  std::shared_ptr<DataBatches> takeDataBatches(
+      const std::string& addressPairKey);
+
+  utils::ConcurrentHashMap<std::string, std::shared_ptr<DataBatches>>&
+  getBatchesMap();
+
  private:
   void throwIfExceptionExists();
 
@@ -79,6 +95,7 @@ class PushState {
   const long deltaMs_;
   const std::unique_ptr<PushStrategy> pushStrategy_;
   const int maxInFlightReqsTotal_;
+  const int pushBufferMaxSize_;
   const bool maxInFlightBytesSizeEnabled_;
   const long maxInFlightBytesSizeTotal_;
   const long maxInFlightBytesSizePerWorker_;
@@ -89,6 +106,8 @@ class PushState {
   utils::ConcurrentHashMap<std::string, std::shared_ptr<std::atomic<long>>>
       inflightBytesSizePerAddress_;
   utils::ConcurrentHashMap<int, int> inflightBatchBytesSizes_;
+  utils::ConcurrentHashMap<std::string, std::shared_ptr<DataBatches>>
+      batchesMap_;
   folly::Synchronized<std::unique_ptr<std::exception>> exception_;
   std::atomic<bool> cleaned_{false};
 };
diff --git a/cpp/celeborn/network/Message.cpp b/cpp/celeborn/network/Message.cpp
index f1d69d04d..39911849a 100644
--- a/cpp/celeborn/network/Message.cpp
+++ b/cpp/celeborn/network/Message.cpp
@@ -181,5 +181,42 @@ void 
PushData::internalEncodeTo(memory::WriteOnlyByteBuffer& buffer) const {
   protocol::encode(buffer, shuffleKey_);
   protocol::encode(buffer, partitionUniqueId_);
 }
+
+PushMergedData::PushMergedData(
+    long requestId,
+    uint8_t mode,
+    const std::string& shuffleKey,
+    std::vector<std::string> partitionUniqueIds,
+    std::vector<int32_t> batchOffsets,
+    std::unique_ptr<memory::ReadOnlyByteBuffer> body)
+    : Message(PUSH_MERGED_DATA, std::move(body)),
+      requestId_(requestId),
+      mode_(mode),
+      shuffleKey_(shuffleKey),
+      partitionUniqueIds_(std::move(partitionUniqueIds)),
+      batchOffsets_(std::move(batchOffsets)) {}
+
+PushMergedData::PushMergedData(const PushMergedData& other)
+    : Message(PUSH_MERGED_DATA, other.body()),
+      requestId_(other.requestId_),
+      mode_(other.mode_),
+      shuffleKey_(other.shuffleKey_),
+      partitionUniqueIds_(other.partitionUniqueIds_),
+      batchOffsets_(other.batchOffsets_) {}
+
+int PushMergedData::internalEncodedLength() const {
+  return sizeof(long) + sizeof(uint8_t) + protocol::encodedLength(shuffleKey_) 
+
+      protocol::encodedLength(partitionUniqueIds_) +
+      protocol::encodedLength(batchOffsets_);
+}
+
+void PushMergedData::internalEncodeTo(
+    memory::WriteOnlyByteBuffer& buffer) const {
+  buffer.write<long>(requestId_);
+  buffer.write<uint8_t>(mode_);
+  protocol::encode(buffer, shuffleKey_);
+  protocol::encode(buffer, partitionUniqueIds_);
+  protocol::encode(buffer, batchOffsets_);
+}
 } // namespace network
 } // namespace celeborn
diff --git a/cpp/celeborn/network/Message.h b/cpp/celeborn/network/Message.h
index e0944294c..3b9124138 100644
--- a/cpp/celeborn/network/Message.h
+++ b/cpp/celeborn/network/Message.h
@@ -18,6 +18,8 @@
 #pragma once
 
 #include <cstdint>
+#include <string>
+#include <vector>
 
 #include "celeborn/memory/ByteBuffer.h"
 #include "celeborn/protocol/ControlMessages.h"
@@ -275,5 +277,50 @@ class PushData : public Message {
   std::string shuffleKey_;
   std::string partitionUniqueId_;
 };
+
+class PushMergedData : public Message {
+ public:
+  PushMergedData(
+      long requestId,
+      uint8_t mode,
+      const std::string& shuffleKey,
+      std::vector<std::string> partitionUniqueIds,
+      std::vector<int32_t> batchOffsets,
+      std::unique_ptr<memory::ReadOnlyByteBuffer> body);
+
+  PushMergedData(const PushMergedData& other);
+
+  long requestId() const {
+    return requestId_;
+  }
+
+  uint8_t mode() const {
+    return mode_;
+  }
+
+  const std::string& shuffleKey() const {
+    return shuffleKey_;
+  }
+
+  const std::vector<std::string>& partitionUniqueIds() const {
+    return partitionUniqueIds_;
+  }
+
+  const std::vector<int32_t>& batchOffsets() const {
+    return batchOffsets_;
+  }
+
+ private:
+  int internalEncodedLength() const override;
+
+  void internalEncodeTo(memory::WriteOnlyByteBuffer& buffer) const override;
+
+  long requestId_;
+  // 0 for primary, 1 for replica. Ref to PartitionLocation::Mode.
+  uint8_t mode_;
+  std::string shuffleKey_;
+  std::vector<std::string> partitionUniqueIds_;
+  std::vector<int32_t> batchOffsets_;
+};
 } // namespace network
 } // namespace celeborn
diff --git a/cpp/celeborn/network/MessageDispatcher.cpp 
b/cpp/celeborn/network/MessageDispatcher.cpp
index 8dd08ec38..86ec14111 100644
--- a/cpp/celeborn/network/MessageDispatcher.cpp
+++ b/cpp/celeborn/network/MessageDispatcher.cpp
@@ -142,6 +142,12 @@ folly::Future<std::unique_ptr<Message>> 
MessageDispatcher::operator()(
       requestId = pushData->requestId();
       break;
     }
+    case Message::PUSH_MERGED_DATA: {
+      PushMergedData* pushMergedData =
+          reinterpret_cast<PushMergedData*>(toSendMsg.get());
+      requestId = pushMergedData->requestId();
+      break;
+    }
     default: {
       CELEBORN_FAIL("unsupported type");
     }
diff --git a/cpp/celeborn/network/TransportClient.cpp 
b/cpp/celeborn/network/TransportClient.cpp
index 0fa531beb..c754eecd0 100644
--- a/cpp/celeborn/network/TransportClient.cpp
+++ b/cpp/celeborn/network/TransportClient.cpp
@@ -116,6 +116,42 @@ void TransportClient::pushDataAsync(
   }
 }
 
+void TransportClient::pushMergedDataAsync(
+    const PushMergedData& pushMergedData,
+    Timeout timeout,
+    std::shared_ptr<RpcResponseCallback> callback) {
+  try {
+    auto requestMsg = std::make_unique<PushMergedData>(pushMergedData);
+    auto future = dispatcher_->sendPushDataRequest(std::move(requestMsg));
+    std::move(future)
+        .within(timeout)
+        .thenValue(
+            [_callback = callback](std::unique_ptr<Message> responseMsg) {
+              if (responseMsg->type() == Message::RPC_RESPONSE) {
+                auto rpcResponse =
+                    reinterpret_cast<RpcResponse*>(responseMsg.get());
+                _callback->onSuccess(rpcResponse->body());
+              } else {
+                _callback->onFailure(std::make_unique<std::runtime_error>(
+                    "pushMergedData return value type is not rpcResponse"));
+              }
+            })
+        .thenError([_callback = callback](const folly::exception_wrapper& e) {
+          _callback->onFailure(
+              std::make_unique<std::runtime_error>(e.what().toStdString()));
+        });
+
+  } catch (std::exception& e) {
+    auto errorMsg = fmt::format(
+        "PushMergedData failed. shuffleKey: {}, mode: {}, error message: {}",
+        pushMergedData.shuffleKey(),
+        pushMergedData.mode(),
+        e.what());
+    LOG(ERROR) << errorMsg;
+    callback->onFailure(std::make_unique<std::runtime_error>(errorMsg));
+  }
+}
+
 void TransportClient::fetchChunkAsync(
     const protocol::StreamChunkSlice& streamChunkSlice,
     const RpcRequest& request,
diff --git a/cpp/celeborn/network/TransportClient.h 
b/cpp/celeborn/network/TransportClient.h
index 78c87414c..5860f92a9 100644
--- a/cpp/celeborn/network/TransportClient.h
+++ b/cpp/celeborn/network/TransportClient.h
@@ -92,6 +92,11 @@ class TransportClient {
       Timeout timeout,
       std::shared_ptr<RpcResponseCallback> callback);
 
+  virtual void pushMergedDataAsync(
+      const PushMergedData& pushMergedData,
+      Timeout timeout,
+      std::shared_ptr<RpcResponseCallback> callback);
+
   virtual void fetchChunkAsync(
       const protocol::StreamChunkSlice& streamChunkSlice,
       const RpcRequest& request,
diff --git a/cpp/celeborn/network/tests/MessageTest.cpp 
b/cpp/celeborn/network/tests/MessageTest.cpp
index d421b5126..3e18f77cd 100644
--- a/cpp/celeborn/network/tests/MessageTest.cpp
+++ b/cpp/celeborn/network/tests/MessageTest.cpp
@@ -18,6 +18,7 @@
 #include <gtest/gtest.h>
 
 #include "celeborn/network/Message.h"
+#include "celeborn/protocol/Encoders.h"
 
 using namespace celeborn;
 using namespace celeborn::network;
@@ -184,3 +185,73 @@ TEST(MessageTest, encodePushData) {
   EXPECT_EQ(
       encodedBuffer->readToString(partitionUniqueId.size()), 
partitionUniqueId);
 }
+
+TEST(MessageTest, encodePushMergedData) {
+  const std::string body = "merged-body-data";
+  auto bodyBuffer = memory::ByteBuffer::createWriteOnly(body.size());
+  bodyBuffer->writeFromString(body);
+  const long requestId = 2000;
+  const uint8_t mode = 0;
+  const std::string shuffleKey = "test-shuffle-key";
+  std::vector<std::string> partitionUniqueIds = {"p-0", "p-1", "p-2"};
+  std::vector<int32_t> batchOffsets = {0, 5, 10};
+
+  auto pushMergedData = std::make_unique<PushMergedData>(
+      requestId,
+      mode,
+      shuffleKey,
+      partitionUniqueIds,
+      batchOffsets,
+      memory::ByteBuffer::toReadOnly(std::move(bodyBuffer)));
+
+  auto encodedBuffer = pushMergedData->encode();
+
+  int expectedEncodedLen = sizeof(long) + sizeof(uint8_t) +
+      protocol::encodedLength(shuffleKey) +
+      protocol::encodedLength(partitionUniqueIds) +
+      protocol::encodedLength(batchOffsets);
+
+  EXPECT_EQ(encodedBuffer->read<int32_t>(), expectedEncodedLen);
+  EXPECT_EQ(encodedBuffer->read<uint8_t>(), Message::Type::PUSH_MERGED_DATA);
+  EXPECT_EQ(encodedBuffer->read<int32_t>(), body.size());
+  EXPECT_EQ(encodedBuffer->read<long>(), requestId);
+  EXPECT_EQ(encodedBuffer->read<uint8_t>(), mode);
+  EXPECT_EQ(encodedBuffer->read<int32_t>(), shuffleKey.size());
+  EXPECT_EQ(encodedBuffer->readToString(shuffleKey.size()), shuffleKey);
+  EXPECT_EQ(encodedBuffer->read<int32_t>(), 3);
+  for (const auto& id : partitionUniqueIds) {
+    EXPECT_EQ(encodedBuffer->read<int32_t>(), id.size());
+    EXPECT_EQ(encodedBuffer->readToString(id.size()), id);
+  }
+  EXPECT_EQ(encodedBuffer->read<int32_t>(), 3);
+  for (auto offset : batchOffsets) {
+    EXPECT_EQ(encodedBuffer->read<int32_t>(), offset);
+  }
+  EXPECT_EQ(encodedBuffer->readToString(body.size()), body);
+}
+
+TEST(MessageTest, pushMergedDataCopyConstructor) {
+  const std::string body = "test-body";
+  auto bodyBuffer = memory::ByteBuffer::createWriteOnly(body.size());
+  bodyBuffer->writeFromString(body);
+  const long requestId = 3000;
+  std::vector<std::string> ids = {"id1", "id2"};
+  std::vector<int32_t> offsets = {0, 4};
+
+  PushMergedData original(
+      requestId,
+      0,
+      "shuffleKey",
+      ids,
+      offsets,
+      memory::ByteBuffer::toReadOnly(std::move(bodyBuffer)));
+
+  PushMergedData copy(original);
+  EXPECT_EQ(copy.requestId(), requestId);
+  EXPECT_EQ(copy.mode(), 0);
+  EXPECT_EQ(copy.shuffleKey(), "shuffleKey");
+  EXPECT_EQ(copy.partitionUniqueIds().size(), 2);
+  EXPECT_EQ(copy.partitionUniqueIds()[0], "id1");
+  EXPECT_EQ(copy.batchOffsets().size(), 2);
+  EXPECT_EQ(copy.batchOffsets()[1], 4);
+}
diff --git a/cpp/celeborn/protocol/Encoders.cpp 
b/cpp/celeborn/protocol/Encoders.cpp
index 7572ca021..7bc167e8e 100644
--- a/cpp/celeborn/protocol/Encoders.cpp
+++ b/cpp/celeborn/protocol/Encoders.cpp
@@ -16,6 +16,8 @@
  */
 
 #include "celeborn/protocol/Encoders.h"
+#include <limits>
+#include "celeborn/utils/Exceptions.h"
 
 namespace celeborn {
 namespace protocol {
@@ -33,5 +35,84 @@ std::string decode(memory::ReadOnlyByteBuffer& buffer) {
   int size = buffer.read<int>();
   return buffer.readToString(size);
 }
+
+int encodedLength(const std::vector<std::string>& arr) {
+  int total = sizeof(int);
+  for (const auto& s : arr) {
+    total += encodedLength(s);
+  }
+  return total;
+}
+
+void encode(
+    memory::WriteOnlyByteBuffer& buffer,
+    const std::vector<std::string>& arr) {
+  CELEBORN_CHECK_LE(
+      arr.size(),
+      static_cast<size_t>(std::numeric_limits<int>::max()),
+      "String array size {} exceeds INT_MAX ({})",
+      arr.size(),
+      std::numeric_limits<int>::max());
+  int count = static_cast<int>(arr.size());
+  buffer.write<int>(count);
+  for (const auto& s : arr) {
+    encode(buffer, s);
+  }
+}
+
+std::vector<std::string> decodeStringArray(memory::ReadOnlyByteBuffer& buffer) 
{
+  int count = buffer.read<int>();
+  CELEBORN_CHECK_GE(count, 0, "Invalid string array count: {}", count);
+  CELEBORN_CHECK_LE(
+      static_cast<size_t>(count),
+      buffer.remainingSize() / sizeof(int),
+      "String array count {} exceeds remaining buffer size {}",
+      count,
+      buffer.remainingSize());
+  std::vector<std::string> result;
+  result.reserve(count);
+  for (int i = 0; i < count; i++) {
+    result.push_back(decode(buffer));
+  }
+  return result;
+}
+
+int encodedLength(const std::vector<int32_t>& arr) {
+  return sizeof(int) + sizeof(int32_t) * arr.size();
+}
+
+void encode(
+    memory::WriteOnlyByteBuffer& buffer,
+    const std::vector<int32_t>& arr) {
+  CELEBORN_CHECK_LE(
+      arr.size(),
+      static_cast<size_t>(std::numeric_limits<int>::max()),
+      "Int array size {} exceeds INT_MAX ({})",
+      arr.size(),
+      std::numeric_limits<int>::max());
+  int count = static_cast<int>(arr.size());
+  buffer.write<int>(count);
+  for (auto val : arr) {
+    buffer.write<int32_t>(val);
+  }
+}
+
+std::vector<int32_t> decodeIntArray(memory::ReadOnlyByteBuffer& buffer) {
+  int count = buffer.read<int>();
+  CELEBORN_CHECK_GE(count, 0, "Invalid int array count: {}", count);
+  CELEBORN_CHECK_LE(
+      static_cast<size_t>(count),
+      buffer.remainingSize() / sizeof(int32_t),
+      "Int array count {} exceeds remaining buffer size {}",
+      count,
+      buffer.remainingSize());
+  std::vector<int32_t> result;
+  result.reserve(count);
+  for (int i = 0; i < count; i++) {
+    result.push_back(buffer.read<int32_t>());
+  }
+  return result;
+}
+
 } // namespace protocol
 } // namespace celeborn
diff --git a/cpp/celeborn/protocol/Encoders.h b/cpp/celeborn/protocol/Encoders.h
index 5e9f7d1fc..015f99c76 100644
--- a/cpp/celeborn/protocol/Encoders.h
+++ b/cpp/celeborn/protocol/Encoders.h
@@ -17,6 +17,10 @@
 
 #pragma once
 
+#include <cstdint>
+#include <string>
+#include <vector>
+
 #include "celeborn/memory/ByteBuffer.h"
 
 namespace celeborn {
@@ -28,5 +32,21 @@ void encode(memory::WriteOnlyByteBuffer& buffer, const 
std::string& msg);
 
 std::string decode(memory::ReadOnlyByteBuffer& buffer);
 
+int encodedLength(const std::vector<std::string>& arr);
+
+void encode(
+    memory::WriteOnlyByteBuffer& buffer,
+    const std::vector<std::string>& arr);
+
+std::vector<std::string> decodeStringArray(memory::ReadOnlyByteBuffer& buffer);
+
+int encodedLength(const std::vector<int32_t>& arr);
+
+void encode(
+    memory::WriteOnlyByteBuffer& buffer,
+    const std::vector<int32_t>& arr);
+
+std::vector<int32_t> decodeIntArray(memory::ReadOnlyByteBuffer& buffer);
+
 } // namespace protocol
 } // namespace celeborn
diff --git a/cpp/celeborn/protocol/tests/EncodersTest.cpp 
b/cpp/celeborn/protocol/tests/EncodersTest.cpp
index 59eb6d702..6e9564879 100644
--- a/cpp/celeborn/protocol/tests/EncodersTest.cpp
+++ b/cpp/celeborn/protocol/tests/EncodersTest.cpp
@@ -46,3 +46,63 @@ TEST(EncodersTest, decode) {
   auto readBuffer = memory::ByteBuffer::toReadOnly(std::move(writeBuffer));
   EXPECT_EQ(decode(*readBuffer), testString);
 }
+
+TEST(EncodersTest, stringArrayEncodedLength) {
+  std::vector<std::string> arr = {"hello", "world", "test"};
+  int expected = sizeof(int);
+  for (const auto& s : arr) {
+    expected += sizeof(int) + s.size();
+  }
+  EXPECT_EQ(encodedLength(arr), expected);
+}
+
+TEST(EncodersTest, stringArrayEmpty) {
+  std::vector<std::string> arr;
+  EXPECT_EQ(encodedLength(arr), sizeof(int));
+  auto writeBuffer = memory::ByteBuffer::createWriteOnly(encodedLength(arr));
+  encode(*writeBuffer, arr);
+  auto readBuffer = memory::ByteBuffer::toReadOnly(std::move(writeBuffer));
+  auto decoded = decodeStringArray(*readBuffer);
+  EXPECT_EQ(decoded.size(), 0);
+}
+
+TEST(EncodersTest, stringArrayEncodeAndDecode) {
+  std::vector<std::string> arr = {"partition-0", "partition-1", "partition-2"};
+  auto writeBuffer = memory::ByteBuffer::createWriteOnly(encodedLength(arr));
+  encode(*writeBuffer, arr);
+  auto readBuffer = memory::ByteBuffer::toReadOnly(std::move(writeBuffer));
+  auto decoded = decodeStringArray(*readBuffer);
+  EXPECT_EQ(decoded.size(), arr.size());
+  for (size_t i = 0; i < arr.size(); i++) {
+    EXPECT_EQ(decoded[i], arr[i]);
+  }
+}
+
+TEST(EncodersTest, intArrayEncodedLength) {
+  std::vector<int32_t> arr = {10, 20, 30, 40};
+  EXPECT_EQ(
+      encodedLength(arr),
+      static_cast<int>(sizeof(int) + sizeof(int32_t) * arr.size()));
+}
+
+TEST(EncodersTest, intArrayEmpty) {
+  std::vector<int32_t> arr;
+  EXPECT_EQ(encodedLength(arr), sizeof(int));
+  auto writeBuffer = memory::ByteBuffer::createWriteOnly(encodedLength(arr));
+  encode(*writeBuffer, arr);
+  auto readBuffer = memory::ByteBuffer::toReadOnly(std::move(writeBuffer));
+  auto decoded = decodeIntArray(*readBuffer);
+  EXPECT_EQ(decoded.size(), 0);
+}
+
+TEST(EncodersTest, intArrayEncodeAndDecode) {
+  std::vector<int32_t> arr = {0, 100, 250, 500};
+  auto writeBuffer = memory::ByteBuffer::createWriteOnly(encodedLength(arr));
+  encode(*writeBuffer, arr);
+  auto readBuffer = memory::ByteBuffer::toReadOnly(std::move(writeBuffer));
+  auto decoded = decodeIntArray(*readBuffer);
+  EXPECT_EQ(decoded.size(), arr.size());
+  for (size_t i = 0; i < arr.size(); i++) {
+    EXPECT_EQ(decoded[i], arr[i]);
+  }
+}

Reply via email to